From 6a8bd7a9811414a88cf63da3a830341bb3202b74 Mon Sep 17 00:00:00 2001 From: cirix Date: Mon, 4 Nov 2013 23:23:13 +0100 Subject: [PATCH 001/785] Adding new methods in test to cover all three test cases.I have serious doubts though if undertow implements JSR 356 to full extend. --- pom.xml | 21 ----- .../websocket/binary/MyEndpointClient.java | 10 +-- .../test/WebsocketByteBufferEndpointTest.java | 84 +++++++++++++++---- .../binary/src/test/resources/arquillian.xml | 2 +- websocket/pom.xml | 16 +++- 5 files changed, 87 insertions(+), 46 deletions(-) diff --git a/pom.xml b/pom.xml index d3aed25ec..52813d3da 100644 --- a/pom.xml +++ b/pom.xml @@ -65,27 +65,6 @@ ${org.jboss.arquillian.version} test - - org.jboss.arquillian.extension - arquillian-drone-bom - 1.2.0.Final - pom - test - - - org.jboss.arquillian.graphene - graphene-webdriver - 2.0.0.Final - pom - test - - - org.jboss.arquillian.selenium - selenium-bom - 2.35.0 - pom - test - diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java index 961f38a8d..5358e3025 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java @@ -12,16 +12,16 @@ /** * @author Nikolaos Ballas - * + * */ @ClientEndpoint public class MyEndpointClient { @OnOpen - public void onOpen(Session session){ - System.out.println("[Action]->Invokint method onOpen of the class:"+this.getClass().getCanonicalName()); - try{ + public void onOpen(Session session) { + System.out.println("[Action]->Invokint method onOpen of the class:"+ this.getClass().getCanonicalName()); + try { session.getBasicRemote().sendBinary(ByteBuffer.wrap("Hello World!".getBytes())); - }catch(IOException ioe){ + } catch (IOException ioe) { ioe.printStackTrace(); } } diff --git a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java index fd35c99bc..0766dabf8 100644 --- a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java +++ b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java @@ -10,8 +10,11 @@ import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; +import javax.websocket.Session; import javax.websocket.WebSocketContainer; +import junit.framework.Assert; + import org.javaee7.websocket.binary.MyEndpointByteArray; import org.javaee7.websocket.binary.MyEndpointByteBuffer; import org.javaee7.websocket.binary.MyEndpointClient; @@ -25,37 +28,84 @@ import org.junit.runner.RunWith; /** - * @author Nikos "cirix" Ballas - * + * @author Nikos Ballas + * */ @RunWith(Arquillian.class) public class WebsocketByteBufferEndpointTest { private static final String WEBAPP_SRC = "src/main/webapp"; - + /** - * Arquillian specific method for creating a file which can be deployed while executing the test. - * @return a war file + * Arquillian specific method for creating a file which can be deployed + * while executing the test. + * + * @return a war file deployable in the jboss instance configuraed in arquillian.xml file. */ - @Deployment(testable = false) @TargetsContainer("wildfly-arquillian") - public static WebArchive createDeployment(){ - WebArchive war = ShrinkWrap.create(WebArchive.class). - addClass(MyEndpointByteBuffer.class). - addClass(MyEndpointByteArray.class). - addClass(MyEndpointInputStream.class). - addAsWebResource(new File(WEBAPP_SRC,"index.jsp")). - addAsWebResource(new File(WEBAPP_SRC,"websocket.js")); + @Deployment(testable = false) + @TargetsContainer("wildfly-arquillian") + public static WebArchive createDeployment() { + WebArchive war = ShrinkWrap.create(WebArchive.class) + .addClass(MyEndpointByteBuffer.class) + .addClass(MyEndpointByteArray.class) + .addClass(MyEndpointInputStream.class) + .addAsWebResource(new File(WEBAPP_SRC, "index.jsp")) + .addAsWebResource(new File(WEBAPP_SRC, "websocket.js")); return war; } - + /** * The basic test method for the class {@link MyEndpointByteBuffer} + * * @throws URISyntaxException * @throws DeploymentException * @throws IOException */ - @Test - public void testEndPointByteBuffer() throws URISyntaxException, DeploymentException,IOException{ + @Test + public void testEndpointByteBuffer() throws URISyntaxException,DeploymentException, IOException { + Session session = connectToServer("bytebuffer"); + Assert.assertNull(session); + } + + /** + * The basic test method for the class {@MyEndpointByteArray + * } + * + * @throws DeploymentException + * @throws IOException + * @throws URISyntaxException + */ + @Test + public void testEndpointByteArray() throws DeploymentException,IOException, URISyntaxException { + Session session = connectToServer("bytearray"); + Assert.assertNull(session); + } + + /** + * The basic test method for the class {@MyEndpointInputStream + * } + * + * @throws DeploymentException + * @throws IOException + * @throws URISyntaxException + */ + @Test + public void testEndpointInputStream() throws DeploymentException,IOException, URISyntaxException { + Session session = connectToServer("inputstream"); + Assert.assertNull(session); + } + + /** + * Method used to supply connection to the server by passing the naming of + * the websocket endpoint + * + * @param endpoint + * @return + * @throws DeploymentException + * @throws IOException + * @throws URISyntaxException + */ + public Session connectToServer(String endpoint) throws DeploymentException, IOException, URISyntaxException { WebSocketContainer wSocketContainer = ContainerProvider.getWebSocketContainer(); - wSocketContainer.connectToServer(MyEndpointClient.class, new URI("ws://localhost:8080/binary/websockeet")); + return wSocketContainer.connectToServer(MyEndpointClient.class, new URI("ws://localhost:8080/binary/" + endpoint)); } } diff --git a/websocket/binary/src/test/resources/arquillian.xml b/websocket/binary/src/test/resources/arquillian.xml index 1c56cc3b3..7498105ff 100644 --- a/websocket/binary/src/test/resources/arquillian.xml +++ b/websocket/binary/src/test/resources/arquillian.xml @@ -5,7 +5,7 @@ http://jboss.org/schema/arquillian/arquillian_1_0.xsd"> - ${serverRoot}/deployments + ${serverRoot}/standalone/deployments diff --git a/websocket/pom.xml b/websocket/pom.xml index eaf577ba1..160c49c3a 100644 --- a/websocket/pom.xml +++ b/websocket/pom.xml @@ -10,7 +10,6 @@ org.javaee7.websocket websocket-samples - 1.0-SNAPSHOT pom Java EE 7 WebSocket Samples @@ -47,5 +46,18 @@ whiteboard endpoint-singleton - + + + io.undertow + undertow-core + 1.0.0.Beta20 + test + + + io.undertow + undertow-websockets-jsr + 1.0.0.Beta20 + test + + From cff6c967da471a6b14d337ed26c060b10bd88437 Mon Sep 17 00:00:00 2001 From: cirix Date: Wed, 6 Nov 2013 01:18:38 +0100 Subject: [PATCH 002/785] Did more retries on websockets. Created PUT + GET test and deployable on jaxrs-endpoint. --- jaxrs/jaxrs-client/pom.xml | 2 - jaxrs/jaxrs-endpoint/pom.xml | 13 +++- .../endpoint/test/JaxRSEndpointTest.java | 72 +++++++++++++++++++ .../src/test/resources/arquillian.xml | 16 +++++ jaxrs/pom.xml | 3 +- pom.xml | 7 +- ....java => WebsocketBinaryEndpointTest.java} | 8 ++- .../binary/src/test/resources/arquillian.xml | 11 ++- 8 files changed, 113 insertions(+), 19 deletions(-) create mode 100644 jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java create mode 100644 jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml rename websocket/binary/src/test/java/org/javaee7/websocket/binary/test/{WebsocketByteBufferEndpointTest.java => WebsocketBinaryEndpointTest.java} (93%) diff --git a/jaxrs/jaxrs-client/pom.xml b/jaxrs/jaxrs-client/pom.xml index c1282b1cf..c32f1e47c 100644 --- a/jaxrs/jaxrs-client/pom.xml +++ b/jaxrs/jaxrs-client/pom.xml @@ -8,8 +8,6 @@ ../pom.xml - org.javaee7.jaxrs jaxrs-client - 1.0-SNAPSHOT war diff --git a/jaxrs/jaxrs-endpoint/pom.xml b/jaxrs/jaxrs-endpoint/pom.xml index fb0bc94df..e90d9a08f 100644 --- a/jaxrs/jaxrs-endpoint/pom.xml +++ b/jaxrs/jaxrs-endpoint/pom.xml @@ -8,8 +8,17 @@ ../pom.xml - org.javaee7.jaxrs jaxrs-endpoint - 1.0-SNAPSHOT war + + + + org.jboss.resteasy + resteasy-client + 3.0.5.Final + jar + test + + + diff --git a/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java b/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java new file mode 100644 index 000000000..4fe2a61f4 --- /dev/null +++ b/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java @@ -0,0 +1,72 @@ +/** + * + */ +package org.javaee7.jaxrs.endpoint.test; + +import java.net.URI; +import java.net.URISyntaxException; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; + +import junit.framework.Assert; + +import org.javaee7.jaxrs.endpoint.Database; +import org.javaee7.jaxrs.endpoint.MyApplication; +import org.javaee7.jaxrs.endpoint.MyResource; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.TargetsContainer; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.junit.InSequence; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * @author Nikolaos Ballas + * + */ +@RunWith(Arquillian.class) +public class JaxRSEndpointTest { + + private Client client = null; + + @Deployment(testable=false) @TargetsContainer("wildfly-arquillian") + public static WebArchive createDeplymentI() { + return ShrinkWrap.create(WebArchive.class, "jaxrs-endpoint.war"). + addClass(MyApplication.class). + addClass(Database.class). + addClass(MyResource.class); + } + + + @Test + @InSequence(1) + public void invokeEndpointPUTTest() throws URISyntaxException{ + WebTarget targetEndpoint= getTargetEndpoint("fruit"); + targetEndpoint.request().put(Entity.text("banana")); + } + @Test + @InSequence(2) + public void invokeEndpointGETTest() throws URISyntaxException { + WebTarget targetEndPoint = getTargetEndpoint("fruit"); + String received = targetEndPoint.request().get(String.class); + Assert.assertEquals("[banana]" ,received); + } + + /** + * The method for obtaining a target endpoint. + * @param endpointName the target endpoint name which we want to invoke + * @return a WebTarget object + * @throws URISyntaxException + */ + public WebTarget getTargetEndpoint(String endpointName) throws URISyntaxException { + if(client == null) { + client = ClientBuilder.newClient(); + } + return client.target(new URI("http://localhost:8080/jaxrs-endpoint/webresources/"+endpointName)); + } +} diff --git a/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml b/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml new file mode 100644 index 000000000..7421b0007 --- /dev/null +++ b/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml @@ -0,0 +1,16 @@ + + + + ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1}/standalone/deployments + + + + ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + \ No newline at end of file diff --git a/jaxrs/pom.xml b/jaxrs/pom.xml index a05ea812d..26b621cd4 100644 --- a/jaxrs/pom.xml +++ b/jaxrs/pom.xml @@ -8,9 +8,7 @@ ../pom.xml - org.javaee7.jaxrs jaxrs-samples - 1.0-SNAPSHOT pom Java EE 7 JAX-RS Samples @@ -53,4 +51,5 @@ readerwriter-injection + org.javaee7.jaxrs diff --git a/pom.xml b/pom.xml index 52813d3da..1cc2b5f0c 100644 --- a/pom.xml +++ b/pom.xml @@ -183,9 +183,6 @@ glassfish - - true - @@ -285,8 +282,10 @@ wildfly-arquillian + + true + - chromium-browser standalone-full.xml /opt/programs/wildfly-8.0.0.Beta1 diff --git a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java similarity index 93% rename from websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java rename to websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java index 0766dabf8..091666a5b 100644 --- a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketByteBufferEndpointTest.java +++ b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java @@ -3,12 +3,13 @@ */ package org.javaee7.websocket.binary.test; +import io.undertow.websockets.jsr.UndertowContainerProvider; + import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.Session; import javax.websocket.WebSocketContainer; @@ -32,7 +33,7 @@ * */ @RunWith(Arquillian.class) -public class WebsocketByteBufferEndpointTest { +public class WebsocketBinaryEndpointTest { private static final String WEBAPP_SRC = "src/main/webapp"; /** @@ -48,6 +49,7 @@ public static WebArchive createDeployment() { .addClass(MyEndpointByteBuffer.class) .addClass(MyEndpointByteArray.class) .addClass(MyEndpointInputStream.class) + .addClass(MyEndpointClient.class) .addAsWebResource(new File(WEBAPP_SRC, "index.jsp")) .addAsWebResource(new File(WEBAPP_SRC, "websocket.js")); return war; @@ -105,7 +107,7 @@ public void testEndpointInputStream() throws DeploymentException,IOException, UR * @throws URISyntaxException */ public Session connectToServer(String endpoint) throws DeploymentException, IOException, URISyntaxException { - WebSocketContainer wSocketContainer = ContainerProvider.getWebSocketContainer(); + WebSocketContainer wSocketContainer = UndertowContainerProvider.getWebSocketContainer(); return wSocketContainer.connectToServer(MyEndpointClient.class, new URI("ws://localhost:8080/binary/" + endpoint)); } } diff --git a/websocket/binary/src/test/resources/arquillian.xml b/websocket/binary/src/test/resources/arquillian.xml index 7498105ff..7421b0007 100644 --- a/websocket/binary/src/test/resources/arquillian.xml +++ b/websocket/binary/src/test/resources/arquillian.xml @@ -3,15 +3,14 @@ xsi:schemaLocation=" http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd"> - + - ${serverRoot}/standalone/deployments + ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1}/standalone/deployments - - + - ${serverRoot} - ${serverProfile} + ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} \ No newline at end of file From 6e8180b9f43bef225737092ce8f65a5f203bff37 Mon Sep 17 00:00:00 2001 From: cirix Date: Wed, 6 Nov 2013 01:33:24 +0100 Subject: [PATCH 003/785] Adding changes in the pom.xml --- websocket/javase-client/pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/websocket/javase-client/pom.xml b/websocket/javase-client/pom.xml index b3edff254..e521e38b9 100644 --- a/websocket/javase-client/pom.xml +++ b/websocket/javase-client/pom.xml @@ -8,9 +8,7 @@ ../pom.xml - org.javaee7.websocket javase-client - 1.0-SNAPSHOT jar - 1.3.1 - - - - - org.jboss.arquillian - arquillian-bom - ${org.jboss.arquillian.version} - test - pom - - - - - - javax - javaee-api - 7.0 - provided - - - org.apache.derby - derby - 10.8.2.2 - provided - - - junit - junit - 4.8.1 - test - - - org.jboss.arquillian.junit - arquillian-junit-container - ${org.jboss.arquillian.version} - test - - - org.jboss.arquillian.container - arquillian-container-impl-base - ${org.jboss.arquillian.version} - test - - - - - codehaus-snapshots - Codehaus Snapshots - http://nexus.codehaus.org/snapshots/ - - false - - - true - - - + + 1.7 + 3.1.0 + glassfish4x + /home/argupta/tools/glassfish-4.0 + wildfly8x + /opt/programs/wildfly-8.0.0.Beta1 + tomcat8x + weblogic12x + /Users/arungup/tools/weblogic/12c/wlserver + gfv3ee6 + 1.1.1.Final + + 1.3.1 + + + + + org.jboss.arquillian + arquillian-bom + ${org.jboss.arquillian.version} + test + pom + + + + + + javax + javaee-api + 7.0 + provided + + + org.apache.derby + derby + 10.8.2.2 + provided + + + junit + junit + 4.8.1 + test + + + org.jboss.arquillian.junit + arquillian-junit-container + ${org.jboss.arquillian.version} + test + + + org.jboss.arquillian.container + arquillian-container-impl-base + ${org.jboss.arquillian.version} + test + + + + + codehaus-snapshots + Codehaus Snapshots + http://nexus.codehaus.org/snapshots/ + + false + + + true + + + - - - codehaus-snapshots - Codehaus Snapshots - http://nexus.codehaus.org/snapshots/ - - false - - - true - - - + + + codehaus-snapshots + Codehaus Snapshots + http://nexus.codehaus.org/snapshots/ + + false + + + true + + + - - ${project.artifactId} - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - ${java.min.version} - ${java.min.version} - - - - org.apache.maven.plugins - maven-war-plugin - 2.1.1 - - false - - - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.5 - - - - - org.apache.derby - derby - - - - ${project.build.directory}/derby - - - - - - cargo.datasource.driver=org.apache.derby.jdbc.EmbeddedDriver| - cargo.datasource.url=jdbc:derby:derbyDB;create=true| - cargo.datasource.jndi=jdbc/__default| - cargo.datasource.username=APP| - cargo.datasource.password=APP - - - - - - - maven-enforcer-plugin - - - - At least Maven in version ${maven.min.version} is - required. - ${maven.min.version} - - - At least a JDK in version ${java.min.version} is - required. - ${java.min.version} - - - - - - - enforce - - - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${plugin.enforcer.version} - - - - - - - glassfish - - - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.5 - - - ${cargo.container.glassfish.id} - installed - ${cargo.container.glassfish.home} - - - - org.apache.derby - derby - none - - - - - - - - - - embedded-glassfish - - - - org.glassfish.embedded - maven-embedded-glassfish-plugin - 4.0 - - target/${project.artifactId}.war - 8080 - - 8181 - - - - - org.glassfish.main.common - simple-glassfish-api - 4.0 - - - org.glassfish.main.extras - glassfish-embedded-all - 4.0 - - - - - start - integration-test - - start - deploy - - - - stop - post-integration-test - - undeploy - stop - - - - - - - - - wildfly - - - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.wildfly.id} - installed - ${cargo.container.wildfly.home} - - - - - - - - - wildfly-arquillian - - true - - - standalone-full.xml - /opt/programs/wildfly-8.0.0.Beta1 - - - - org.wildfly - wildfly-arquillian-container-managed - 8.0.0.Beta1 - test - - - org.jboss.arquillian.protocol - arquillian-protocol-servlet - ${org.jboss.arquillian.version} - test - - - - - - src/test/resources - true - - - - - - tomcat - - - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.tomcat.id} - - http://archive.apache.org/dist/tomcat/tomcat-8/v8.0.0-RC3/bin/apache-tomcat-8.0.0-RC3.zip - - - - - - - - - weblogic - - - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.weblogic.id} - installed - ${cargo.container.weblogic.home} - - - - - - - - javadocs - - - javadocs - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.4 - - - sources - process-resources - - sources - resolve - - - javadoc - false - - - - - - - - + + ${project.artifactId} + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + ${java.min.version} + ${java.min.version} + + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + false + + + + org.codehaus.cargo + cargo-maven2-plugin + 1.4.5 + + + + + org.apache.derby + derby + + + + ${project.build.directory}/derby + + + + + + cargo.datasource.driver=org.apache.derby.jdbc.EmbeddedDriver| + cargo.datasource.url=jdbc:derby:derbyDB;create=true| + cargo.datasource.jndi=jdbc/__default| + cargo.datasource.username=APP| + cargo.datasource.password=APP + + + + + + + maven-enforcer-plugin + + + + At least Maven in version ${maven.min.version} is + required. + ${maven.min.version} + + + At least a JDK in version ${java.min.version} is + required. + ${java.min.version} + + + + + + + enforce + + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${plugin.enforcer.version} + + + + + + + glassfish + + + + org.codehaus.cargo + cargo-maven2-plugin + 1.4.5 + + + ${cargo.container.glassfish.id} + installed + ${cargo.container.glassfish.home} + + + + org.apache.derby + derby + none + + + + + + + + + + org.glassfish.tyrus + tyrus-client + 1.3 + test + + + org.glassfish.tyrus + tyrus-container-grizzly-client + 1.3 + test + + + + + embedded-glassfish + + + + org.glassfish.embedded + maven-embedded-glassfish-plugin + 4.0 + + target/${project.artifactId}.war + 8080 + + 8181 + + + + + org.glassfish.main.common + simple-glassfish-api + 4.0 + + + org.glassfish.main.extras + glassfish-embedded-all + 4.0 + + + + + start + integration-test + + start + deploy + + + + stop + post-integration-test + + undeploy + stop + + + + + + + + + wildfly + + + + org.codehaus.cargo + cargo-maven2-plugin + + + ${cargo.container.wildfly.id} + installed + ${cargo.container.wildfly.home} + + + + + + + + + wildfly-arquillian + + true + + + standalone-full.xml + /opt/programs/wildfly-8.0.0.Beta1 + + + + org.wildfly + wildfly-arquillian-container-managed + 8.0.0.Beta1 + test + + + org.jboss.arquillian.protocol + arquillian-protocol-servlet + ${org.jboss.arquillian.version} + test + + + + + + src/test/resources + true + + + + + + tomcat + + + + org.codehaus.cargo + cargo-maven2-plugin + + + ${cargo.container.tomcat.id} + + http://archive.apache.org/dist/tomcat/tomcat-8/v8.0.0-RC3/bin/apache-tomcat-8.0.0-RC3.zip + + + + + + + + + weblogic + + + + org.codehaus.cargo + cargo-maven2-plugin + + + ${cargo.container.weblogic.id} + installed + ${cargo.container.weblogic.home} + + + + + + + + javadocs + + + javadocs + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.4 + + + sources + process-resources + + sources + resolve + + + javadoc + false + + + + + + + + - - batch - cdi - concurrency - ejb - el - javamail - jaxrs - jca - jms - jpa - jta - jsf - json - servlet - validation - websocket - extra - + + batch + cdi + concurrency + ejb + el + javamail + jaxrs + jca + jms + jpa + jta + jsf + json + servlet + validation + websocket + extra + - - ${maven.min.version} - + + ${maven.min.version} + \ No newline at end of file From 6ed60ac49e912f519f3853c1b5fe57253b3bf1f0 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 10:37:47 +0100 Subject: [PATCH 023/785] Changing the indentation to 4 spaces --- .../websocket/binary/MyEndpointClient.java | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java index 5358e3025..2af6a8f90 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java @@ -1,5 +1,5 @@ /** - * + * */ package org.javaee7.websocket.binary; @@ -12,17 +12,18 @@ /** * @author Nikolaos Ballas - * + * */ @ClientEndpoint public class MyEndpointClient { - @OnOpen - public void onOpen(Session session) { - System.out.println("[Action]->Invokint method onOpen of the class:"+ this.getClass().getCanonicalName()); - try { - session.getBasicRemote().sendBinary(ByteBuffer.wrap("Hello World!".getBytes())); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } + + @OnOpen + public void onOpen(Session session) { + System.out.println("[Action]->Invokint method onOpen of the class:" + this.getClass().getCanonicalName()); + try { + session.getBasicRemote().sendBinary(ByteBuffer.wrap("Hello World!".getBytes())); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } } From 3ef5d3f8a6217018089be5de5a2c2f62f8cc9150 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 10:55:30 +0100 Subject: [PATCH 024/785] Fixing junit version number to 4.11 again --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 972150f53..e1f87a0cb 100644 --- a/pom.xml +++ b/pom.xml @@ -50,7 +50,7 @@ junit junit - 4.8.1 + 4.11 test From eea70182499c50e8cf3601bb36122644a4787bfd Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 11:39:55 +0100 Subject: [PATCH 025/785] Tests are working again, WAR can be deployed on WildFly and GlassFish. Clients are working with Tyrys/Grizzly dependencies but need to be clearly resolved for WildFly. Waiting for Undertow bug (number??) to be fixed. --- .../websocket/binary/MyEndpointByteArray.java | 7 +--- .../binary/MyEndpointByteBuffer.java | 7 ++-- .../websocket/binary/MyEndpointClient.java | 8 +++- .../binary/MyEndpointInputStream.java | 5 +-- websocket/binary/src/main/webapp/websocket.js | 3 -- .../test/WebsocketBinaryEndpointTest.java | 38 ++++++++++++------- 6 files changed, 38 insertions(+), 30 deletions(-) diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteArray.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteArray.java index 5fa566689..f69e45ff1 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteArray.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteArray.java @@ -40,9 +40,7 @@ package org.javaee7.websocket.binary; import java.io.IOException; -import java.nio.ByteBuffer; import javax.websocket.OnMessage; -import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** @@ -51,8 +49,7 @@ @ServerEndpoint("/bytearray") public class MyEndpointByteArray { @OnMessage - public void echoBinary(byte[] data, Session session) throws IOException { - System.out.println("echoBinary (byte[]): " + data); - session.getBasicRemote().sendBinary(ByteBuffer.wrap(data)); + public byte[] echoBinary(byte[] data) throws IOException { + return data; } } diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteBuffer.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteBuffer.java index d2658b6c6..8ddbaaf49 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteBuffer.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointByteBuffer.java @@ -42,7 +42,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import javax.websocket.OnMessage; -import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** @@ -51,8 +50,8 @@ @ServerEndpoint("/bytebuffer") public class MyEndpointByteBuffer { @OnMessage - public void echoBinary(ByteBuffer data, Session session) throws IOException { - System.out.println("echoBinary (ByteBuffer): " + data); - session.getBasicRemote().sendBinary(data); + public ByteBuffer echoBinary(ByteBuffer data) throws IOException { + System.out.println("echoBinary"); + return data; } } diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java index 2af6a8f90..f80f6f297 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointClient.java @@ -7,6 +7,7 @@ import java.nio.ByteBuffer; import javax.websocket.ClientEndpoint; +import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; @@ -16,14 +17,19 @@ */ @ClientEndpoint public class MyEndpointClient { + public static byte[] response; @OnOpen public void onOpen(Session session) { - System.out.println("[Action]->Invokint method onOpen of the class:" + this.getClass().getCanonicalName()); try { session.getBasicRemote().sendBinary(ByteBuffer.wrap("Hello World!".getBytes())); } catch (IOException ioe) { ioe.printStackTrace(); } } + + @OnMessage + public void processMessage(byte[] message) { + MyEndpointClient.response = message; + } } diff --git a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointInputStream.java b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointInputStream.java index a9c28a2eb..efb4db582 100644 --- a/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointInputStream.java +++ b/websocket/binary/src/main/java/org/javaee7/websocket/binary/MyEndpointInputStream.java @@ -55,9 +55,8 @@ public class MyEndpointInputStream { @OnMessage public void echoStream(InputStream stream, Session session) throws IOException { System.out.println("echoStream: " + stream); - byte[] b = new byte[8]; - int n = stream.read(b); - System.out.println("read " + n + " bytes"); + byte[] b = new byte[12]; + stream.read(b); session.getBasicRemote().sendBinary(ByteBuffer.wrap(b)); } } diff --git a/websocket/binary/src/main/webapp/websocket.js b/websocket/binary/src/main/webapp/websocket.js index 4abf26f74..3e9cbf961 100644 --- a/websocket/binary/src/main/webapp/websocket.js +++ b/websocket/binary/src/main/webapp/websocket.js @@ -68,17 +68,14 @@ var output = document.getElementById("output"); function onOpenByteArray() { console.log("onOpen (byte])"); - writeToScreen("CONNECTED (byte[])"); } function onOpenByteBuffer() { console.log("onOpen (ByteBuffer)"); - writeToScreen("CONNECTED (ByteBuffer)"); } function onOpenInputStream() { console.log("onOpen (InputStream)"); - writeToScreen("CONNECTED (InputStream)"); } function echoBinaryByteArray() { diff --git a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java index 54a73294f..8c0176364 100644 --- a/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java +++ b/websocket/binary/src/test/java/org/javaee7/websocket/binary/test/WebsocketBinaryEndpointTest.java @@ -3,7 +3,6 @@ */ package org.javaee7.websocket.binary.test; - import java.io.File; import java.io.IOException; import java.net.URI; @@ -14,8 +13,6 @@ import javax.websocket.Session; import javax.websocket.WebSocketContainer; -import static junit.framework.Assert.assertNull; - import org.javaee7.websocket.binary.MyEndpointByteArray; import org.javaee7.websocket.binary.MyEndpointByteBuffer; import org.javaee7.websocket.binary.MyEndpointClient; @@ -25,6 +22,7 @@ import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; +import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; @@ -32,10 +30,11 @@ * @author Nikos Ballas * @author Arun Gupta */ -@RunWith(Arquillian.class) +//@RunWith(Arquillian.class) public class WebsocketBinaryEndpointTest { private static final String WEBAPP_SRC = "src/main/webapp"; + private static final String RESPONSE = "Hello World!"; /** * Arquillian specific method for creating a file which can be deployed @@ -45,14 +44,13 @@ public class WebsocketBinaryEndpointTest { * arquillian.xml file. */ @Deployment(testable = false) - @TargetsContainer("wildfly-arquillian") +// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class) .addClass(MyEndpointByteBuffer.class) .addClass(MyEndpointByteArray.class) .addClass(MyEndpointInputStream.class) .addClass(MyEndpointClient.class) - .addAsWebResource(new File(WEBAPP_SRC, "index.jsp")) .addAsWebResource(new File(WEBAPP_SRC, "websocket.js")); return war; } @@ -65,9 +63,13 @@ public static WebArchive createDeployment() { * @throws IOException */ @Test - public void testEndpointByteBuffer() throws URISyntaxException, DeploymentException, IOException { + public void testEndpointByteBuffer() throws URISyntaxException, DeploymentException, IOException, InterruptedException { Session session = connectToServer("bytebuffer"); - assertNull(session); + assertNotNull(session); + System.out.println("Waiting for 2 seconds to receive response"); + Thread.sleep(2000); + assertNotNull(MyEndpointClient.response); + assertArrayEquals(RESPONSE.getBytes(), MyEndpointClient.response); } /** @@ -80,9 +82,13 @@ public void testEndpointByteBuffer() throws URISyntaxException, DeploymentExcept * @throws URISyntaxException */ @Test - public void testEndpointByteArray() throws DeploymentException, IOException, URISyntaxException { + public void testEndpointByteArray() throws DeploymentException, IOException, URISyntaxException, InterruptedException { Session session = connectToServer("bytearray"); - assertNull(session); + assertNotNull(session); + System.out.println("Waiting for 2 seconds to receive response"); + Thread.sleep(2000); + assertNotNull(MyEndpointClient.response); + assertArrayEquals(RESPONSE.getBytes(), MyEndpointClient.response); } /** @@ -95,9 +101,13 @@ public void testEndpointByteArray() throws DeploymentException, IOException, URI * @throws URISyntaxException */ @Test - public void testEndpointInputStream() throws DeploymentException, IOException, URISyntaxException { + public void testEndpointInputStream() throws DeploymentException, IOException, URISyntaxException, InterruptedException { Session session = connectToServer("inputstream"); - assertNull(session); + assertNotNull(session); + System.out.println("Waiting for 2 seconds to receive response"); + Thread.sleep(2000); + assertNotNull(MyEndpointClient.response); + assertArrayEquals(RESPONSE.getBytes(), MyEndpointClient.response); } /** @@ -111,7 +121,7 @@ public void testEndpointInputStream() throws DeploymentException, IOException, U * @throws URISyntaxException */ public Session connectToServer(String endpoint) throws DeploymentException, IOException, URISyntaxException { - WebSocketContainer wSocketContainer = ContainerProvider.getWebSocketContainer(); - return wSocketContainer.connectToServer(MyEndpointClient.class, new URI("ws://localhost:8080/binary/" + endpoint)); + WebSocketContainer container = ContainerProvider.getWebSocketContainer(); + return container.connectToServer(MyEndpointClient.class, new URI("ws://localhost:8080/binary/" + endpoint)); } } From db5c2d914c327dadaa2cdc794529ca4ec5d408bd Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 11:44:17 +0100 Subject: [PATCH 026/785] Moving the groupId along with other elements --- jaxrs/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jaxrs/pom.xml b/jaxrs/pom.xml index 1a73d97c5..7824282d3 100644 --- a/jaxrs/pom.xml +++ b/jaxrs/pom.xml @@ -8,6 +8,7 @@ ../pom.xml + org.javaee7.jaxrs jaxrs-samples pom Java EE 7 JAX-RS Samples @@ -39,6 +40,4 @@ singleton-annotation readerwriter-injection - - org.javaee7.jaxrs From 3e848bebdae9dffcff3b57af2866463715ba993c Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 11:49:09 +0100 Subject: [PATCH 027/785] RESTEasy dependency moved to parent pom in a specific profile --- jaxrs/jaxrs-endpoint/pom.xml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/jaxrs/jaxrs-endpoint/pom.xml b/jaxrs/jaxrs-endpoint/pom.xml index e90d9a08f..df573aa32 100644 --- a/jaxrs/jaxrs-endpoint/pom.xml +++ b/jaxrs/jaxrs-endpoint/pom.xml @@ -11,14 +11,4 @@ jaxrs-endpoint war - - - org.jboss.resteasy - resteasy-client - 3.0.5.Final - jar - test - - - From bc5d6e02510d57172a635dca428f735a812b0574 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 11:49:30 +0100 Subject: [PATCH 028/785] Jersey and RESTEasy dependencies are added in specific profile --- pom.xml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pom.xml b/pom.xml index e1f87a0cb..5414b3d13 100644 --- a/pom.xml +++ b/pom.xml @@ -220,6 +220,12 @@ 1.3 test + + org.glassfish.jersey.core + jersey-client + 2.4 + test + @@ -291,6 +297,15 @@ + + + org.jboss.resteasy + resteasy-client + 3.0.5.Final + jar + test + + wildfly-arquillian From ede3878d75c17aa176e6a956cf3b20c10ea86ffa Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 13:10:45 +0100 Subject: [PATCH 029/785] commenting Arquillian dependencies till it is sorted out --- .../javaee7/ejb/stateless/AccountSessionBeanTest.java | 8 +++----- .../stateless/AccountSessionBeanWithInterfaceTest.java | 10 ++++------ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java index 3a4f3a1b2..469599c7c 100644 --- a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java +++ b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java @@ -19,7 +19,7 @@ /** * @author Arun Gupta */ -@RunWith(Arquillian.class) +//@RunWith(Arquillian.class) public class AccountSessionBeanTest { @EJB AccountSessionBean bean; @@ -29,8 +29,8 @@ public class AccountSessionBeanTest { * * @return a war file */ - @Deployment - @TargetsContainer("wildfly-arquillian") +// @Deployment +// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(AccountSessionBean.class); @@ -43,7 +43,6 @@ public static WebArchive createDeployment() { */ @Test public void testWithdraw() { - System.out.println("withdraw"); String result = bean.withdraw((float)5.0); assertEquals("Withdrawn: 5.0", result); } @@ -53,7 +52,6 @@ public void testWithdraw() { */ @Test public void testDeposit() { - System.out.println("deposit"); String result = bean.withdraw((float)10.0); assertEquals("Deposited: 10.0", result); } diff --git a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java index f09f28c85..9043d1cbb 100644 --- a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java +++ b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java @@ -20,7 +20,7 @@ /** * @author Arun Gupta */ -@RunWith(Arquillian.class) +//@RunWith(Arquillian.class) public class AccountSessionBeanWithInterfaceTest { @EJB Account bean; @@ -30,8 +30,8 @@ public class AccountSessionBeanWithInterfaceTest { * * @return a war file */ - @Deployment - @TargetsContainer("wildfly-arquillian") +// @Deployment +// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(AccountSessionBean.class); @@ -44,7 +44,6 @@ public static WebArchive createDeployment() { */ @Test public void testWithdraw() { - System.out.println("withdraw"); String result = bean.withdraw((float)5.0); assertEquals("Withdrawn: 5.0", result); } @@ -54,8 +53,7 @@ public void testWithdraw() { */ @Test public void testDeposit() { - System.out.println("deposit"); - String result = bean.withdraw((float)10.0); + String result = bean.withdraw((float)10.0); assertEquals("Deposited: 10.0", result); } From 33b86ba9e77d929f0cab1a7400ab8d322f245513 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 22:52:08 +0200 Subject: [PATCH 030/785] Cleaning up test --- .../java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java b/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java index 8aff10243..2d50f1814 100644 --- a/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java +++ b/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java @@ -19,9 +19,6 @@ public class MyResourceTest { private static WebTarget target; - public MyResourceTest() { - } - @BeforeClass public static void setUpClass() { Client client = ClientBuilder.newClient(); From ddad3da835402050aec0b6f54508b3349b91716b Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 23:24:00 +0200 Subject: [PATCH 031/785] Adding XMLAssert and JSONAssert for comparing XML and JSON --- .../client/negotiation/MyResourceTest.java | 18 ++++++++++-------- pom.xml | 12 ++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java b/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java index c739c0f27..4af673717 100644 --- a/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java +++ b/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java @@ -6,15 +6,17 @@ package org.javaee7.jaxrs.client.negotiation; +import java.io.IOException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.*; + +import org.custommonkey.xmlunit.XMLAssert; +import org.json.JSONException; +import org.skyscreamer.jsonassert.JSONAssert; +import org.xml.sax.SAXException; /** * @author Arun Gupta @@ -31,15 +33,15 @@ public static void setUpClass() { } @Test - public void testXML() { + public void testXML() throws SAXException, IOException { String xml = target.request("application/xml").get(String.class); - assertEquals("1Penny2Leonard3Sheldon", xml); + XMLAssert.assertXMLEqual("1Penny2Leonard3Sheldon", xml); } @Test - public void testJSON() { + public void testJSON() throws JSONException { String json = target.request("application/json").get(String.class); - assertEquals("[{\"age\":1,\"name\":\"Penny\"},{\"age\":2,\"name\":\"Leonard\"},{\"age\":3,\"name\":\"Sheldon\"}]", json); + JSONAssert.assertEquals("[{\"age\":1,\"name\":\"Penny\"},{\"age\":2,\"name\":\"Leonard\"},{\"age\":3,\"name\":\"Sheldon\"}]", json, false); } } diff --git a/pom.xml b/pom.xml index 5414b3d13..31d7996d4 100644 --- a/pom.xml +++ b/pom.xml @@ -65,6 +65,18 @@ ${org.jboss.arquillian.version} test + + xmlunit + xmlunit + 1.5 + test + + + org.skyscreamer + jsonassert + 1.2.1 + test + From ad5873d61553aff123cc4109aa61ca006b9081b2 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 23:41:48 +0200 Subject: [PATCH 032/785] Adding test --- .../jaxrs/dynamicfilter/MyResource.java | 21 +++++++-- .../dynamicfilter/ServerLoggingFilter.java | 8 +++- .../jaxrs/dynamicfilter/MyResourceTest.java | 46 +++++++++++++++++++ 3 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java diff --git a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/MyResource.java b/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/MyResource.java index a9cbf1d53..d1ff0b58e 100644 --- a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/MyResource.java +++ b/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/MyResource.java @@ -42,23 +42,34 @@ import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; /** * @author Arun Gupta */ @Path("fruits") public class MyResource { - private String[] response = { "apple", "banana", "mango" }; + private final String[] response = { "apple", "banana", "mango" }; + + @Context Request request; + @Context HttpHeaders headers; @GET public String getList() { - System.out.println("@GET"); - return response[0]; + for (String header : headers.getRequestHeaders().keySet()) { + if (header.equals("myHeader")) { + if (headers.getRequestHeader(header).get(0).equals("myValue")) + return response[0]; + } + } + return response[1]; } @POST - public void addFruit(String fruit) { - System.out.println("@POST"); + public String echoFruit(String fruit) { + return fruit; } } diff --git a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/ServerLoggingFilter.java b/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/ServerLoggingFilter.java index 040b7ebc6..267aac84b 100644 --- a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/ServerLoggingFilter.java +++ b/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/ServerLoggingFilter.java @@ -58,8 +58,12 @@ public void filter(ContainerRequestContext crc) throws IOException { System.out.println("ContainerRequestFilter"); System.out.println(crc.getMethod() + " " + crc.getUriInfo().getAbsolutePath()); for (String key : crc.getHeaders().keySet()) { - System.out.println(key + ": " + crc.getHeaders().get(key)); + System.out.println(" " + key + ": " + crc.getHeaders().get(key)); } + + // add a header, check in test + crc.getHeaders().add("myHeader", "myValue"); + System.out.println("ContainerRequestFilter"); } @@ -67,7 +71,7 @@ public void filter(ContainerRequestContext crc) throws IOException { public void filter(ContainerRequestContext crc, ContainerResponseContext crc1) throws IOException { System.out.println("ContainerResponseFilter"); for (String key : crc1.getHeaders().keySet()) { - System.out.println(key + ": " + crc1.getHeaders().get(key)); + System.out.println("
" + key + ": " + crc1.getHeaders().get(key)); } System.out.println("ContainerResponseFilter"); } diff --git a/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java b/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java new file mode 100644 index 000000000..c6e6d1c86 --- /dev/null +++ b/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java @@ -0,0 +1,46 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.jaxrs.dynamicfilter; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * @author Arun Gupta + */ +public class MyResourceTest { + + private static WebTarget target; + + public MyResourceTest() { + } + + @BeforeClass + public static void setUpClass() { + Client client = ClientBuilder.newClient(); + target = client.target("http://localhost:8080/dynamicfilter/webresources/fruits"); + } + + @Test + public void testGetList() { + String result = target.request().get(String.class); + assertEquals("apple", result); + } + + @Test + public void testPost() { + String response = target.request().post(Entity.text("apple"), String.class); + assertEquals("apple", response); + } +} From 796d585dea7e43865156b973c2d6181758d0a8c2 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Thu, 7 Nov 2013 23:55:43 +0200 Subject: [PATCH 033/785] Removing JSP/Servlet, adding tests --- .../jaxrs/filter/ClientLoggingFilter.java | 1 + .../org/javaee7/jaxrs/filter/MyResource.java | 36 ++++- .../jaxrs/filter/ServerLoggingFilter.java | 1 + .../org/javaee7/jaxrs/filter/TestServlet.java | 145 ------------------ jaxrs/filter/src/main/webapp/index.jsp | 55 ------- .../javaee7/jaxrs/filter/MyResourceTest.java | 52 +++++++ 6 files changed, 85 insertions(+), 205 deletions(-) delete mode 100644 jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/TestServlet.java delete mode 100644 jaxrs/filter/src/main/webapp/index.jsp create mode 100644 jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java diff --git a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ClientLoggingFilter.java b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ClientLoggingFilter.java index 90be9eb50..6ca8e9c86 100644 --- a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ClientLoggingFilter.java +++ b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ClientLoggingFilter.java @@ -58,6 +58,7 @@ public void filter(ClientRequestContext crc) throws IOException { for (Entry e : crc.getHeaders().entrySet()) { System.out.print(e.getKey() + ": " + e.getValue()); } + crc.getHeaders().add("clientHeader", "clientHeaderValue"); System.out.println("ClientRequestFilter"); } diff --git a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/MyResource.java b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/MyResource.java index ead65d720..662535d83 100644 --- a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/MyResource.java +++ b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/MyResource.java @@ -44,21 +44,47 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; /** * @author Arun Gupta */ @Path("fruits") public class MyResource { + + @Context + HttpHeaders headers; + @GET public String getFruit() { - return "apple"; + String clientHeaderValue = headers.getHeaderString("clientHeader"); + String serverHeaderValue = headers.getHeaderString("serverHeader"); + + if (clientHeaderValue != null + && clientHeaderValue.equals("clientHeaderValue") + && serverHeaderValue != null + && serverHeaderValue.equals("serverHeaderValue")) { + return "apple"; + } else { + return "banana"; + } } @POST - @Consumes(value="*/*") + @Consumes(value = "*/*") @Produces("text/plain") - public String getFruit2(String index) { - return "apple"; - } + public String echoFruit(String fruit) { + String clientHeaderValue = headers.getHeaderString("clientHeader"); + String serverHeaderValue = headers.getHeaderString("serverHeader"); + + if (clientHeaderValue != null + && clientHeaderValue.equals("clientHeaderValue") + && serverHeaderValue != null + && serverHeaderValue.equals("serverHeaderValue")) { + return fruit; + } else { + return fruit.toUpperCase(); + } + } } diff --git a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ServerLoggingFilter.java b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ServerLoggingFilter.java index 07c90c9dc..bc4c8bbb5 100644 --- a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ServerLoggingFilter.java +++ b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/ServerLoggingFilter.java @@ -65,6 +65,7 @@ public void filter(ContainerRequestContext crc) throws IOException { for (String key : crc.getHeaders().keySet()) { System.out.println(key + ": " + crc.getHeaders().get(key)); } + crc.getHeaders().add("serverHeader", "serverHeaderValue"); System.out.println("ContainerRequestFilter"); } diff --git a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/TestServlet.java b/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/TestServlet.java deleted file mode 100644 index 00a814ff5..000000000 --- a/jaxrs/filter/src/main/java/org/javaee7/jaxrs/filter/TestServlet.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.filter; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("JAX-RS Client/Server Filter"); - out.println(""); - out.println(""); - out.println("

JAX-RS Client/Server Filter

"); - Client client = ClientBuilder.newClient(); - client.register(ClientLoggingFilter.class); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/fruits"); - out.println(target.getUri()+ "

"); - out.println("GET request"+ "

"); - String result = target.request().get(String.class); - out.println("Received response (GET): " + result + "

"); - - System.out.println("**** POST request"); - result = target - .request() - .post(Entity.text("1"), String.class); - out.println("Received response (POST): " + result + "

"); - - out.println("Received response: " + result + "

"); - out.println("

Check server log for client/server filter output such as <start>ClientRequestFilter and <start>ContainerRequestFilter"); - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/filter/src/main/webapp/index.jsp b/jaxrs/filter/src/main/webapp/index.jsp deleted file mode 100644 index d7b9b6d9a..000000000 --- a/jaxrs/filter/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JAX-RS 2 Filter - - -

JAX-RS 2 Filter

- Invoke the Client and check the server.log for filter output. - - diff --git a/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java b/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java new file mode 100644 index 000000000..92dd85c01 --- /dev/null +++ b/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java @@ -0,0 +1,52 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.jaxrs.filter; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * @author Arun Gupta + */ +public class MyResourceTest { + + private static WebTarget target; + + @BeforeClass + public static void setUpClass() { + Client client = ClientBuilder.newClient(); + client.register(ClientLoggingFilter.class); + target = client.target("http://localhost:8080/filter/webresources/fruits"); + } + + /** + * Test of getFruit method, of class MyResource. + */ + @Test + public void testGetFruit() { + String result = target.request().get(String.class); + assertEquals("Likely that the headers set in the filter were not available in endpoint", + "apple", + result); + } + + /** + * Test of getFruit2 method, of class MyResource. + */ + @Test + public void testPostFruit() { + String result = target.request().post(Entity.text("apple"), String.class); + assertEquals("Likely that the headers set in the filter were not available in endpoint", + "apple", + result); + } + +} From 88f46b44eefceee9c55400292e5ef41cf4ab0292 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:48:50 +0200 Subject: [PATCH 034/785] Added detailed instructions on how to run the samples/tests in different modes (needs more testing of the instructions) --- README.md | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e22afafeb..8eee3b27f 100644 --- a/README.md +++ b/README.md @@ -6,30 +6,47 @@ I don't plan to write any formal documentation, read the code. The [Java EE 7 Es ## How to run ? ## -### How I run them ? ### +### Maven Plugins ### -1. Open the sample in [NetBeans 7.4 nightly](http://bits.netbeans.org/dev/nightly/latest) +#### WildFly #### + +##### One time ##### + +1. ``git clone https://github.com/wildfly/wildfly-maven-plugin`` +2. ``cd wildfly-maven-plugin`` +3. ``mvn install`` + +##### Deploy the app, run the tests ##### + +1. For each sample: ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` + +### NetBeans ### + +1. Open the sample in [NetBeans 7.4](http://netbeans.org) 2. Click on "Run" (sample is built and deployed on GlassFish 4, main page shows up) 3. Main page provides feature name, how to run the sample, and displays the output ### Cargo ### -By default, all samples are deployed on GlassFish 4. They can be deployed on Widlfly 8 by adding ``-P wildfly`` to all maven commands. Make sure to edit ``glassfish.home`` or ``wildfly.home`` property value in the top-level ``pom.xml`` to point to your local GlassFish or Wildfly directory respectively. Only one profile can be active at a given time otherwise there will be port conflicts. +Samples can be deployed and run on WildFly and GlassFish 4. + +Make sure to edit ``glassfish.home`` or ``wildfly.home`` property value in the top-level ``pom.xml`` to point to your local GlassFish or Wildfly directory respectively. This is achieved using Maven profiles. Include ``-P wildfly`` on mvn CLI to run the samples on WildFly and ``-P glassfish`` fo GlassFish. -1. In one terminal, anywhere in the project with a ``pom.xml``: ``mvn cargo:run`` to start GlassFish server or ``mvn -P wildfly`` to start Wildfly server. -2. In another terminal, in the actual sample directory +Only one profile can be active at a given time otherwise there will be port conflicts. + +1. In one terminal, ``mvn cargo:run`` at the top-level directory to start container +2. In the sample directory 1. ``mvn package cargo:deploy`` to deploy for the first time 2. ``mvn package cargo:redeploy`` to redeploy subsequently 3. ``mvn cargo:undeploy`` to undeploy 3. Check for application name printed by Cargo output. Access the application at http://localhost:8080/ -4. Same as 3 in the first one ### Manual ### -1. ``mvn clean package`` +1. ``mvn clean package -DskipTests`` 2. Deploy on GlassFish using ``asadmin deploy target/XXX.war`` or deploy on Wildfly using ``TBD`` 3. Access http://localhost:8080/XXX/ (main page shows up) -4. Same as 3 in the first one + ## List of Samples ## From 48e0e7e1f1907d7f2c8b7f2cc8fd6cb5066f2228 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:52:17 +0200 Subject: [PATCH 035/785] Clarified some instructions and added more placeholders --- README.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8eee3b27f..8e1220a90 100644 --- a/README.md +++ b/README.md @@ -6,26 +6,32 @@ I don't plan to write any formal documentation, read the code. The [Java EE 7 Es ## How to run ? ## -### Maven Plugins ### +### Maven Plugins (WildFly) ### -#### WildFly #### - -##### One time ##### +#### One time #### 1. ``git clone https://github.com/wildfly/wildfly-maven-plugin`` 2. ``cd wildfly-maven-plugin`` 3. ``mvn install`` -##### Deploy the app, run the tests ##### +#### Deploy the app, run the tests #### 1. For each sample: ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` +### Maven Plugins (GlassFish) ### + +TBD + ### NetBeans ### 1. Open the sample in [NetBeans 7.4](http://netbeans.org) -2. Click on "Run" (sample is built and deployed on GlassFish 4, main page shows up) +2. Click on "Run" (sample is built and deployed on GlassFish 4, main page shows up). NetBeans do not support WildFly yet. 3. Main page provides feature name, how to run the sample, and displays the output +### JBoss Tools ### + +### IntelliJ ### + ### Cargo ### Samples can be deployed and run on WildFly and GlassFish 4. From dedb372879c68e1b011b8488e0dec929b67690d8 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:57:52 +0200 Subject: [PATCH 036/785] Added dependencies for unit testing --- pom.xml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pom.xml b/pom.xml index 31d7996d4..775c3839c 100644 --- a/pom.xml +++ b/pom.xml @@ -77,6 +77,18 @@ 1.2.1 test + + httpunit + httpunit + 1.7 + test + + + rhino + js + 1.7R1 + test + @@ -307,6 +319,11 @@ + + org.wildfly.plugins + wildfly-maven-plugin + 1.0.0.Beta1-SNAPSHOT + From 4286009e3f2481912451661bd442cfd147529853 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:58:08 +0200 Subject: [PATCH 037/785] Starting work on unit test --- .../metadata/complete/TestServletTest.java | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/servlet/metadata-complete/src/test/java/org/javaee7/servlet/metadata/complete/TestServletTest.java b/servlet/metadata-complete/src/test/java/org/javaee7/servlet/metadata/complete/TestServletTest.java index 2b9921950..f50e20ee3 100644 --- a/servlet/metadata-complete/src/test/java/org/javaee7/servlet/metadata/complete/TestServletTest.java +++ b/servlet/metadata-complete/src/test/java/org/javaee7/servlet/metadata/complete/TestServletTest.java @@ -5,23 +5,20 @@ */ package org.javaee7.servlet.metadata.complete; +import com.meterware.httpunit.GetMethodWebRequest; +import com.meterware.httpunit.WebConversation; +import com.meterware.httpunit.WebResponse; import java.io.File; -import java.io.PrintWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.TargetsContainer; -import org.jboss.arquillian.junit.Arquillian; +import java.io.IOException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; +import org.xml.sax.SAXException; /** * @author Arun Gupta */ -@RunWith(Arquillian.class) +//@RunWith(Arquillian.class) public class TestServletTest { private static final String WEBAPP_SRC = "src/main/webapp"; @@ -32,8 +29,8 @@ public class TestServletTest { * * @return a war file */ - @Deployment(testable = false) - @TargetsContainer("wildfly-arquillian") +// @Deployment(testable = false) +// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(TestServlet.class). @@ -46,13 +43,10 @@ public static WebArchive createDeployment() { * Test of processRequest method, of class TestServlet. */ @Test - public void testProcessRequest() throws Exception { - System.out.println("processRequest"); - HttpServletRequest request = null; - HttpServletResponse response = null; - TestServlet instance = new TestServlet(); - instance.processRequest(request, response); - PrintWriter writer = response.getWriter(); -// response. + public void testProcessRequest() throws IOException, SAXException { + WebConversation conv = new WebConversation(); + GetMethodWebRequest getRequest = new GetMethodWebRequest("http://localhost:8080/metadata-complete/TestServlet"); + WebResponse getResponse = conv.getResponse(getRequest); + System.out.println(getResponse.getText()); } } From 99136911d010062274aa28e977d5fba2bf50d7b9 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:58:39 +0200 Subject: [PATCH 038/785] Starting work on unit test --- .../scope/TransactionalBeanTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 jta/transaction-scope/src/test/java/org/javaee7/jta/transaction/scope/TransactionalBeanTest.java diff --git a/jta/transaction-scope/src/test/java/org/javaee7/jta/transaction/scope/TransactionalBeanTest.java b/jta/transaction-scope/src/test/java/org/javaee7/jta/transaction/scope/TransactionalBeanTest.java new file mode 100644 index 000000000..e6fdcf40a --- /dev/null +++ b/jta/transaction-scope/src/test/java/org/javaee7/jta/transaction/scope/TransactionalBeanTest.java @@ -0,0 +1,53 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jta.transaction.scope; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * @author Arun Gupta + */ +public class TransactionalBeanTest { + + /** + * Test of scenario1 method, of class MyTransactionalBean. + */ + @Test + public void testScenario1() { + System.out.println("scenario1"); + MyTransactionalBean instance = new MyTransactionalBean(); + instance.scenario1(); + // TODO review the generated test code and remove the default call to fail. + fail("The test case is a prototype."); + } + + /** + * Test of scenario2 method, of class MyTransactionalBean. + */ + @Test + public void testScenario2() { + System.out.println("scenario2"); + MyTransactionalBean instance = new MyTransactionalBean(); + instance.scenario2(); + // TODO review the generated test code and remove the default call to fail. + fail("The test case is a prototype."); + } + + /** + * Test of scenario3 method, of class MyTransactionalBean. + */ + @Test + public void testScenario3() { + System.out.println("scenario3"); + MyTransactionalBean instance = new MyTransactionalBean(); + instance.scenario3(); + // TODO review the generated test code and remove the default call to fail. + fail("The test case is a prototype."); + } + +} From fb2a6704241e4266309b0b75ac1b19346fbd6ba4 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 01:59:28 +0200 Subject: [PATCH 039/785] Removing GlassFish-specific dependencies --- jaxrs/invocation-async/pom.xml | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/jaxrs/invocation-async/pom.xml b/jaxrs/invocation-async/pom.xml index fc33b5b10..c5a33d40f 100644 --- a/jaxrs/invocation-async/pom.xml +++ b/jaxrs/invocation-async/pom.xml @@ -12,21 +12,4 @@ invocation-async 1.0-SNAPSHOT war - - - org.glassfish.jersey.containers - jersey-container-servlet - 2.0 - - - org.glassfish.jersey.core - jersey-client - 2.0 - - - org.glassfish.jersey.media - jersey-media-multipart - 2.0 - - From ae8c867fb4df3f4e3a902b9e3972e6c1945decb1 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 02:00:14 +0200 Subject: [PATCH 040/785] Removing redundant plugins --- jaxrs/singleton-annotation/pom.xml | 67 ------------------------------ 1 file changed, 67 deletions(-) diff --git a/jaxrs/singleton-annotation/pom.xml b/jaxrs/singleton-annotation/pom.xml index 60cbf875e..93a1202a3 100644 --- a/jaxrs/singleton-annotation/pom.xml +++ b/jaxrs/singleton-annotation/pom.xml @@ -11,71 +11,4 @@ singleton-annotation 1.0-SNAPSHOT war - - singleton-annotation - - - ${project.build.directory}/endorsed - UTF-8 - - - - - javax - javaee-web-api - 7.0 - provided - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - ${endorsed.dir} - - - - - org.apache.maven.plugins - maven-war-plugin - 2.3 - - false - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.6 - - - validate - - copy - - - ${endorsed.dir} - true - - - javax - javaee-endorsed-api - 7.0 - jar - - - - - - - - - From b28819f976f88968558d43230ad84e7ed1ccfc09 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 02:00:28 +0200 Subject: [PATCH 041/785] Removing redundant test --- .../endpoint/test/JaxRSEndpointTest.java | 72 ------------------- 1 file changed, 72 deletions(-) delete mode 100644 jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java diff --git a/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java b/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java deleted file mode 100644 index 4fe2a61f4..000000000 --- a/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/test/JaxRSEndpointTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - */ -package org.javaee7.jaxrs.endpoint.test; - -import java.net.URI; -import java.net.URISyntaxException; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; - -import junit.framework.Assert; - -import org.javaee7.jaxrs.endpoint.Database; -import org.javaee7.jaxrs.endpoint.MyApplication; -import org.javaee7.jaxrs.endpoint.MyResource; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.TargetsContainer; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.arquillian.junit.InSequence; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -/** - * @author Nikolaos Ballas - * - */ -@RunWith(Arquillian.class) -public class JaxRSEndpointTest { - - private Client client = null; - - @Deployment(testable=false) @TargetsContainer("wildfly-arquillian") - public static WebArchive createDeplymentI() { - return ShrinkWrap.create(WebArchive.class, "jaxrs-endpoint.war"). - addClass(MyApplication.class). - addClass(Database.class). - addClass(MyResource.class); - } - - - @Test - @InSequence(1) - public void invokeEndpointPUTTest() throws URISyntaxException{ - WebTarget targetEndpoint= getTargetEndpoint("fruit"); - targetEndpoint.request().put(Entity.text("banana")); - } - @Test - @InSequence(2) - public void invokeEndpointGETTest() throws URISyntaxException { - WebTarget targetEndPoint = getTargetEndpoint("fruit"); - String received = targetEndPoint.request().get(String.class); - Assert.assertEquals("[banana]" ,received); - } - - /** - * The method for obtaining a target endpoint. - * @param endpointName the target endpoint name which we want to invoke - * @return a WebTarget object - * @throws URISyntaxException - */ - public WebTarget getTargetEndpoint(String endpointName) throws URISyntaxException { - if(client == null) { - client = ClientBuilder.newClient(); - } - return client.target(new URI("http://localhost:8080/jaxrs-endpoint/webresources/"+endpointName)); - } -} From 94b211a22e9cc11490b67f4c3074d86b5ee85d99 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 02:00:58 +0200 Subject: [PATCH 042/785] Fixing typo --- jsf/passthrough/src/main/webapp/template.xhtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsf/passthrough/src/main/webapp/template.xhtml b/jsf/passthrough/src/main/webapp/template.xhtml index 6acb82d3e..311fc667d 100644 --- a/jsf/passthrough/src/main/webapp/template.xhtml +++ b/jsf/passthrough/src/main/webapp/template.xhtml @@ -8,7 +8,7 @@ - JSF 2.2 Passthrough Attributes< + JSF 2.2 Passthrough Attributes From afe98cb3f5cdab594d422509bb88ee7a08efdeb9 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 02:22:58 +0200 Subject: [PATCH 043/785] Added support for running the samples/tests using GlassFish maven plugin --- pom.xml | 59 +++++++++++++++++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/pom.xml b/pom.xml index 775c3839c..49ff50b23 100644 --- a/pom.xml +++ b/pom.xml @@ -205,6 +205,18 @@ glassfish + + + maven.java.net + Java.net Repository for Maven + https://maven.java.net/content/groups/promoted/ + + + maven2-repository.dev.java.net + Java.net Repository for Maven + http://download.java.net/maven/glassfish/ + + @@ -229,33 +241,6 @@ - - - - - org.glassfish.tyrus - tyrus-client - 1.3 - test - - - org.glassfish.tyrus - tyrus-container-grizzly-client - 1.3 - test - - - org.glassfish.jersey.core - jersey-client - 2.4 - test - - - - - embedded-glassfish - - org.glassfish.embedded maven-embedded-glassfish-plugin @@ -300,6 +285,26 @@ + + + org.glassfish.tyrus + tyrus-client + 1.3 + test + + + org.glassfish.tyrus + tyrus-container-grizzly-client + 1.3 + test + + + org.glassfish.jersey.core + jersey-client + 2.4 + test + + wildfly From c4135b1e22ebb2e1e8bbf957b08635aee061a448 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 02:25:09 +0200 Subject: [PATCH 044/785] Added instructions for running in GlassFish --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8e1220a90..8d11b29ed 100644 --- a/README.md +++ b/README.md @@ -14,13 +14,13 @@ I don't plan to write any formal documentation, read the code. The [Java EE 7 Es 2. ``cd wildfly-maven-plugin`` 3. ``mvn install`` -#### Deploy the app, run the tests #### +#### For each sample #### -1. For each sample: ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` +1. ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` ### Maven Plugins (GlassFish) ### -TBD +For each sample: ``mvn embedded-glassfish:deploy test -P glassfish`` ### NetBeans ### @@ -28,7 +28,7 @@ TBD 2. Click on "Run" (sample is built and deployed on GlassFish 4, main page shows up). NetBeans do not support WildFly yet. 3. Main page provides feature name, how to run the sample, and displays the output -### JBoss Tools ### +### JBoss Tools (Eclipse) ### ### IntelliJ ### @@ -53,7 +53,6 @@ Only one profile can be active at a given time otherwise there will be port conf 2. Deploy on GlassFish using ``asadmin deploy target/XXX.war`` or deploy on Wildfly using ``TBD`` 3. Access http://localhost:8080/XXX/ (main page shows up) - ## List of Samples ## The following script will generate the complete list of samples. From b34c31ff6e012319a8672e521e278b5569a59ab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 07:34:59 +0100 Subject: [PATCH 045/785] test failure fix --- .../org/javaee7/jaxrs/client/MyResourceTest.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java index d360b6fde..10d09dcc5 100644 --- a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java +++ b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java @@ -5,16 +5,18 @@ */ package org.javaee7.jaxrs.client; +import static org.junit.Assert.*; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; + +import org.junit.Before; import org.junit.FixMethodOrder; +import org.junit.Test; import org.junit.runners.MethodSorters; /** @@ -25,11 +27,8 @@ public class MyResourceTest { private static WebTarget target; - public MyResourceTest() { - } - - @BeforeClass - public static void setUpClass() { + @Before + public void setUp() { Client client = ClientBuilder.newClient(); target = client.target("http://localhost:8080/jaxrs-client/webresources/persons"); } From 6470b8ab191e94df5f70a6e2bbde1d4ed27e55a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 07:56:18 +0100 Subject: [PATCH 046/785] test resources cleanup --- .../java/org/javaee7/jaxrs/client/MyResourceTest.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java index 10d09dcc5..71844505c 100644 --- a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java +++ b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; +import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -26,13 +27,19 @@ public class MyResourceTest { private static WebTarget target; + private Client client; @Before - public void setUp() { - Client client = ClientBuilder.newClient(); + public void setUp() throws Exception { + client = ClientBuilder.newClient(); target = client.target("http://localhost:8080/jaxrs-client/webresources/persons"); } + @After + public void after() { + client.close(); + } + /** * Test of getList method, of class MyResource. */ From ddb8a5578e3dabd7b019bc023fc8a6907dbc1e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 08:11:22 +0100 Subject: [PATCH 047/785] test code cleanup --- .../java/org/javaee7/jaxrs/client/MyResourceTest.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java index 71844505c..a734e1c36 100644 --- a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java +++ b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java @@ -14,7 +14,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -26,20 +25,15 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MyResourceTest { - private static WebTarget target; + private WebTarget target; private Client client; @Before - public void setUp() throws Exception { + public void setUp() { client = ClientBuilder.newClient(); target = client.target("http://localhost:8080/jaxrs-client/webresources/persons"); } - @After - public void after() { - client.close(); - } - /** * Test of getList method, of class MyResource. */ From 9f6a575daffdc20770a0dbfa8ef29b34da80392a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 08:12:44 +0100 Subject: [PATCH 048/785] minor code change --- .../org/javaee7/jaxrs/client/PersonSessionBean.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java index 37594952f..81bcf27b6 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java @@ -41,6 +41,7 @@ import java.util.ArrayList; import java.util.List; + import javax.ejb.Singleton; /** @@ -48,24 +49,24 @@ */ @Singleton public class PersonSessionBean { - List list; - + private final List list; + public PersonSessionBean() { list = new ArrayList<>(); } - + public void addPerson(Person p) { list.add(p); } - + public void deletePerson(String name) { for (Person p : list) { - if (p.getName().equals(name)) { + if (name.equals(p.getName())) { list.remove(p); } } } - + public List getPersons() { return list; } From 4ec28521394e2ac196f4cc39cb350e946474313a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 09:56:19 +0100 Subject: [PATCH 049/785] added WEB-INF/beans.xml to enable CDI - possibly bug, should not be needed in JEE7 --- jaxrs/jaxrs-client/src/main/webapp/WEB-INF/beans.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 jaxrs/jaxrs-client/src/main/webapp/WEB-INF/beans.xml diff --git a/jaxrs/jaxrs-client/src/main/webapp/WEB-INF/beans.xml b/jaxrs/jaxrs-client/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 000000000..e69de29bb From 49975aec201303e07da6377e0740ae6e8fe1660e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 09:57:42 +0100 Subject: [PATCH 050/785] bugfix - ConcurrentModificationException in PersonSessionBean deletePerson --- .../org/javaee7/jaxrs/client/PersonSessionBean.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java index 81bcf27b6..87f82f19e 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/PersonSessionBean.java @@ -60,11 +60,16 @@ public void addPerson(Person p) { } public void deletePerson(String name) { + Person p = findPersonByName(name); + if (p != null) + list.remove(p); + } + private Person findPersonByName(String name) { for (Person p : list) { - if (name.equals(p.getName())) { - list.remove(p); - } + if (name.equals(p.getName())) + return p; } + return null; } public List getPersons() { From bfac7f0a33d0785c9d8da85aa9fe4f57120f3316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 10:38:08 +0100 Subject: [PATCH 051/785] remove compile warnings --- .../java/org/javaee7/jaxrs/client/TestJAXRS2Client.java | 7 +++++-- .../org/javaee7/jaxrs/client/TestURLConnectionClient.java | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java index 6dcb09a72..1c8ae6213 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java @@ -41,6 +41,7 @@ import java.io.IOException; import java.io.PrintWriter; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -59,6 +60,8 @@ @WebServlet(urlPatterns = {"/TestJAXRS2Client"}) public class TestJAXRS2Client extends HttpServlet { + private static final long serialVersionUID = 1L; + /** * Processes requests for both HTTP * GET and @@ -114,13 +117,13 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re .get(Person.class); out.print("GOT person: " + person + "
"); out.println("... done.
"); - + // Client-driven content negotiation out.print("
Client-side content negotiation...
"); String json = target.request().accept(MediaType.APPLICATION_JSON).get(String.class); out.print("GOT JSON: " + json + "
"); out.println("... done."); - + out.println(""); out.println(""); } diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java index 02261b45e..cd158069d 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java @@ -48,6 +48,7 @@ import java.net.URLEncoder; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -63,6 +64,8 @@ @WebServlet(urlPatterns = {"/TestURLConnectionClient"}) public class TestURLConnectionClient extends HttpServlet { + private static final long serialVersionUID = 4961659627909544506L; + private static final String CHARSET = "UTF-8"; /** @@ -123,7 +126,7 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re // is.read(bytes); // out.println(new String(bytes)); // } - + try { JAXBContext jc = JAXBContext.newInstance(Person.class, People.class); Unmarshaller um = jc.createUnmarshaller(); From f790d5907229357f8e0aca7681de6b5ca2dd2090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Saka=C5=99?= Date: Fri, 8 Nov 2013 10:42:48 +0100 Subject: [PATCH 052/785] fix test failures --- jaxrs/jaxrs-client/pom.xml | 8 ++++++++ .../java/org/javaee7/jaxrs/client/TestJAXRS2Client.java | 3 ++- .../java/org/javaee7/jaxrs/client/MyResourceTest.java | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/jaxrs/jaxrs-client/pom.xml b/jaxrs/jaxrs-client/pom.xml index c32f1e47c..35210af77 100644 --- a/jaxrs/jaxrs-client/pom.xml +++ b/jaxrs/jaxrs-client/pom.xml @@ -10,4 +10,12 @@ jaxrs-client war + + + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.5.Final + test + + diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java index 1c8ae6213..6942fc56a 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java @@ -60,7 +60,8 @@ @WebServlet(urlPatterns = {"/TestJAXRS2Client"}) public class TestJAXRS2Client extends HttpServlet { - private static final long serialVersionUID = 1L; + + private static final long serialVersionUID = 1975269372645791816L; /** * Processes requests for both HTTP diff --git a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java index a734e1c36..d5988e153 100644 --- a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java +++ b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java @@ -115,7 +115,7 @@ public void test4Delete() { @Test public void test5ClientSideNegotiation() { String json = target.request().accept(MediaType.APPLICATION_JSON).get(String.class); - assertEquals("[{\"age\":1,\"name\":\"Penny\"},{\"age\":2,\"name\":\"Leonard\"},{\"age\":3,\"name\":\"Sheldon\"}]", json); + assertEquals("[{\"name\":\"Penny\",\"age\":1},{\"name\":\"Leonard\",\"age\":2},{\"name\":\"Sheldon\",\"age\":3}]", json); } @Test From 316b7182b044a43ea5fcf8c3f55f835df99b7168 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 15:16:59 +0200 Subject: [PATCH 053/785] Commenting Arquillian dependencies for now --- .../managedexecutor/ExecutorInvokeAllServletTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java b/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java index 84fac4b57..8ceacba78 100644 --- a/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java +++ b/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java @@ -24,7 +24,7 @@ /** * @author Arun Gupta */ -@RunWith(Arquillian.class) +//@RunWith(Arquillian.class) public class ExecutorInvokeAllServletTest { @Resource(name = "DefaultManagedExecutorService") @@ -36,8 +36,8 @@ public class ExecutorInvokeAllServletTest { * * @return a war file */ - @Deployment - @TargetsContainer("wildfly-arquillian") +// @Deployment +// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(MyCallableTask.class). From b96d864acb30f3e265215cdbc01b1e257e30d890 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:12:39 +0200 Subject: [PATCH 054/785] Adding RESTEasy jaxb-provider dependency in test scope --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index 49ff50b23..78688c40a 100644 --- a/pom.xml +++ b/pom.xml @@ -339,6 +339,12 @@ jar test + + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.5.Final + test +
From a26ad1bccc0248b39f22e688e0b63fdb79bd7e09 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:27:30 +0200 Subject: [PATCH 055/785] Cleaning up the test and commented as support for this API is optional --- .../javaee7/ejb/embeddable/MyBeanTest.java | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/ejb/embeddable/src/test/java/org/javaee7/ejb/embeddable/MyBeanTest.java b/ejb/embeddable/src/test/java/org/javaee7/ejb/embeddable/MyBeanTest.java index 7a849b652..e7bd745a3 100644 --- a/ejb/embeddable/src/test/java/org/javaee7/ejb/embeddable/MyBeanTest.java +++ b/ejb/embeddable/src/test/java/org/javaee7/ejb/embeddable/MyBeanTest.java @@ -40,40 +40,20 @@ package org.javaee7.ejb.embeddable; import javax.ejb.embeddable.EJBContainer; -import org.junit.After; -import org.junit.AfterClass; import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.Test; /** * @author Arun Gupta */ public class MyBeanTest { - public MyBeanTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - /** * Test of sayHello method, of class MyBean. + * + * Commented for now as support for this API is optional */ - @org.junit.Test +// @Test public void testSayHello() throws Exception { System.out.println("sayHello"); String name = "Duke"; From f78ef6bdf6c8011ddf2022aa2bb1d3c58def00e4 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:28:13 +0200 Subject: [PATCH 056/785] Moved RESTEasy JAXB module to parent pom.xml --- jaxrs/jaxrs-client/pom.xml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/jaxrs/jaxrs-client/pom.xml b/jaxrs/jaxrs-client/pom.xml index 35210af77..c32f1e47c 100644 --- a/jaxrs/jaxrs-client/pom.xml +++ b/jaxrs/jaxrs-client/pom.xml @@ -10,12 +10,4 @@ jaxrs-client war - - - org.jboss.resteasy - resteasy-jaxb-provider - 3.0.5.Final - test - - From e934ff3efe5d42dd224235610e2d418f2c2b00cd Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:28:50 +0200 Subject: [PATCH 057/785] Commenting the test for now until JNDI lookup is figured out correctly --- .../concurrency/managedthreadfactory/MyTaskTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/concurrency/managedthreadfactory/src/test/java/org/javaee7/concurrency/managedthreadfactory/MyTaskTest.java b/concurrency/managedthreadfactory/src/test/java/org/javaee7/concurrency/managedthreadfactory/MyTaskTest.java index f5cfea34c..7de74afd2 100644 --- a/concurrency/managedthreadfactory/src/test/java/org/javaee7/concurrency/managedthreadfactory/MyTaskTest.java +++ b/concurrency/managedthreadfactory/src/test/java/org/javaee7/concurrency/managedthreadfactory/MyTaskTest.java @@ -30,7 +30,7 @@ public class MyTaskTest { * * using JNDI lookup */ - @Test +// @Test public void testJNDILookup() { try { InitialContext ctx = new InitialContext(); @@ -51,7 +51,7 @@ public void testJNDILookup() { * * using @Resource, with no name */ - @Test +// @Test public void testResourceNoName() { Thread thread = factory.newThread(new MyTask(1)); assertNotNull(thread); @@ -63,7 +63,7 @@ public void testResourceNoName() { * * using @Resource, with no name */ - @Test +// @Test public void testResourceWithName() { Thread thread = factory2.newThread(new MyTask(1)); assertNotNull(thread); From 8a62f8484e5a3d61fc74d8d90b9f4c669f65a366 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:42:14 +0200 Subject: [PATCH 058/785] CoCommenting the test for now until EJB injection is identified --- .../AccountSessionBeanWithInterfaceTest.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java index 9043d1cbb..4c925ebcd 100644 --- a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java +++ b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanWithInterfaceTest.java @@ -3,27 +3,24 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ - package org.javaee7.ejb.stateless; import javax.ejb.EJB; import org.javaee7.ejb.stateless.remote.Account; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.TargetsContainer; -import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import static org.junit.Assert.*; -import org.junit.runner.RunWith; /** * @author Arun Gupta */ //@RunWith(Arquillian.class) public class AccountSessionBeanWithInterfaceTest { - @EJB Account bean; - + + @EJB + Account bean; + /** * Arquillian specific method for creating a file which can be deployed * while executing the test. @@ -38,23 +35,23 @@ public static WebArchive createDeployment() { System.out.println(war.toString(true)); return war; } - + /** * Test of withdraw method, of class AccountSessionBean. */ - @Test +// @Test public void testWithdraw() { - String result = bean.withdraw((float)5.0); + String result = bean.withdraw((float) 5.0); assertEquals("Withdrawn: 5.0", result); } /** * Test of deposit method, of class AccountSessionBean. */ - @Test +// @Test public void testDeposit() { - String result = bean.withdraw((float)10.0); + String result = bean.withdraw((float) 10.0); assertEquals("Deposited: 10.0", result); } - + } From 7e3b4ae715d15790eee4f3ecf6bc2b055a9d73cb Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:42:20 +0200 Subject: [PATCH 059/785] CoCommenting the test for now until EJB injection is identified --- .../javaee7/ejb/stateless/AccountSessionBeanTest.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java index 469599c7c..44dd68560 100644 --- a/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java +++ b/ejb/stateless/src/test/java/org/javaee7/ejb/stateless/AccountSessionBeanTest.java @@ -7,19 +7,14 @@ package org.javaee7.ejb.stateless; import javax.ejb.EJB; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.TargetsContainer; -import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import static org.junit.Assert.*; -import org.junit.runner.RunWith; /** * @author Arun Gupta */ -//@RunWith(Arquillian.class) public class AccountSessionBeanTest { @EJB AccountSessionBean bean; @@ -29,8 +24,6 @@ public class AccountSessionBeanTest { * * @return a war file */ -// @Deployment -// @TargetsContainer("wildfly-arquillian") public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(AccountSessionBean.class); @@ -41,7 +34,7 @@ public static WebArchive createDeployment() { /** * Test of withdraw method, of class AccountSessionBean. */ - @Test +// @Test public void testWithdraw() { String result = bean.withdraw((float)5.0); assertEquals("Withdrawn: 5.0", result); @@ -50,7 +43,7 @@ public void testWithdraw() { /** * Test of deposit method, of class AccountSessionBean. */ - @Test +// @Test public void testDeposit() { String result = bean.withdraw((float)10.0); assertEquals("Deposited: 10.0", result); From b76dd35c64d0f3b6f82cfdb305a8ad403143f9cf Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 16:48:35 +0200 Subject: [PATCH 060/785] Initializing the client before each test --- .../java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java b/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java index 4b2a9c1b7..5345a0515 100644 --- a/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java +++ b/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java @@ -17,6 +17,7 @@ import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; +import org.junit.Before; /** * @author Arun Gupta @@ -27,8 +28,8 @@ public class MyResourceTest { private static WebTarget target; - @BeforeClass - public static void setUpClass() { + @Before + public void setUpClass() { Client client = ClientBuilder.newClient(); target = client.target("http://localhost:8080/async-client/webresources/fruits"); } From 7a1e4fb8dbbf3f6418385bb0051cda78f5001b66 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 17:42:41 +0200 Subject: [PATCH 061/785] Removing GlassFish specific dependency --- .../java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java b/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java index 5a8dbd9f8..bb763e351 100644 --- a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java +++ b/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java @@ -51,7 +51,6 @@ import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; -import org.glassfish.jersey.filter.LoggingFilter; /** * @author Arun Gupta @@ -81,7 +80,6 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re out.println("

Mapping Exceptions

"); Client client = ClientBuilder.newClient(); WebTarget target = client - .register(new LoggingFilter(Logger.getAnonymousLogger(), true)) .target("http://" + request.getServerName() + ":" From dfa353c3671da9c6f3ce33c0b97b32a5d8260e0d Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 17:45:44 +0200 Subject: [PATCH 062/785] Commenting GlassFish specific modules --- jaxrs/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxrs/pom.xml b/jaxrs/pom.xml index 7824282d3..836943687 100644 --- a/jaxrs/pom.xml +++ b/jaxrs/pom.xml @@ -35,7 +35,7 @@ request-binding resource-validation server-negotiation - server-sent-event + singleton-application singleton-annotation readerwriter-injection From f88ef7be0d0eaddf006576f77ac4cf289a0d2d6f Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 17:51:30 +0200 Subject: [PATCH 063/785] Returning just the order id --- .../java/org/javaee7/jaxrs/mapping/exceptions/MyResource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/MyResource.java b/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/MyResource.java index 7bc648576..49a8acd88 100644 --- a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/MyResource.java +++ b/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/MyResource.java @@ -55,7 +55,7 @@ public String getOrder(@PathParam("id") int id) { if (id % 2 == 0) { throw new OrderNotFoundException(id); } - return String.valueOf("Order found: " + id); + return String.valueOf(id); } } From bbb6fe95b4002db2373d3c663e035fb52ad42f53 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 17:52:57 +0200 Subject: [PATCH 064/785] Removing web pages and converting to unit tests --- .../jaxrs/mapping/exceptions/TestServlet.java | 146 ------------------ .../src/main/webapp/index.jsp | 55 ------- .../mapping/exceptions/MyResourceTest.java | 55 +++++++ 3 files changed, 55 insertions(+), 201 deletions(-) delete mode 100644 jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java delete mode 100644 jaxrs/mapping-exceptions/src/main/webapp/index.jsp create mode 100644 jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java diff --git a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java b/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java deleted file mode 100644 index bb763e351..000000000 --- a/jaxrs/mapping-exceptions/src/main/java/org/javaee7/jaxrs/mapping/exceptions/TestServlet.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.mapping.exceptions; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.logging.Logger; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("Mapping Exceptions"); - out.println(""); - out.println(""); - out.println("

Mapping Exceptions

"); - Client client = ClientBuilder.newClient(); - WebTarget target = client - .target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/order"); - - out.print("

GETTing odd-numbered order ...
"); - out.print(target.path("1").request().get(String.class)); - - out.print("

GETTing even-numbered order ...
"); - try { - out.print(target.path("2").request().get(String.class)); - } catch (ClientErrorException e) { - out.println(e.getMessage() + "
"); - } - out.println("Got an error indicating HTTP 412 precondition failed ?"); - out.println("
... done.
"); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/mapping-exceptions/src/main/webapp/index.jsp b/jaxrs/mapping-exceptions/src/main/webapp/index.jsp deleted file mode 100644 index 30c14c106..000000000 --- a/jaxrs/mapping-exceptions/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - Mapping Exceptions - - -

Mapping Exceptions

- Invoke the Client. - - diff --git a/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java b/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java new file mode 100644 index 000000000..122b62d88 --- /dev/null +++ b/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java @@ -0,0 +1,55 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jaxrs.mapping.exceptions; + +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author argupta + */ +public class MyResourceTest { + WebTarget target; + + @Before + public void setUp() { + Client client = ClientBuilder.newClient(); + target = client + .target("http://localhost:8080/mapping-exceptions/webresources/order"); + } + + /** + * Test of getOrder method, of class MyResource. + */ + @Test + public void testOddOrder() { + String response = target.path("1").request().get(String.class); + assertEquals("1", response); + } + + /** + * Test of getOrder method, of class MyResource. + */ + @Test + public void testEvenOrder() { + try { + System.out.print(target.path("2").request().get(String.class)); + } catch (ClientErrorException e) { + assertEquals(412, e.getResponse().getStatus()); + } catch (Exception e) { + fail(e.getMessage()); + } + + } + +} From b538a289fe4134447458750cd75f9d1e799f6212 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 18:10:38 +0200 Subject: [PATCH 065/785] Fixing a name --- .../java/org/javaee7/jaxrs/server/negotiation/MyResource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java index 3653b6780..91707e26f 100644 --- a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java +++ b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java @@ -54,7 +54,7 @@ public class MyResource { public Person[] getList() { Person[] list = new Person[3]; list[0] = new Person("Penny", 1); - list[1] = new Person("Howard", 2); + list[1] = new Person("Leonard", 2); list[2] = new Person("Sheldon", 3); return list; From 7acd1f1fd37dae7789346db2a24b2746f1185a15 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 18:20:06 +0200 Subject: [PATCH 066/785] Removing web pages/Servlet and converting to unit tests --- .../jaxrs/server/negotiation/TestServlet.java | 142 ------------------ .../src/main/webapp/index.jsp | 55 ------- .../server/negotiation/MyResourceTest.java | 62 ++++++++ 3 files changed, 62 insertions(+), 197 deletions(-) delete mode 100644 jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/TestServlet.java delete mode 100644 jaxrs/server-negotiation/src/main/webapp/index.jsp create mode 100644 jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java diff --git a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/TestServlet.java b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/TestServlet.java deleted file mode 100644 index 6a804779a..000000000 --- a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/TestServlet.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.server.negotiation; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import org.glassfish.jersey.filter.LoggingFilter; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("Server-side Content Preference"); - out.println(""); - out.println(""); - out.println("

Server-side Content Preference

"); - out.println("Initializing client...
"); - Client client = ClientBuilder.newClient(); - WebTarget target = client. - register(LoggingFilter.class) - .target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/persons"); - - // GET - out.print("GETTing...
"); - String string = target.request().accept("application/*").get(String.class); - out.format("GOT the representation: " + string); - out.format("

Did you get the JSON representation ?"); - out.println("

... done.
"); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/server-negotiation/src/main/webapp/index.jsp b/jaxrs/server-negotiation/src/main/webapp/index.jsp deleted file mode 100644 index 3e2267545..000000000 --- a/jaxrs/server-negotiation/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - Server-side Content Preference - - -

Server-side Content Preference

- Invoke the Client. - - diff --git a/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java b/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java new file mode 100644 index 000000000..c9dc9e1ea --- /dev/null +++ b/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java @@ -0,0 +1,62 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jaxrs.server.negotiation; + +import java.io.IOException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import org.custommonkey.xmlunit.XMLAssert; +import org.json.JSONException; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.xml.sax.SAXException; + +/** + * @author Arun Gupta + */ +public class MyResourceTest { + + WebTarget target; + + @Before + public void setUp() { + Client client = ClientBuilder.newClient(); + target = client + .target("http://localhost:8080/server-negotiation/webresources/persons"); + } + + @Test + public void testJson() throws JSONException { + String response = target.request().accept("application/*").get(String.class); + JSONAssert.assertEquals("[{\"name\":\"Penny\",\"age\":1},{\"name\":\"Leonard\",\"age\":2},{\"name\":\"Sheldon\",\"age\":3}]", + response, + JSONCompareMode.STRICT); + } + + @Test + public void testJson2() throws JSONException { + String response = target.request().get(String.class); + JSONAssert.assertEquals("[{\"name\":\"Penny\",\"age\":1},{\"name\":\"Leonard\",\"age\":2},{\"name\":\"Sheldon\",\"age\":3}]", + response, + JSONCompareMode.STRICT); + } + + @Test + public void testXml() throws JSONException, SAXException, IOException { + String response = target.request().accept("application/xml").get(String.class); + XMLAssert.assertXMLEqual("1Penny2Leonard3Sheldon", + response); + } + +} From 49952be7255ccadb21da4cb7c4a795d2d35f9216 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Fri, 8 Nov 2013 18:50:06 +0200 Subject: [PATCH 067/785] Removing web pages/Servlet and converting to unit tests --- .../singelton/application/MyResource.java | 1 - .../singelton/application/TestServlet.java | 159 ------------------ .../src/main/webapp/WEB-INF/beans.xml | 6 - .../src/main/webapp/index.jsp | 55 ------ 4 files changed, 221 deletions(-) delete mode 100644 jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/TestServlet.java delete mode 100644 jaxrs/singleton-application/src/main/webapp/WEB-INF/beans.xml delete mode 100644 jaxrs/singleton-application/src/main/webapp/index.jsp diff --git a/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/MyResource.java b/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/MyResource.java index 487f50ce4..80382b0d2 100644 --- a/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/MyResource.java +++ b/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/MyResource.java @@ -62,7 +62,6 @@ public class MyResource { public MyResource() { strings = new ArrayList<>(); - System.out.println("******* init"); } @GET diff --git a/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/TestServlet.java b/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/TestServlet.java deleted file mode 100644 index c53826cd2..000000000 --- a/jaxrs/singleton-application/src/main/java/org/javaee7/jaxrs/singelton/application/TestServlet.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.singelton.application; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("JAX-RS 2 Client API"); - out.println(""); - out.println(""); - out.println("

JAX-RS 2 Client API at " + request.getContextPath() + "

"); - out.println("Initializing client...
"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/myresource"); - - out.print("POSTing...
"); - // POST - target.request().post(Entity.text("pineapple")); - target.request().post(Entity.text("mango")); - target.request().post(Entity.text("kiwi")); - target.request().post(Entity.text("passion fruit")); - out.print("POSTed a few items ...
"); - - // GET - out.print("GETTing...
"); - String list = target.request().get(String.class); - out.format("GOT %1$s items
", list); - out.println("... done.
"); - - // GET with path param - out.print("GETTing with parameter...
"); - String person = target - .path("{id}") - .resolveTemplate("id", "2") - .request(MediaType.TEXT_PLAIN) - .get(String.class); - out.print("GOT person: " + person + "
"); - out.println("... done."); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/singleton-application/src/main/webapp/WEB-INF/beans.xml b/jaxrs/singleton-application/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index ba9b10154..000000000 --- a/jaxrs/singleton-application/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/jaxrs/singleton-application/src/main/webapp/index.jsp b/jaxrs/singleton-application/src/main/webapp/index.jsp deleted file mode 100644 index 1a76cd379..000000000 --- a/jaxrs/singleton-application/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JAX-RS 2 Singleton (using Application) - - -

JAX-RS 2 Singleton (using Application)

- Invoke the client. - - From fa5c95c6cab847362ca3e4ee7f3531b07a7e70c9 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 10:14:23 +0200 Subject: [PATCH 068/785] Cleaning up instructions --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8d11b29ed..3059772e0 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,15 @@ I don't plan to write any formal documentation, read the code. The [Java EE 7 Es #### For each sample #### -1. ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` +1. ``mvn package -DskipTests`` +2. ``mvn wildfly:start wildfly:deploy-only test -P wildfly`` ### Maven Plugins (GlassFish) ### -For each sample: ``mvn embedded-glassfish:deploy test -P glassfish`` +#### For each sample #### + +1. ``mvn package -DskipTests`` +2. ``mvn embedded-glassfish:deploy test -P glassfish`` ### NetBeans ### From e73854e33121c68235d209fb28ddbdc8ab2ad4ff Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 13:39:37 +0200 Subject: [PATCH 069/785] Fixed a typo --- .../java/org/javaee7/jpa/schemagen/scripts/TestServlet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java index 71241c973..adf84250d 100644 --- a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java +++ b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java @@ -72,7 +72,7 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re try (PrintWriter out = response.getWriter()) { out.println(""); out.println(""); - out.println("SList of Employees"); + out.println("List of Employees"); out.println(""); out.println(""); out.println("

List of Employees

"); From 6410300666b6f804e3203b67ba97104af44cd30e Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 13:41:29 +0200 Subject: [PATCH 070/785] Removing try-with-resources to allow any errors to show up on ServletOutputStream --- .../jpa/schemagen/scripts/TestServlet.java | 39 +++++++++---------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java index adf84250d..4f3ebbbdb 100644 --- a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java +++ b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/TestServlet.java @@ -53,13 +53,13 @@ */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { - - @Inject EmployeeBean bean; + + @Inject + EmployeeBean bean; /** - * Processes requests for both HTTP - * GET and - * POST methods. + * Processes requests for both HTTP GET and POST + * methods. * * @param request servlet request * @param response servlet response @@ -69,25 +69,23 @@ public class TestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println("List of Employees"); - out.println(""); - out.println(""); - out.println("

List of Employees

"); - for (Employee e : bean.get()) { - out.println(e.getName() + "
"); - } - out.println(""); - out.println(""); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println("List of Employees"); + out.println(""); + out.println(""); + out.println("

List of Employees

"); + for (Employee e : bean.get()) { + out.println(e.getName() + "
"); } + out.println(""); + out.println(""); } // /** - * Handles the HTTP - * GET method. + * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response @@ -101,8 +99,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } /** - * Handles the HTTP - * POST method. + * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response From ef3b243f1db0ba7cd9e39d2139f0d343ab83859d Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 13:59:42 +0200 Subject: [PATCH 071/785] Removing a redundant method --- .../java/org/javaee7/jpa/schemagen/scripts/EmployeeBean.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/EmployeeBean.java b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/EmployeeBean.java index cefb0d0de..13304627f 100644 --- a/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/EmployeeBean.java +++ b/jpa/schema-gen-scripts/src/main/java/org/javaee7/jpa/schemagen/scripts/EmployeeBean.java @@ -53,10 +53,6 @@ public class EmployeeBean { @PersistenceContext EntityManager em; - public void persist(Employee e) { - em.persist(e); - } - public List get() { return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); } From f70f5a978d8800cb63cd627df4dd35f1c1ec2448 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:12:50 +0200 Subject: [PATCH 072/785] Adding a new sample to demonstrate unsynchronized PC --- jpa/pom.xml | 3 +- jpa/unsynchronized-pc/pom.xml | 13 ++ .../jpa/unsynchronized/pc/Employee.java | 92 ++++++++++++ .../jpa/unsynchronized/pc/EmployeeBean.java | 70 +++++++++ .../jpa/unsynchronized/pc/TestServlet.java | 133 ++++++++++++++++++ .../src/main/resources/META-INF/create.sql | 1 + .../src/main/resources/META-INF/drop.sql | 1 + .../src/main/resources/META-INF/load.sql | 7 + .../main/resources/META-INF/persistence.xml | 18 +++ .../src/main/webapp/index.jsp | 56 ++++++++ 10 files changed, 393 insertions(+), 1 deletion(-) create mode 100644 jpa/unsynchronized-pc/pom.xml create mode 100644 jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/Employee.java create mode 100644 jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/EmployeeBean.java create mode 100644 jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java create mode 100644 jpa/unsynchronized-pc/src/main/resources/META-INF/create.sql create mode 100644 jpa/unsynchronized-pc/src/main/resources/META-INF/drop.sql create mode 100644 jpa/unsynchronized-pc/src/main/resources/META-INF/load.sql create mode 100644 jpa/unsynchronized-pc/src/main/resources/META-INF/persistence.xml create mode 100644 jpa/unsynchronized-pc/src/main/webapp/index.jsp diff --git a/jpa/pom.xml b/jpa/pom.xml index 60a0384ea..128c0de64 100644 --- a/jpa/pom.xml +++ b/jpa/pom.xml @@ -19,17 +19,18 @@ entitygraph listeners multiple-pu - schema-gen-metadata storedprocedure jndi-context locking-optimistic locking-pessimistic pu-typesafe + schema-gen-metadata schema-gen-scripts schema-gen-scripts-external schema-gen-scripts-generate native-sql native-sql-resultset-mapping + unsynchronized-pc diff --git a/jpa/unsynchronized-pc/pom.xml b/jpa/unsynchronized-pc/pom.xml new file mode 100644 index 000000000..52ba089c8 --- /dev/null +++ b/jpa/unsynchronized-pc/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.javaee7.jpa + jpa-samples + 1.0-SNAPSHOT + ../pom.xml + + + unsynchronized-pc + war + diff --git a/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/Employee.java b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/Employee.java new file mode 100644 index 000000000..904087939 --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/Employee.java @@ -0,0 +1,92 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.unsynchronized.pc; + +import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +/** + * @author Arun Gupta + */ +@Entity +@Table(name="EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC") +@NamedQueries({ + @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") +}) +public class Employee implements Serializable { + private static final long serialVersionUID = 1L; + @Id + private int id; + + @Column(length=50) + private String name; + + public Employee() { } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public Employee(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/EmployeeBean.java b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/EmployeeBean.java new file mode 100644 index 000000000..c54455ff7 --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/EmployeeBean.java @@ -0,0 +1,70 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.unsynchronized.pc; + +import java.util.List; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.SynchronizationType; + +/** + * @author Arun Gupta + */ +@Stateless +public class EmployeeBean { + + @PersistenceContext(synchronization = SynchronizationType.UNSYNCHRONIZED) + EntityManager em; + + public void persistWithoutJoin(Employee e) { + em.persist(e); + } + + public void persistWithJoin(Employee e) { + em.joinTransaction(); + em.persist(e); + } + + + public List get() { + return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); + } +} diff --git a/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java new file mode 100644 index 000000000..92f4b5f3d --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java @@ -0,0 +1,133 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.unsynchronized.pc; + +import java.io.IOException; +import java.io.PrintWriter; +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Arun Gupta + */ +@WebServlet(urlPatterns = {"/TestServlet"}) +public class TestServlet extends HttpServlet { + + @Inject + EmployeeBean bean; + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println("List of Employees"); + out.println(""); + out.println(""); + listEmployees(out, "Initial list", "Total == 7?"); + Employee e = new Employee(8, "Priya"); + bean.persistWithoutJoin(e); + listEmployees(out, "Unsynchronized PC has not joined a transaction", "Total == 7?"); + bean.persistWithJoin(e); + listEmployees(out, "Unsynchronized PC has joined a transaction", "Total == 8?"); + out.println(""); + out.println(""); + } + + private void listEmployees(PrintWriter out, String title, String result) { + out.println("

" + title + " (" + bean.get().size() + ") " + result + "

"); + for (Employee e : bean.get()) { + out.println(e.getName() + "
"); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// +} diff --git a/jpa/unsynchronized-pc/src/main/resources/META-INF/create.sql b/jpa/unsynchronized-pc/src/main/resources/META-INF/create.sql new file mode 100644 index 000000000..8ae9a8353 --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/resources/META-INF/create.sql @@ -0,0 +1 @@ +CREATE TABLE EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null) \ No newline at end of file diff --git a/jpa/unsynchronized-pc/src/main/resources/META-INF/drop.sql b/jpa/unsynchronized-pc/src/main/resources/META-INF/drop.sql new file mode 100644 index 000000000..57f31978a --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/resources/META-INF/drop.sql @@ -0,0 +1 @@ +DROP TABLE EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC \ No newline at end of file diff --git a/jpa/unsynchronized-pc/src/main/resources/META-INF/load.sql b/jpa/unsynchronized-pc/src/main/resources/META-INF/load.sql new file mode 100644 index 000000000..4f81f8024 --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/resources/META-INF/load.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (1, 'Penny') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (2, 'Sheldon') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (3, 'Amy') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (4, 'Leonard') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (5, 'Bernadette') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (6, 'Raj') +INSERT INTO EMPLOYEE_SCHEMA_UNSYNCHRONIZED_PC("ID", "NAME") VALUES (7, 'Howard') \ No newline at end of file diff --git a/jpa/unsynchronized-pc/src/main/resources/META-INF/persistence.xml b/jpa/unsynchronized-pc/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..010072bfd --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/jpa/unsynchronized-pc/src/main/webapp/index.jsp b/jpa/unsynchronized-pc/src/main/webapp/index.jsp new file mode 100644 index 000000000..1bec2dc71 --- /dev/null +++ b/jpa/unsynchronized-pc/src/main/webapp/index.jsp @@ -0,0 +1,56 @@ + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + JPA 2.1 Unsynchronized Persistence Context + + +

JPA 2.1 Unsynchronized Persistence Context

+ + Add & List employees. + + From 3c495ea2c74e70ce4a4772d28800473d79f2b596 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:15:40 +0200 Subject: [PATCH 073/785] Removing try-with-resources to allow any errors to show up on ServletOutputStream --- .../javaee7/jpa/listeners/TestServlet.java | 85 +++++++++---------- 1 file changed, 41 insertions(+), 44 deletions(-) diff --git a/jpa/listeners/src/main/java/org/javaee7/jpa/listeners/TestServlet.java b/jpa/listeners/src/main/java/org/javaee7/jpa/listeners/TestServlet.java index e8459447c..1e663f0a9 100644 --- a/jpa/listeners/src/main/java/org/javaee7/jpa/listeners/TestServlet.java +++ b/jpa/listeners/src/main/java/org/javaee7/jpa/listeners/TestServlet.java @@ -61,16 +61,16 @@ */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { - + @PersistenceUnit EntityManagerFactory emf; - - @EJB MovieBean bean; + + @EJB + MovieBean bean; /** - * Processes requests for both HTTP - * GET and - * POST methods. + * Processes requests for both HTTP GET and POST + * methods. * * @param request servlet request * @param response servlet response @@ -80,48 +80,46 @@ public class TestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("JPA Listeners"); - out.println(""); - out.println(""); - out.println("

JPA Listeners

"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + out.println("JPA Listeners"); + out.println(""); + out.println(""); + out.println("

JPA Listeners

"); - System.out.println("--> Listing movies"); - for (Movie m : bean.listMovies()) { - System.out.println(m.getName()); - } - System.out.println("--> Creating a movie"); - bean.createMovie(); - System.out.println("--> Listing movies"); - for (Movie m : bean.listMovies()) { - System.out.println(m.getName()); - } - System.out.println("--> Updating a movie"); - bean.updateMovie(); - System.out.println("--> Listing movies"); - for (Movie m : bean.listMovies()) { - System.out.println(m.getName()); - } - System.out.println("--> Deleting a movie"); - bean.deleteMovie(); - System.out.println("--> Listing movies"); - for (Movie m : bean.listMovies()) { - System.out.println(m.getName()); - } - out.println("Check \"server.log\" for output messages from listeners."); - - out.println(""); - out.println(""); + System.out.println("--> Listing movies"); + for (Movie m : bean.listMovies()) { + System.out.println(m.getName()); + } + System.out.println("--> Creating a movie"); + bean.createMovie(); + System.out.println("--> Listing movies"); + for (Movie m : bean.listMovies()) { + System.out.println(m.getName()); } + System.out.println("--> Updating a movie"); + bean.updateMovie(); + System.out.println("--> Listing movies"); + for (Movie m : bean.listMovies()) { + System.out.println(m.getName()); + } + System.out.println("--> Deleting a movie"); + bean.deleteMovie(); + System.out.println("--> Listing movies"); + for (Movie m : bean.listMovies()) { + System.out.println(m.getName()); + } + out.println("Check \"server.log\" for output messages from listeners."); + + out.println(""); + out.println(""); } // /** - * Handles the HTTP - * GET method. + * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response @@ -134,8 +132,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } /** - * Handles the HTTP - * POST method. + * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response From ab3ff87e88c295bc868ec53c57eecbdd19c1f422 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:42:25 +0200 Subject: [PATCH 074/785] Better output statements --- .../org/javaee7/jpa/unsynchronized/pc/TestServlet.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java index 92f4b5f3d..b475a1072 100644 --- a/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java +++ b/jpa/unsynchronized-pc/src/main/java/org/javaee7/jpa/unsynchronized/pc/TestServlet.java @@ -72,15 +72,16 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re PrintWriter out = response.getWriter(); out.println(""); out.println(""); - out.println("List of Employees"); + out.println("Unsynchronized Persistence Context"); out.println(""); out.println(""); + out.println("

Unsynchronized Persistence Context

"); listEmployees(out, "Initial list", "Total == 7?"); Employee e = new Employee(8, "Priya"); bean.persistWithoutJoin(e); - listEmployees(out, "Unsynchronized PC has not joined a transaction", "Total == 7?"); + listEmployees(out, "PC has not joined a transaction", "Total == 7?"); bean.persistWithJoin(e); - listEmployees(out, "Unsynchronized PC has joined a transaction", "Total == 8?"); + listEmployees(out, "PC has joined a transaction", "Total == 8?"); out.println(""); out.println(""); } From 5f2e0e419441259b269aabe53a5f37f1339455d6 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:47:06 +0200 Subject: [PATCH 075/785] Adding extended persistence context sample, need further investigation --- jpa/extended-pc/pom.xml | 13 ++ .../org/javaee7/jpa/extended/pc/Employee.java | 92 ++++++++++++ .../javaee7/jpa/extended/pc/EmployeeBean.java | 72 ++++++++++ .../javaee7/jpa/extended/pc/TestServlet.java | 134 ++++++++++++++++++ .../src/main/resources/META-INF/create.sql | 1 + .../src/main/resources/META-INF/drop.sql | 1 + .../src/main/resources/META-INF/load.sql | 7 + .../main/resources/META-INF/persistence.xml | 18 +++ jpa/extended-pc/src/main/webapp/index.jsp | 56 ++++++++ 9 files changed, 394 insertions(+) create mode 100644 jpa/extended-pc/pom.xml create mode 100644 jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/Employee.java create mode 100644 jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/EmployeeBean.java create mode 100644 jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/TestServlet.java create mode 100644 jpa/extended-pc/src/main/resources/META-INF/create.sql create mode 100644 jpa/extended-pc/src/main/resources/META-INF/drop.sql create mode 100644 jpa/extended-pc/src/main/resources/META-INF/load.sql create mode 100644 jpa/extended-pc/src/main/resources/META-INF/persistence.xml create mode 100644 jpa/extended-pc/src/main/webapp/index.jsp diff --git a/jpa/extended-pc/pom.xml b/jpa/extended-pc/pom.xml new file mode 100644 index 000000000..5deef5bdb --- /dev/null +++ b/jpa/extended-pc/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.javaee7.jpa + jpa-samples + 1.0-SNAPSHOT + ../pom.xml + + + extended-pc + war + diff --git a/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/Employee.java b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/Employee.java new file mode 100644 index 000000000..c1c4d4977 --- /dev/null +++ b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/Employee.java @@ -0,0 +1,92 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.extended.pc; + +import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +/** + * @author Arun Gupta + */ +@Entity +@Table(name="EMPLOYEE_SCHEMA_EXTENDED_PC") +@NamedQueries({ + @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") +}) +public class Employee implements Serializable { + private static final long serialVersionUID = 1L; + @Id + private int id; + + @Column(length=50) + private String name; + + public Employee() { } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public Employee(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/EmployeeBean.java b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/EmployeeBean.java new file mode 100644 index 000000000..70082c99e --- /dev/null +++ b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/EmployeeBean.java @@ -0,0 +1,72 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.extended.pc; + +import java.util.List; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +/** + * @author Arun Gupta + */ +@Stateful +public class EmployeeBean { + + @PersistenceContext(type = PersistenceContextType.EXTENDED) + EntityManager em; + + @TransactionAttribute(TransactionAttributeType.NEVER) + public void persistWithoutTransaction(Employee e) { + em.persist(e); + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public void persistWithTransaction(Employee e) { + em.persist(e); + } + + public List get() { + return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); + } +} diff --git a/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/TestServlet.java b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/TestServlet.java new file mode 100644 index 000000000..a559cc1e2 --- /dev/null +++ b/jpa/extended-pc/src/main/java/org/javaee7/jpa/extended/pc/TestServlet.java @@ -0,0 +1,134 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.extended.pc; + +import java.io.IOException; +import java.io.PrintWriter; +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Arun Gupta + */ +@WebServlet(urlPatterns = {"/TestServlet"}) +public class TestServlet extends HttpServlet { + + @Inject + EmployeeBean bean; + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println("Extended Persistence Context"); + out.println(""); + out.println(""); + out.println("

Extended Persistence Context

"); + listEmployees(out, "Initial list", "Total == 7?"); + Employee e = new Employee(8, "Priya"); + bean.persistWithoutTransaction(e); + listEmployees(out, "PC without a transaction", "Total == 7?"); + bean.persistWithTransaction(e); + listEmployees(out, "PC with a transaction", "Total == 8?"); + out.println(""); + out.println(""); + } + + private void listEmployees(PrintWriter out, String title, String result) { + out.println("

" + title + " (" + bean.get().size() + ") " + result + "

"); + for (Employee e : bean.get()) { + out.println(e.getName() + "
"); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// +} diff --git a/jpa/extended-pc/src/main/resources/META-INF/create.sql b/jpa/extended-pc/src/main/resources/META-INF/create.sql new file mode 100644 index 000000000..2b9dc3a28 --- /dev/null +++ b/jpa/extended-pc/src/main/resources/META-INF/create.sql @@ -0,0 +1 @@ +CREATE TABLE EMPLOYEE_SCHEMA_EXTENDED_PC ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null) \ No newline at end of file diff --git a/jpa/extended-pc/src/main/resources/META-INF/drop.sql b/jpa/extended-pc/src/main/resources/META-INF/drop.sql new file mode 100644 index 000000000..a75c07a18 --- /dev/null +++ b/jpa/extended-pc/src/main/resources/META-INF/drop.sql @@ -0,0 +1 @@ +DROP TABLE EMPLOYEE_SCHEMA_EXTENDED_PC \ No newline at end of file diff --git a/jpa/extended-pc/src/main/resources/META-INF/load.sql b/jpa/extended-pc/src/main/resources/META-INF/load.sql new file mode 100644 index 000000000..44c6793d5 --- /dev/null +++ b/jpa/extended-pc/src/main/resources/META-INF/load.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (1, 'Penny') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (2, 'Sheldon') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (3, 'Amy') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (4, 'Leonard') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (5, 'Bernadette') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (6, 'Raj') +INSERT INTO EMPLOYEE_SCHEMA_EXTENDED_PC("ID", "NAME") VALUES (7, 'Howard') \ No newline at end of file diff --git a/jpa/extended-pc/src/main/resources/META-INF/persistence.xml b/jpa/extended-pc/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..010072bfd --- /dev/null +++ b/jpa/extended-pc/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/jpa/extended-pc/src/main/webapp/index.jsp b/jpa/extended-pc/src/main/webapp/index.jsp new file mode 100644 index 000000000..c5fab84e0 --- /dev/null +++ b/jpa/extended-pc/src/main/webapp/index.jsp @@ -0,0 +1,56 @@ + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + JPA 2.1 Extended Persistence Context + + +

JPA 2.1 Extended Persistence Context

+ + Add & List employees. + + From 09898c725756645494f2e3ff24f3c60dc8b3991e Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:51:44 +0200 Subject: [PATCH 076/785] Added extended-pc --- jpa/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/jpa/pom.xml b/jpa/pom.xml index 128c0de64..2ad3e8630 100644 --- a/jpa/pom.xml +++ b/jpa/pom.xml @@ -31,6 +31,7 @@ native-sql native-sql-resultset-mapping unsynchronized-pc + extended-pc From 5561bfc53bfc36ea2d69152b97c82a9aacd37c55 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:54:02 +0200 Subject: [PATCH 077/785] Fixing the table name --- .../src/main/java/org/javaee7/jpa/schemagen/Employee.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jpa/schema-gen-metadata/src/main/java/org/javaee7/jpa/schemagen/Employee.java b/jpa/schema-gen-metadata/src/main/java/org/javaee7/jpa/schemagen/Employee.java index fd1cb84af..0d62cfc23 100644 --- a/jpa/schema-gen-metadata/src/main/java/org/javaee7/jpa/schemagen/Employee.java +++ b/jpa/schema-gen-metadata/src/main/java/org/javaee7/jpa/schemagen/Employee.java @@ -53,7 +53,7 @@ * @author Arun Gupta */ @Entity -@Table(name = "EMPLOYEE_SCHEMA_GEN") +@Table(name = "EMPLOYEE_SCHEMA_GEN_METADATA") @NamedQueries({ @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") }) From 9b5e3e7272d7538a7d7629ae1dce9fb33c358009 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 14:55:12 +0200 Subject: [PATCH 078/785] Removing redundant attributes --- jpa/schema-gen-metadata/pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/jpa/schema-gen-metadata/pom.xml b/jpa/schema-gen-metadata/pom.xml index 997704741..6238e013b 100644 --- a/jpa/schema-gen-metadata/pom.xml +++ b/jpa/schema-gen-metadata/pom.xml @@ -8,9 +8,6 @@ ../pom.xml - org.javaee7.jpa schema-gen-metadata - 1.0-SNAPSHOT war - schema-gen-metadata From 6b614f97fae6b6e452ebe2b9246b3e130da30762 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 15:12:30 +0200 Subject: [PATCH 079/785] New sample to show @Index usage --- jpa/pom.xml | 1 + jpa/schema-gen-index/pom.xml | 13 ++++ .../java/org/javaee7/jpa/index/Employee.java | 53 ++++++++++++++++ .../org/javaee7/jpa/index/EmployeeBean.java | 63 +++++++++++++++++++ .../main/resources/META-INF/persistence.xml | 14 +++++ .../src/main/webapp/index.jsp | 60 ++++++++++++++++++ 6 files changed, 204 insertions(+) create mode 100644 jpa/schema-gen-index/pom.xml create mode 100644 jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/Employee.java create mode 100644 jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/EmployeeBean.java create mode 100644 jpa/schema-gen-index/src/main/resources/META-INF/persistence.xml create mode 100644 jpa/schema-gen-index/src/main/webapp/index.jsp diff --git a/jpa/pom.xml b/jpa/pom.xml index 2ad3e8630..75890d840 100644 --- a/jpa/pom.xml +++ b/jpa/pom.xml @@ -28,6 +28,7 @@ schema-gen-scripts schema-gen-scripts-external schema-gen-scripts-generate + schema-gen-index native-sql native-sql-resultset-mapping unsynchronized-pc diff --git a/jpa/schema-gen-index/pom.xml b/jpa/schema-gen-index/pom.xml new file mode 100644 index 000000000..8f962972e --- /dev/null +++ b/jpa/schema-gen-index/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + + org.javaee7.jpa + jpa-samples + 1.0-SNAPSHOT + ../pom.xml + + + schema-gen-index + war + diff --git a/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/Employee.java b/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/Employee.java new file mode 100644 index 000000000..63d64c986 --- /dev/null +++ b/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/Employee.java @@ -0,0 +1,53 @@ +package org.javaee7.jpa.index; + +import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Index; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +/** + * @author Arun Gupta + */ +@Entity +@Table(name = "EMPLOYEE_SCHEMA_GEN_INDEX", + indexes = @Index(columnList="NAME")) +@NamedQueries({ + @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") +}) +public class Employee implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(length=40) + private String name; + + public Employee() { } + + public Employee(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/EmployeeBean.java b/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/EmployeeBean.java new file mode 100644 index 000000000..4a028cf11 --- /dev/null +++ b/jpa/schema-gen-index/src/main/java/org/javaee7/jpa/index/EmployeeBean.java @@ -0,0 +1,63 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.index; + +import java.util.List; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +/** + * @author Arun Gupta + */ +@Stateless +public class EmployeeBean { + + @PersistenceContext + EntityManager em; + + public void persist(Employee e) { + em.persist(e); + } + + public List get() { + return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); + } +} diff --git a/jpa/schema-gen-index/src/main/resources/META-INF/persistence.xml b/jpa/schema-gen-index/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..b5bbf1244 --- /dev/null +++ b/jpa/schema-gen-index/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/jpa/schema-gen-index/src/main/webapp/index.jsp b/jpa/schema-gen-index/src/main/webapp/index.jsp new file mode 100644 index 000000000..750316d2f --- /dev/null +++ b/jpa/schema-gen-index/src/main/webapp/index.jsp @@ -0,0 +1,60 @@ + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + JPA 2.1 Schema Generation with @Index + + +

JPA 2.1 Schema Generation with @Index

+ +

Check for generated scripts in + /tmp/create.sql and look for + statements like: +

+ CREATE INDEX INDEX_EMPLOYEE_SCHEMA_GEN_INDEX_NAME ON EMPLOYEE_SCHEMA_GEN_INDEX (NAME) + + From 42b9f67bbcb2cffad6ee2a57a66f0067b99ffb03 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 17:13:13 +0200 Subject: [PATCH 080/785] Starting a new sample for @Converter and @Convert --- jpa/jpa-converter/pom.xml | 13 ++ .../org/javaee7/jpa/converter/Employee.java | 71 ++++++++++ .../javaee7/jpa/converter/EmployeeBean.java | 24 ++++ .../jpa/converter/EmployeeDateConverter.java | 38 +++++ .../org/javaee7/jpa/converter/MyDate.java | 33 +++++ .../javaee7/jpa/converter/TestServlet.java | 132 ++++++++++++++++++ .../src/main/resources/META-INF/create.sql | 1 + .../src/main/resources/META-INF/drop.sql | 1 + .../src/main/resources/META-INF/load.sql | 7 + .../main/resources/META-INF/persistence.xml | 18 +++ jpa/jpa-converter/src/main/webapp/index.jsp | 57 ++++++++ 11 files changed, 395 insertions(+) create mode 100644 jpa/jpa-converter/pom.xml create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeBean.java create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java create mode 100644 jpa/jpa-converter/src/main/resources/META-INF/create.sql create mode 100644 jpa/jpa-converter/src/main/resources/META-INF/drop.sql create mode 100644 jpa/jpa-converter/src/main/resources/META-INF/load.sql create mode 100644 jpa/jpa-converter/src/main/resources/META-INF/persistence.xml create mode 100644 jpa/jpa-converter/src/main/webapp/index.jsp diff --git a/jpa/jpa-converter/pom.xml b/jpa/jpa-converter/pom.xml new file mode 100644 index 000000000..46d352793 --- /dev/null +++ b/jpa/jpa-converter/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.javaee7.jpa + jpa-samples + 1.0-SNAPSHOT + ../pom.xml + + + jpa-converter + war + diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java new file mode 100644 index 000000000..a9ed94d00 --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java @@ -0,0 +1,71 @@ +package org.javaee7.jpa.converter; + +import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +/** + * @author Arun Gupta + */ +@Entity +@Table(name="EMPLOYEE_SCHEMA_CONVERTER") +@NamedQueries({ + @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") +}) +public class Employee implements Serializable { + private static final long serialVersionUID = 1L; + @Id + private int id; + + @Column(length=50) + private String name; + + @Convert(converter = EmployeeDateConverter.class) + private String dob; + + public Employee() { } + + public Employee(String name) { + this.name = name; + } + + public Employee(int id, String name, String dob) { + this.id = id; + this.name = name; + this.dob = dob; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + @Override + public String toString() { + return name + "(" + dob + ")"; + } +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeBean.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeBean.java new file mode 100644 index 000000000..248d4740c --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeBean.java @@ -0,0 +1,24 @@ +package org.javaee7.jpa.converter; + +import java.util.List; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +/** + * @author Arun Gupta + */ +@Stateless +public class EmployeeBean { + + @PersistenceContext + EntityManager em; + + public void persist(Employee e) { + em.persist(e); + } + + public List get() { + return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); + } +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java new file mode 100644 index 000000000..0528e3040 --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jpa.converter; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +/** + * @author Arun Gupta + */ +@Converter +public class EmployeeDateConverter implements AttributeConverter { + final SimpleDateFormat format = new SimpleDateFormat("M/dd/yy"); + + @Override + public String convertToDatabaseColumn(MyDate attribute) { + return attribute.getDate().toString(); + } + + @Override + public MyDate convertToEntityAttribute(String date) { + Date d = null; + try { + d = format.parse(date); + } catch (ParseException ex) { + ex.printStackTrace(); + } + return new MyDate(d); + } + +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java new file mode 100644 index 000000000..168f7493a --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java @@ -0,0 +1,33 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jpa.converter; + +import java.util.Date; + +/** + * @author Arun Gupta + */ +public class MyDate { + Date date; + + public MyDate() { + } + + public MyDate(Date date) { + this.date = date; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java new file mode 100644 index 000000000..e775e9dc9 --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java @@ -0,0 +1,132 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package org.javaee7.jpa.converter; + +import java.io.IOException; +import java.io.PrintWriter; +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Arun Gupta + */ +@WebServlet(urlPatterns = {"/TestServlet"}) +public class TestServlet extends HttpServlet { + + @Inject + EmployeeBean bean; + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println("JPA 2.1 Converter"); + out.println(""); + out.println(""); + out.println("

JPA 2.1 Converter

"); + out.println("Original list of employees"); + for (Employee e : bean.get()) { + out.println(e + "
"); + } + out.println("

Adding a new employee

"); + Employee emp = new Employee(8, "Lucy", "3/31/1980"); + bean.persist(emp); + out.println("Updated list of employees"); + for (Employee e : bean.get()) { + out.println(e + "
"); + } + out.println(""); + out.println(""); + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// +} diff --git a/jpa/jpa-converter/src/main/resources/META-INF/create.sql b/jpa/jpa-converter/src/main/resources/META-INF/create.sql new file mode 100644 index 000000000..4ee28659e --- /dev/null +++ b/jpa/jpa-converter/src/main/resources/META-INF/create.sql @@ -0,0 +1 @@ +CREATE TABLE EMPLOYEE_SCHEMA_CONVERTER ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null, "DOB" VARCHAR(10) not null) \ No newline at end of file diff --git a/jpa/jpa-converter/src/main/resources/META-INF/drop.sql b/jpa/jpa-converter/src/main/resources/META-INF/drop.sql new file mode 100644 index 000000000..20101ab71 --- /dev/null +++ b/jpa/jpa-converter/src/main/resources/META-INF/drop.sql @@ -0,0 +1 @@ +DROP TABLE EMPLOYEE_SCHEMA_CONVERTER \ No newline at end of file diff --git a/jpa/jpa-converter/src/main/resources/META-INF/load.sql b/jpa/jpa-converter/src/main/resources/META-INF/load.sql new file mode 100644 index 000000000..948d76b56 --- /dev/null +++ b/jpa/jpa-converter/src/main/resources/META-INF/load.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (1, 'Leonard', '12/9/1980') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (2, 'Sheldon', '3/24/1973') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (3, 'Penny', '11/30/1985') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (4, 'Raj', '4/30/1975') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (5, 'Howard', '12/9/1980') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (6, 'Bernadette', '6/23/1980') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (7, 'Amy', '12/12/1975') \ No newline at end of file diff --git a/jpa/jpa-converter/src/main/resources/META-INF/persistence.xml b/jpa/jpa-converter/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..010072bfd --- /dev/null +++ b/jpa/jpa-converter/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/jpa/jpa-converter/src/main/webapp/index.jsp b/jpa/jpa-converter/src/main/webapp/index.jsp new file mode 100644 index 000000000..533145e82 --- /dev/null +++ b/jpa/jpa-converter/src/main/webapp/index.jsp @@ -0,0 +1,57 @@ + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + JPA 2.1 Converter + + +

JPA 2.1 Converter

+ + List & Add employees. + + + From 49a7d9afe2bf7974c46f0a4a2af09e4a612aca2a Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 17:31:29 +0200 Subject: [PATCH 081/785] Temporal attributes cannot be used with @Convert and so changing to CreditCard based upon Antonio's slide deck --- .../org/javaee7/jpa/converter/CreditCard.java | 38 +++++++++++++++++++ .../jpa/converter/CreditCardConverter.java | 28 ++++++++++++++ .../org/javaee7/jpa/converter/Employee.java | 21 +++++----- .../jpa/converter/EmployeeDateConverter.java | 38 ------------------- .../org/javaee7/jpa/converter/MyDate.java | 33 ---------------- .../src/main/resources/META-INF/create.sql | 2 +- .../src/main/resources/META-INF/load.sql | 13 +++---- 7 files changed, 84 insertions(+), 89 deletions(-) create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java create mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCardConverter.java delete mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java delete mode 100644 jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java new file mode 100644 index 000000000..db48e1987 --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jpa.converter; + +import java.util.Date; + +/** + * @author Arun Gupta + */ +public class CreditCard { + String cardNumber; + + public CreditCard() { + } + + public CreditCard(String cardNumber) { + this.cardNumber = cardNumber; + } + + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + @Override + public String toString() { + return cardNumber; + } + + +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCardConverter.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCardConverter.java new file mode 100644 index 000000000..6f1ef73ed --- /dev/null +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCardConverter.java @@ -0,0 +1,28 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.jpa.converter; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +/** + * @author Arun Gupta + */ +@Converter +public class CreditCardConverter implements AttributeConverter { + + @Override + public String convertToDatabaseColumn(CreditCard attribute) { + return attribute.toString(); + } + + @Override + public CreditCard convertToEntityAttribute(String card) { + return new CreditCard(card); + } + +} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java index a9ed94d00..69691e02e 100644 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java @@ -1,6 +1,7 @@ package org.javaee7.jpa.converter; import java.io.Serializable; +import java.util.Date; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; @@ -25,8 +26,8 @@ public class Employee implements Serializable { @Column(length=50) private String name; - @Convert(converter = EmployeeDateConverter.class) - private String dob; + @Convert(converter = CreditCardConverter.class) + private String card; public Employee() { } @@ -34,10 +35,10 @@ public Employee(String name) { this.name = name; } - public Employee(int id, String name, String dob) { + public Employee(int id, String name, String card) { this.id = id; this.name = name; - this.dob = dob; + this.card = card; } public int getId() { @@ -56,16 +57,16 @@ public void setName(String name) { this.name = name; } - public String getDob() { - return dob; + public String getCard() { + return card; } - public void setDob(String dob) { - this.dob = dob; + public void setCard(String card) { + this.card = card; } - + @Override public String toString() { - return name + "(" + dob + ")"; + return name + "(" + card + ")"; } } diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java deleted file mode 100644 index 0528e3040..000000000 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/EmployeeDateConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - -package org.javaee7.jpa.converter; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; - -/** - * @author Arun Gupta - */ -@Converter -public class EmployeeDateConverter implements AttributeConverter { - final SimpleDateFormat format = new SimpleDateFormat("M/dd/yy"); - - @Override - public String convertToDatabaseColumn(MyDate attribute) { - return attribute.getDate().toString(); - } - - @Override - public MyDate convertToEntityAttribute(String date) { - Date d = null; - try { - d = format.parse(date); - } catch (ParseException ex) { - ex.printStackTrace(); - } - return new MyDate(d); - } - -} diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java deleted file mode 100644 index 168f7493a..000000000 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/MyDate.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ - -package org.javaee7.jpa.converter; - -import java.util.Date; - -/** - * @author Arun Gupta - */ -public class MyDate { - Date date; - - public MyDate() { - } - - public MyDate(Date date) { - this.date = date; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - -} diff --git a/jpa/jpa-converter/src/main/resources/META-INF/create.sql b/jpa/jpa-converter/src/main/resources/META-INF/create.sql index 4ee28659e..eea2051a5 100644 --- a/jpa/jpa-converter/src/main/resources/META-INF/create.sql +++ b/jpa/jpa-converter/src/main/resources/META-INF/create.sql @@ -1 +1 @@ -CREATE TABLE EMPLOYEE_SCHEMA_CONVERTER ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null, "DOB" VARCHAR(10) not null) \ No newline at end of file +CREATE TABLE EMPLOYEE_SCHEMA_CONVERTER ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null, "CARD" VARCHAR(15) not null) \ No newline at end of file diff --git a/jpa/jpa-converter/src/main/resources/META-INF/load.sql b/jpa/jpa-converter/src/main/resources/META-INF/load.sql index 948d76b56..48dc3c346 100644 --- a/jpa/jpa-converter/src/main/resources/META-INF/load.sql +++ b/jpa/jpa-converter/src/main/resources/META-INF/load.sql @@ -1,7 +1,6 @@ -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (1, 'Leonard', '12/9/1980') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (2, 'Sheldon', '3/24/1973') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (3, 'Penny', '11/30/1985') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (4, 'Raj', '4/30/1975') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (5, 'Howard', '12/9/1980') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (6, 'Bernadette', '6/23/1980') -INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "DOB") VALUES (7, 'Amy', '12/12/1975') \ No newline at end of file +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (1, 'Leonard', '11-22-33-44') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (2, 'Sheldon', '22-33-44-55') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (3, 'Penny', '33-44-55-66') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (4, 'Raj', '44-55-66-77') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (5, 'Howard', '55-66-77-88') +INSERT INTO EMPLOYEE_SCHEMA_CONVERTER("ID", "NAME", "CARD") VALUES (6, 'Bernadette', '66-77-88-99') \ No newline at end of file From 7185c9ddec0e84df78aac78383aa7be86b1ef06b Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 17:31:45 +0200 Subject: [PATCH 082/785] Adding the jpa-converter module --- jpa/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/jpa/pom.xml b/jpa/pom.xml index 75890d840..65ff4cc53 100644 --- a/jpa/pom.xml +++ b/jpa/pom.xml @@ -33,6 +33,7 @@ native-sql-resultset-mapping unsynchronized-pc extended-pc + jpa-converter From b8d4b7661762a521d6528afad7e36dbe45723ccc Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 17:55:03 +0200 Subject: [PATCH 083/785] Sample is now working --- .../java/org/javaee7/jpa/converter/CreditCard.java | 4 ++-- .../main/java/org/javaee7/jpa/converter/Employee.java | 10 +++++----- .../java/org/javaee7/jpa/converter/TestServlet.java | 7 ++++--- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java index db48e1987..d46eb3d47 100644 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/CreditCard.java @@ -6,12 +6,12 @@ package org.javaee7.jpa.converter; -import java.util.Date; +import java.io.Serializable; /** * @author Arun Gupta */ -public class CreditCard { +public class CreditCard implements Serializable { String cardNumber; public CreditCard() { diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java index 69691e02e..8d4280fed 100644 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/Employee.java @@ -27,7 +27,7 @@ public class Employee implements Serializable { private String name; @Convert(converter = CreditCardConverter.class) - private String card; + private CreditCard card; public Employee() { } @@ -35,7 +35,7 @@ public Employee(String name) { this.name = name; } - public Employee(int id, String name, String card) { + public Employee(int id, String name, CreditCard card) { this.id = id; this.name = name; this.card = card; @@ -57,16 +57,16 @@ public void setName(String name) { this.name = name; } - public String getCard() { + public CreditCard getCard() { return card; } - public void setCard(String card) { + public void setCard(CreditCard card) { this.card = card; } @Override public String toString() { - return name + "(" + card + ")"; + return name + " (" + card + ")"; } } diff --git a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java index e775e9dc9..db6e5ef60 100644 --- a/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java +++ b/jpa/jpa-converter/src/main/java/org/javaee7/jpa/converter/TestServlet.java @@ -76,14 +76,15 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re out.println(""); out.println(""); out.println("

JPA 2.1 Converter

"); - out.println("Original list of employees"); + out.println("

Original list of employees (" + bean.get().size() + ")

"); for (Employee e : bean.get()) { out.println(e + "
"); } out.println("

Adding a new employee

"); - Employee emp = new Employee(8, "Lucy", "3/31/1980"); + Employee emp = new Employee(8, "Lucy", new CreditCard("22-44-66-88")); bean.persist(emp); - out.println("Updated list of employees"); + out.println("Added"); + out.println("

Updated list of employees(" + bean.get().size() + ")

"); for (Employee e : bean.get()) { out.println(e + "
"); } From 1c0aaedf651be368dadeb8caf7643e25342a0799 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 23:22:12 +0200 Subject: [PATCH 084/785] New sample for asynchronous EJB - need to add different use cases --- ejb/async-ejb/pom.xml | 13 +++ .../org/javaee7/ejb/async/MyAsyncBean.java | 28 +++++ .../org/javaee7/ejb/async/TestServlet.java | 106 ++++++++++++++++++ ejb/async-ejb/src/main/webapp/index.jsp | 56 +++++++++ .../ejb/async/AccountSessionBeanTest.java | 53 +++++++++ 5 files changed, 256 insertions(+) create mode 100644 ejb/async-ejb/pom.xml create mode 100644 ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java create mode 100644 ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java create mode 100644 ejb/async-ejb/src/main/webapp/index.jsp create mode 100644 ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java diff --git a/ejb/async-ejb/pom.xml b/ejb/async-ejb/pom.xml new file mode 100644 index 000000000..9c09939e2 --- /dev/null +++ b/ejb/async-ejb/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + + org.javaee7.ejb + ejb-samples + 1.0-SNAPSHOT + ../pom.xml + + + async-ejb + war + diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java new file mode 100644 index 000000000..e0ce2b7ba --- /dev/null +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java @@ -0,0 +1,28 @@ +package org.javaee7.ejb.async; + +import java.util.concurrent.Future; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.ejb.AsyncResult; +import javax.ejb.Stateless; + +/** + * @author Arun Gupta + */ +@Stateless +public class MyAsyncBean { + + public Future addNumbers(int n1, int n2) { + try { + // simulating a long running query + Thread.sleep(3000); + } catch (InterruptedException ex) { + Logger.getLogger(MyAsyncBean.class.getName()).log(Level.SEVERE, null, ex); + } + return new AsyncResult(n1 + n2); + } + + public void doSomething(String what) { + System.out.println("Just did " + what); + } +} diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java new file mode 100644 index 000000000..dcad5ad2d --- /dev/null +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java @@ -0,0 +1,106 @@ +package org.javaee7.ejb.async; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Arun Gupta + */ +@WebServlet(urlPatterns = {"/TestServlet"}) +public class TestServlet extends HttpServlet { + @Inject MyAsyncBean bean;; + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + out.println(""); + out.println(""); + out.println(""); + out.println("Asynchronous EJB"); + out.println(""); + out.println(""); + out.println("

Asynchronous EJB

"); + Future result = bean.addNumbers(2, 4); + while (true) { + out.println("
Waiting ..."); + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); + } + if (result.isDone()) { + out.println("
Result is now ready..."); + try { + out.println("
Got the result: " + result.get()); + } catch (InterruptedException | ExecutionException ex) { + Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); + } + break; + } + } + + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/ejb/async-ejb/src/main/webapp/index.jsp b/ejb/async-ejb/src/main/webapp/index.jsp new file mode 100644 index 000000000..aba30255f --- /dev/null +++ b/ejb/async-ejb/src/main/webapp/index.jsp @@ -0,0 +1,56 @@ + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + EJB : Async + + +

EJB : Async

+ + Call asynchronous bean + + diff --git a/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java b/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java new file mode 100644 index 000000000..62ef486d3 --- /dev/null +++ b/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java @@ -0,0 +1,53 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.javaee7.ejb.async; + +import org.javaee7.ejb.async.MyAsyncBean; +import javax.ejb.EJB; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * @author Arun Gupta + */ +public class AccountSessionBeanTest { + @EJB MyAsyncBean bean; + + /** + * Arquillian specific method for creating a file which can be deployed + * while executing the test. + * + * @return a war file + */ + public static WebArchive createDeployment() { + WebArchive war = ShrinkWrap.create(WebArchive.class). + addClass(MyAsyncBean.class); + System.out.println(war.toString(true)); + return war; + } + + /** + * Test of withdraw method, of class AccountSessionBean. + */ +// @Test + public void testWithdraw() { +// String result = bean.withdraw((float)5.0); +// assertEquals("Withdrawn: 5.0", result); + } + + /** + * Test of deposit method, of class AccountSessionBean. + */ +// @Test + public void testDeposit() { +// String result = bean.withdraw((float)10.0); +// assertEquals("Deposited: 10.0", result); + } + +} From 74a18b85abb585b221ef0bf94d960cf9f2e211d2 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 23:25:13 +0200 Subject: [PATCH 085/785] Adding @Asynchronous on method - works on both WildFly and GlassFish --- .../src/main/java/org/javaee7/ejb/async/MyAsyncBean.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java index e0ce2b7ba..b5d619fb1 100644 --- a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java @@ -4,6 +4,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.AsyncResult; +import javax.ejb.Asynchronous; import javax.ejb.Stateless; /** @@ -12,6 +13,7 @@ @Stateless public class MyAsyncBean { + @Asynchronous public Future addNumbers(int n1, int n2) { try { // simulating a long running query @@ -21,8 +23,4 @@ public Future addNumbers(int n1, int n2) { } return new AsyncResult(n1 + n2); } - - public void doSomething(String what) { - System.out.println("Just did " + what); - } } From 0f1cb049bfb17ea7a5c189f85f3533a1f9070c2e Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sat, 9 Nov 2013 23:33:23 +0200 Subject: [PATCH 086/785] Adding class-level and method-level annotations --- .../ejb/async/MyAsyncBeanClassLevel.java | 30 +++++++++++++++++++ ...cBean.java => MyAsyncBeanMethodLevel.java} | 9 ++++-- .../org/javaee7/ejb/async/TestServlet.java | 25 ++++++++++++++-- .../ejb/async/AccountSessionBeanTest.java | 6 ++-- 4 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanClassLevel.java rename ejb/async-ejb/src/main/java/org/javaee7/ejb/async/{MyAsyncBean.java => MyAsyncBeanMethodLevel.java} (67%) diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanClassLevel.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanClassLevel.java new file mode 100644 index 000000000..57c9878c5 --- /dev/null +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanClassLevel.java @@ -0,0 +1,30 @@ +package org.javaee7.ejb.async; + +import java.util.concurrent.Future; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.ejb.AsyncResult; +import javax.ejb.Asynchronous; +import javax.ejb.Stateless; + +/** + * @author Arun Gupta + */ +@Stateless +@Asynchronous +public class MyAsyncBeanClassLevel { + + public Future addNumbers(int n1, int n2) { + try { + // simulating a long running query + Thread.sleep(3000); + } catch (InterruptedException ex) { + Logger.getLogger(MyAsyncBeanClassLevel.class.getName()).log(Level.SEVERE, null, ex); + } + return new AsyncResult(n1 + n2); + } + + public void doSomething(String what) { + System.out.println("Just did " + what); + } +} diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanMethodLevel.java similarity index 67% rename from ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java rename to ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanMethodLevel.java index b5d619fb1..9f8de0334 100644 --- a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBean.java +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/MyAsyncBeanMethodLevel.java @@ -11,7 +11,7 @@ * @author Arun Gupta */ @Stateless -public class MyAsyncBean { +public class MyAsyncBeanMethodLevel { @Asynchronous public Future addNumbers(int n1, int n2) { @@ -19,8 +19,13 @@ public Future addNumbers(int n1, int n2) { // simulating a long running query Thread.sleep(3000); } catch (InterruptedException ex) { - Logger.getLogger(MyAsyncBean.class.getName()).log(Level.SEVERE, null, ex); + Logger.getLogger(MyAsyncBeanMethodLevel.class.getName()).log(Level.SEVERE, null, ex); } return new AsyncResult(n1 + n2); } + + @Asynchronous + public void doSomething(String what) { + System.out.println("Just did " + what); + } } diff --git a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java index dcad5ad2d..3351f378b 100644 --- a/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java +++ b/ejb/async-ejb/src/main/java/org/javaee7/ejb/async/TestServlet.java @@ -18,7 +18,8 @@ */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { - @Inject MyAsyncBean bean;; + @Inject MyAsyncBeanMethodLevel methodBean; + @Inject MyAsyncBeanClassLevel classBean; /** * Processes requests for both HTTP GET and POST @@ -40,7 +41,8 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re out.println(""); out.println(""); out.println("

Asynchronous EJB

"); - Future result = bean.addNumbers(2, 4); + out.println("

Method-level annotation

"); + Future result = methodBean.addNumbers(2, 4); while (true) { out.println("
Waiting ..."); try { @@ -59,6 +61,25 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re } } + out.println("

Class-level annotation

"); + result = methodBean.addNumbers(2, 4); + while (true) { + out.println("
Waiting ..."); + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); + } + if (result.isDone()) { + out.println("
Result is now ready..."); + try { + out.println("
Got the result: " + result.get()); + } catch (InterruptedException | ExecutionException ex) { + Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); + } + break; + } + } out.println(""); out.println(""); } diff --git a/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java b/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java index 62ef486d3..8115fa86c 100644 --- a/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java +++ b/ejb/async-ejb/src/test/java/org/javaee7/ejb/async/AccountSessionBeanTest.java @@ -6,7 +6,7 @@ package org.javaee7.ejb.async; -import org.javaee7.ejb.async.MyAsyncBean; +import org.javaee7.ejb.async.MyAsyncBeanMethodLevel; import javax.ejb.EJB; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; @@ -17,7 +17,7 @@ * @author Arun Gupta */ public class AccountSessionBeanTest { - @EJB MyAsyncBean bean; + @EJB MyAsyncBeanMethodLevel bean; /** * Arquillian specific method for creating a file which can be deployed @@ -27,7 +27,7 @@ public class AccountSessionBeanTest { */ public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). - addClass(MyAsyncBean.class); + addClass(MyAsyncBeanMethodLevel.class); System.out.println(war.toString(true)); return war; } From ee3af546558017eb8390398272a7c4e7c0a560db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20Gr=C3=A9au?= Date: Sun, 10 Nov 2013 12:36:05 +0100 Subject: [PATCH 087/785] On Chrome/WildFly, REST client doesn't work. Seems that XMLHttpRequest need to be reopen before each POST request --- websocket/websocket-vs-rest/src/main/webapp/rest.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/websocket/websocket-vs-rest/src/main/webapp/rest.js b/websocket/websocket-vs-rest/src/main/webapp/rest.js index e192ad53e..c7c00b4b0 100644 --- a/websocket/websocket-vs-rest/src/main/webapp/rest.js +++ b/websocket/websocket-vs-rest/src/main/webapp/rest.js @@ -71,8 +71,9 @@ function restEchoText() { payload += "x"; } restStartTime = new Date().getTime(); - xhr.open("POST", restUri, false); + for (var i = 0; i < times.value; i++) { + xhr.open("POST", restUri, false); xhr.send(payload); restSendBar.value += 100 / times.value; } From 9339e6e0082bd50d90b1ef240c68344bbb88d377 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 15:34:46 +0200 Subject: [PATCH 088/785] Giving a more appropriate name to the module, also cleaning up Servlet try/resources --- .../pom.xml | 3 +- .../container/managed}/MessageReceiver.java | 2 +- .../container/managed}/MessageSender.java | 2 +- .../container/managed}/TestServlet.java | 52 +++++++++---------- .../src/main/webapp/WEB-INF/beans.xml | 0 .../src/main/webapp/index.jsp | 0 6 files changed, 30 insertions(+), 29 deletions(-) rename jms/{jmscontext-cdi => jmscontext-container-managed}/pom.xml (83%) rename jms/{jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi => jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed}/MessageReceiver.java (97%) rename jms/{jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi => jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed}/MessageSender.java (97%) rename jms/{jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi => jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed}/TestServlet.java (80%) rename jms/{jmscontext-cdi => jmscontext-container-managed}/src/main/webapp/WEB-INF/beans.xml (100%) rename jms/{jmscontext-cdi => jmscontext-container-managed}/src/main/webapp/index.jsp (100%) diff --git a/jms/jmscontext-cdi/pom.xml b/jms/jmscontext-container-managed/pom.xml similarity index 83% rename from jms/jmscontext-cdi/pom.xml rename to jms/jmscontext-container-managed/pom.xml index cc9ae493d..3848682b4 100644 --- a/jms/jmscontext-cdi/pom.xml +++ b/jms/jmscontext-container-managed/pom.xml @@ -9,7 +9,8 @@ org.javaee7.jms - jmscontext-cdi + jmscontext-container-managed 1.0-SNAPSHOT war + jmscontext-container-managed diff --git a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageReceiver.java b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageReceiver.java similarity index 97% rename from jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageReceiver.java rename to jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageReceiver.java index 75d91b60f..f4d58811c 100644 --- a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageReceiver.java +++ b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageReceiver.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -package org.javaee7.jms.jmscontext.cdi; +package org.javaee7.jms.jmscontext.container.managed; import javax.annotation.Resource; import javax.ejb.Stateless; diff --git a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageSender.java b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageSender.java similarity index 97% rename from jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageSender.java rename to jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageSender.java index 29b6dcc8a..c5d672ce7 100644 --- a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/MessageSender.java +++ b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/MessageSender.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -package org.javaee7.jms.jmscontext.cdi; +package org.javaee7.jms.jmscontext.container.managed; import javax.annotation.Resource; import javax.ejb.Stateless; diff --git a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/TestServlet.java b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/TestServlet.java similarity index 80% rename from jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/TestServlet.java rename to jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/TestServlet.java index e43cb0dd2..a75f858ea 100644 --- a/jms/jmscontext-cdi/src/main/java/org/javaee7/jms/jmscontext/cdi/TestServlet.java +++ b/jms/jmscontext-container-managed/src/main/java/org/javaee7/jms/jmscontext/container/managed/TestServlet.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -package org.javaee7.jms.jmscontext.cdi; +package org.javaee7.jms.jmscontext.container.managed; import java.io.IOException; import java.io.PrintWriter; @@ -53,15 +53,16 @@ */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { - - @Inject MessageSender sender; - - @Inject MessageReceiver receiver; + + @Inject + MessageSender sender; + + @Inject + MessageReceiver receiver; /** - * Processes requests for both HTTP - * GET and - * POST methods. + * Processes requests for both HTTP GET and POST + * methods. * * @param request servlet request * @param response servlet response @@ -70,27 +71,27 @@ public class TestServlet extends HttpServlet { */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String message = "foobar"; + response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("JMSContext Injection"); - out.println(""); - out.println(""); - out.println("

JMSContext Injection

"); - sender.sendMessage("foobar"); - out.println("Message sent

"); - out.println("Message received: " + receiver.receiveMessage()); - out.println(""); - out.println(""); - } + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + out.println("Container Managed JMSContext"); + out.println(""); + out.println(""); + out.println("

Container Managed JMSContext

"); + sender.sendMessage(message); + out.println("Message sent: " + message + "

"); + out.println("Message received: " + receiver.receiveMessage()); + out.println(""); + out.println(""); } // /** - * Handles the HTTP - * GET method. + * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response @@ -104,8 +105,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } /** - * Handles the HTTP - * POST method. + * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response diff --git a/jms/jmscontext-cdi/src/main/webapp/WEB-INF/beans.xml b/jms/jmscontext-container-managed/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jms/jmscontext-cdi/src/main/webapp/WEB-INF/beans.xml rename to jms/jmscontext-container-managed/src/main/webapp/WEB-INF/beans.xml diff --git a/jms/jmscontext-cdi/src/main/webapp/index.jsp b/jms/jmscontext-container-managed/src/main/webapp/index.jsp similarity index 100% rename from jms/jmscontext-cdi/src/main/webapp/index.jsp rename to jms/jmscontext-container-managed/src/main/webapp/index.jsp From f7a4391e63a1fe5e6a3a9db5e87378cfc83a244b Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 15:37:55 +0200 Subject: [PATCH 089/785] Removing redundant and --- jms/jmscontext-container-managed/pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/jms/jmscontext-container-managed/pom.xml b/jms/jmscontext-container-managed/pom.xml index 3848682b4..f5f405b18 100644 --- a/jms/jmscontext-container-managed/pom.xml +++ b/jms/jmscontext-container-managed/pom.xml @@ -8,9 +8,6 @@ ../pom.xml - org.javaee7.jms jmscontext-container-managed - 1.0-SNAPSHOT war - jmscontext-container-managed From 13640783cebcdb09bcc152deb372d06905095787 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 15:43:56 +0200 Subject: [PATCH 090/785] Fixing titles --- jms/jmscontext-container-managed/src/main/webapp/index.jsp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jms/jmscontext-container-managed/src/main/webapp/index.jsp b/jms/jmscontext-container-managed/src/main/webapp/index.jsp index 81c4fbde4..74a6b81df 100644 --- a/jms/jmscontext-container-managed/src/main/webapp/index.jsp +++ b/jms/jmscontext-container-managed/src/main/webapp/index.jsp @@ -46,10 +46,10 @@ - JMS 2 : JMSContext Injection + Container Managed JMSContext -

JMS 2 : JMSContext Injection

+

Container Managed JMSContext

Send and Receive message. From 00b764566ed7a8fe90c697696911af5ef56786c8 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 15:55:08 +0200 Subject: [PATCH 091/785] Starting a new sample - application-managed JMSContext, still need figure out why injection is failing in GlassFish --- jms/jmscontext-app-managed/pom.xml | 13 +++ .../app/managed/MessageReceiver.java | 26 ++++++ .../jmscontext/app/managed/MessageSender.java | 29 ++++++ .../jmscontext/app/managed/TestServlet.java | 91 +++++++++++++++++++ .../src/main/webapp/WEB-INF/beans.xml | 6 ++ .../src/main/webapp/index.jsp | 14 +++ 6 files changed, 179 insertions(+) create mode 100644 jms/jmscontext-app-managed/pom.xml create mode 100644 jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageReceiver.java create mode 100644 jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageSender.java create mode 100644 jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/TestServlet.java create mode 100644 jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml create mode 100644 jms/jmscontext-app-managed/src/main/webapp/index.jsp diff --git a/jms/jmscontext-app-managed/pom.xml b/jms/jmscontext-app-managed/pom.xml new file mode 100644 index 000000000..4f9bfc4b5 --- /dev/null +++ b/jms/jmscontext-app-managed/pom.xml @@ -0,0 +1,13 @@ + + + 4.0.0 + + org.javaee7.jms + jms-samples + 1.0-SNAPSHOT + ../pom.xml + + + jmscontext-app-managed + war + diff --git a/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageReceiver.java b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageReceiver.java new file mode 100644 index 000000000..6ca7add4f --- /dev/null +++ b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageReceiver.java @@ -0,0 +1,26 @@ +package org.javaee7.jms.jmscontext.app.managed; + +import javax.annotation.Resource; +import javax.ejb.Stateless; +import javax.jms.ConnectionFactory; +import javax.jms.JMSContext; +import javax.jms.Queue; + +/** + * @author Arun Gupta + */ +@Stateless +public class MessageReceiver { + + @Resource + private ConnectionFactory factory; + + @Resource(mappedName="java:global/jms/myQueue") + Queue myQueue; + + public String receiveMessage() { + try (JMSContext context = factory.createContext()) { + return context.createConsumer(myQueue).receiveBody(String.class, 1000); + } + } +} diff --git a/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageSender.java b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageSender.java new file mode 100644 index 000000000..148c3bc42 --- /dev/null +++ b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/MessageSender.java @@ -0,0 +1,29 @@ +package org.javaee7.jms.jmscontext.app.managed; + +import javax.annotation.Resource; +import javax.ejb.Stateless; +import javax.jms.ConnectionFactory; +import javax.jms.JMSContext; +import javax.jms.JMSDestinationDefinition; +import javax.jms.Queue; + +/** + * @author Arun Gupta + */ +@Stateless +@JMSDestinationDefinition(name = "java:global/jms/myQueue", + interfaceName = "javax.jms.Queue") +public class MessageSender { + + @Resource + private ConnectionFactory factory; + + @Resource(mappedName="java:global/jms/myQueue") + Queue myQueue; + + public void sendMessage(String message) { + try (JMSContext context = factory.createContext()) { + context.createProducer().send(myQueue, message); + } + } +} diff --git a/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/TestServlet.java b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/TestServlet.java new file mode 100644 index 000000000..6675fdf09 --- /dev/null +++ b/jms/jmscontext-app-managed/src/main/java/org/javaee7/jms/jmscontext/app/managed/TestServlet.java @@ -0,0 +1,91 @@ +package org.javaee7.jms.jmscontext.app.managed; + +import java.io.IOException; +import java.io.PrintWriter; +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Arun Gupta + */ +@WebServlet(urlPatterns = {"/TestServlet"}) +public class TestServlet extends HttpServlet { + + @Inject + MessageSender sender; + + @Inject + MessageReceiver receiver; + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String message = "foobar"; + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + out.println("Application Managed JMSContext"); + out.println(""); + out.println(""); + out.println("

Application Managed JMSContext

"); + sender.sendMessage(message); + out.println("Message sent: " + message + "

"); + out.println("Message received: " + receiver.receiveMessage()); + out.println(""); + out.println(""); + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// +} diff --git a/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml b/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 000000000..2777559c2 --- /dev/null +++ b/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/jms/jmscontext-app-managed/src/main/webapp/index.jsp b/jms/jmscontext-app-managed/src/main/webapp/index.jsp new file mode 100644 index 000000000..2fa9f924e --- /dev/null +++ b/jms/jmscontext-app-managed/src/main/webapp/index.jsp @@ -0,0 +1,14 @@ +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + + Application Managed JMSContext + + +

Application Managed JMSContext

+ Send and Receive message. + + From 4335eef086b02b52b9fd6f9257392b7293a0e311 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:25:24 +0200 Subject: [PATCH 092/785] Sample works on WildFly beta2 snapshot and GlassFish 4 --- .../src/main/webapp/WEB-INF/beans.xml | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml diff --git a/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml b/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index 2777559c2..000000000 --- a/jms/jmscontext-app-managed/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - From 8d596a9971ae736ea6e9fe793962a635271ff2f8 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:26:01 +0200 Subject: [PATCH 093/785] Adding container-managed and app-managed JMSContext modules --- jms/pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jms/pom.xml b/jms/pom.xml index e7e5ac73f..24f717177 100644 --- a/jms/pom.xml +++ b/jms/pom.xml @@ -18,7 +18,8 @@ send-receive-simple send-receive temp-destination - jmscontext-cdi - + jmscontext-container-managed + jmscontext-app-managed + From efdf84cd073459385d20a429a1d8bd4c358f4db9 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:28:01 +0200 Subject: [PATCH 094/785] Removing try-with-resources to allow any errors to show up on ServletOutputStream --- .../servlet/security/SecureServlet.java | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java b/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java index 0bfdb1ca4..ff7ac4e73 100644 --- a/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java +++ b/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java @@ -54,9 +54,8 @@ public class SecureServlet extends HttpServlet { /** - * Processes requests for both HTTP - * GET and - * POST methods. + * Processes requests for both HTTP GET and POST + * methods. * * @param request servlet request * @param response servlet response @@ -66,24 +65,22 @@ public class SecureServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet SecureServlet"); - out.println(""); - out.println(""); - out.println("

Basic Auth with File-base Realm (" + method + ")

"); - out.println("

Were you prompted for username/password ?

"); - out.println(""); - out.println(""); - } + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet SecureServlet"); + out.println(""); + out.println(""); + out.println("

Basic Auth with File-base Realm (" + method + ")

"); + out.println("

Were you prompted for username/password ?

"); + out.println(""); + out.println(""); } // /** - * Handles the HTTP - * GET method. + * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response @@ -97,8 +94,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } /** - * Handles the HTTP - * POST method. + * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response From 31a482e56bea957c240fac217eb78a9417332927 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:33:02 +0200 Subject: [PATCH 095/785] Fixing the title --- .../main/java/org/javaee7/servlet/security/SecureServlet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java b/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java index ff7ac4e73..a716866c1 100644 --- a/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java +++ b/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java @@ -69,7 +69,7 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re out.println(""); out.println(""); out.println(""); - out.println("Servlet SecureServlet"); + out.println("Servlet Security - Basic Auth with File-base Realm"); out.println(""); out.println(""); out.println("

Basic Auth with File-base Realm (" + method + ")

"); From a3e7b030196f76a9f038460a71ffd844ac690353 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:35:41 +0200 Subject: [PATCH 096/785] Changed the module name to be more intuitive --- servlet/pom.xml | 2 +- servlet/{servlet-security => servlet-basicauth-file}/pom.xml | 3 ++- .../main/java/org/javaee7/servlet/security/SecureServlet.java | 0 .../src/main/webapp/WEB-INF/glassfish-web.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../src/main/webapp/index.jsp | 0 6 files changed, 3 insertions(+), 2 deletions(-) rename servlet/{servlet-security => servlet-basicauth-file}/pom.xml (85%) rename servlet/{servlet-security => servlet-basicauth-file}/src/main/java/org/javaee7/servlet/security/SecureServlet.java (100%) rename servlet/{servlet-security => servlet-basicauth-file}/src/main/webapp/WEB-INF/glassfish-web.xml (100%) rename servlet/{servlet-security => servlet-basicauth-file}/src/main/webapp/WEB-INF/web.xml (100%) rename servlet/{servlet-security => servlet-basicauth-file}/src/main/webapp/index.jsp (100%) diff --git a/servlet/pom.xml b/servlet/pom.xml index 02c01f57f..14eaa2c1d 100644 --- a/servlet/pom.xml +++ b/servlet/pom.xml @@ -27,7 +27,7 @@ nonblocking protocol-handler resource-packaging - servlet-security + servlet-basicauth-file servlet-filters file-upload web-fragment diff --git a/servlet/servlet-security/pom.xml b/servlet/servlet-basicauth-file/pom.xml similarity index 85% rename from servlet/servlet-security/pom.xml rename to servlet/servlet-basicauth-file/pom.xml index 906a5aeb9..cc31476ff 100644 --- a/servlet/servlet-security/pom.xml +++ b/servlet/servlet-basicauth-file/pom.xml @@ -9,7 +9,8 @@ org.javaee7.servlet - servlet-security + servlet-basicauth-file 1.0-SNAPSHOT war + servlet-basicauth-file diff --git a/servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java b/servlet/servlet-basicauth-file/src/main/java/org/javaee7/servlet/security/SecureServlet.java similarity index 100% rename from servlet/servlet-security/src/main/java/org/javaee7/servlet/security/SecureServlet.java rename to servlet/servlet-basicauth-file/src/main/java/org/javaee7/servlet/security/SecureServlet.java diff --git a/servlet/servlet-security/src/main/webapp/WEB-INF/glassfish-web.xml b/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/glassfish-web.xml similarity index 100% rename from servlet/servlet-security/src/main/webapp/WEB-INF/glassfish-web.xml rename to servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/glassfish-web.xml diff --git a/servlet/servlet-security/src/main/webapp/WEB-INF/web.xml b/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from servlet/servlet-security/src/main/webapp/WEB-INF/web.xml rename to servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml diff --git a/servlet/servlet-security/src/main/webapp/index.jsp b/servlet/servlet-basicauth-file/src/main/webapp/index.jsp similarity index 100% rename from servlet/servlet-security/src/main/webapp/index.jsp rename to servlet/servlet-basicauth-file/src/main/webapp/index.jsp From 4e35f53be6edaa4e44557ea807ce13d9da3ebd0d Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 16:36:34 +0200 Subject: [PATCH 097/785] Adding async-ejb module --- ejb/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/ejb/pom.xml b/ejb/pom.xml index ea36b19c5..7e3756d29 100644 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -21,5 +21,6 @@ stateful stateless timer + async-ejb From 151704932dbd596619f179e5578bc41a1b9c6095 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Sun, 10 Nov 2013 17:21:57 +0200 Subject: [PATCH 098/785] Removing deny-uncovered-http-methods --- servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml b/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml index 791c69a6c..801251bb3 100644 --- a/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml +++ b/servlet/servlet-basicauth-file/src/main/webapp/WEB-INF/web.xml @@ -45,7 +45,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> - SecureServlet From defd52a6cbc34c8681d105845cd58a293ace3421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20Gr=C3=A9au?= Date: Sun, 10 Nov 2013 21:20:21 +0100 Subject: [PATCH 099/785] clean for pull request --- websocket/websocket-vs-rest/src/main/webapp/rest.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/websocket/websocket-vs-rest/src/main/webapp/rest.js b/websocket/websocket-vs-rest/src/main/webapp/rest.js index c7c00b4b0..4eb5645ef 100644 --- a/websocket/websocket-vs-rest/src/main/webapp/rest.js +++ b/websocket/websocket-vs-rest/src/main/webapp/rest.js @@ -71,9 +71,8 @@ function restEchoText() { payload += "x"; } restStartTime = new Date().getTime(); - for (var i = 0; i < times.value; i++) { - xhr.open("POST", restUri, false); + xhr.open("POST", restUri, false); xhr.send(payload); restSendBar.value += 100 / times.value; } From 5e7721b82b9e55517c88044502a502df7fe10926 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Mon, 11 Nov 2013 11:05:27 +0100 Subject: [PATCH 100/785] Adding JBoss Nexus repository and Hibernate OGM dependencies, and commenting them for now --- pom.xml | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/pom.xml b/pom.xml index 78688c40a..f9ab5d118 100644 --- a/pom.xml +++ b/pom.xml @@ -308,6 +308,38 @@
wildfly + @@ -332,6 +364,24 @@ + + org.jboss.resteasy resteasy-client From 198804887f04c446074744310c0ebf88383610ae Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Mon, 11 Nov 2013 12:18:42 +0100 Subject: [PATCH 101/785] Fixing https://github.com/arun-gupta/javaee7-samples/pull/32 --- .../batch/chunk/csv/database/Person.java | 20 ++++++++++++++++--- .../src/main/resources/META-INF/create.sql | 2 +- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/batch/chunk-csv-database/src/main/java/org/javaee7/batch/chunk/csv/database/Person.java b/batch/chunk-csv-database/src/main/java/org/javaee7/batch/chunk/csv/database/Person.java index 5aa9e6e1c..6163430f2 100644 --- a/batch/chunk-csv-database/src/main/java/org/javaee7/batch/chunk/csv/database/Person.java +++ b/batch/chunk-csv-database/src/main/java/org/javaee7/batch/chunk/csv/database/Person.java @@ -43,6 +43,8 @@ import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @@ -62,14 +64,18 @@ @NamedQuery(name = "Person.findByName", query = "SELECT c FROM Person c WHERE c.name = :name"), @NamedQuery(name = "Person.findByHiredate", query = "SELECT c FROM Person c WHERE c.hiredate = :hiredate")}) public class Person implements Serializable { - private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + private static final long serialVersionUID = 1L; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "NAME") private String name; - + @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @@ -88,6 +94,14 @@ public Person(String name, String hiredate) { this.hiredate = hiredate; } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { return name; } @@ -128,5 +142,5 @@ public boolean equals(Object object) { public String toString() { return name; } - + } diff --git a/batch/chunk-csv-database/src/main/resources/META-INF/create.sql b/batch/chunk-csv-database/src/main/resources/META-INF/create.sql index 7a4b78d58..a23e4f7ac 100644 --- a/batch/chunk-csv-database/src/main/resources/META-INF/create.sql +++ b/batch/chunk-csv-database/src/main/resources/META-INF/create.sql @@ -1 +1 @@ -CREATE TABLE CHUNK_CSV_DATABASE ("NAME" VARCHAR(50) not null primary key, "HIREDATE" VARCHAR(50) not null) \ No newline at end of file +CREATE TABLE CHUNK_CSV_DATABASE ("ID" INTEGER not null primary key, "NAME" VARCHAR(50) not null primary key, "HIREDATE" VARCHAR(50) not null) \ No newline at end of file From fe38b1a8bd0cc1100787f52878abd65ddf5ec8e1 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 10:07:39 +0100 Subject: [PATCH 102/785] Removed previously commented repositories --- pom.xml | 34 +--------------------------------- 1 file changed, 1 insertion(+), 33 deletions(-) diff --git a/pom.xml b/pom.xml index f9ab5d118..8675205c7 100644 --- a/pom.xml +++ b/pom.xml @@ -308,38 +308,6 @@ wildfly - @@ -359,7 +327,7 @@ org.wildfly.plugins wildfly-maven-plugin - 1.0.0.Beta1-SNAPSHOT + 1.0.0.Beta1 From 4ff23ded28c088cb4804abd0b402a3616d1758c7 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 10:48:47 +0100 Subject: [PATCH 103/785] Add Wildfly Managed/Remote and Glassfish Embedded Arquillian profiles --- .../jaxrs/endpoint/MyResourceTest.java | 27 +- .../src/test/resources/arquillian.xml | 30 +- pom.xml | 280 +++++------------- 3 files changed, 107 insertions(+), 230 deletions(-) diff --git a/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/MyResourceTest.java b/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/MyResourceTest.java index c8528d222..f4e3d5868 100644 --- a/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/MyResourceTest.java +++ b/jaxrs/jaxrs-endpoint/src/test/java/org/javaee7/jaxrs/endpoint/MyResourceTest.java @@ -6,26 +6,31 @@ package org.javaee7.jaxrs.endpoint; +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; + import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.FixMethodOrder; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; /** * @author Arun Gupta */ -//@RunWith(Arquillian.class) +@RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MyResourceTest { @@ -37,8 +42,7 @@ public class MyResourceTest { * * @return a war file */ - @Deployment -// @TargetsContainer("wildfly-arquillian") + @Deployment(testable = false) public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class). addClass(MyApplication.class). @@ -49,10 +53,13 @@ public static WebArchive createDeployment() { return war; } - @BeforeClass - public static void setupClass() { + @ArquillianResource + private URL base; + + @Before + public void setupClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/jaxrs-endpoint/webresources/fruit"); + target = client.target(new URL(base, "webresources/fruit").toExternalForm()); } /** diff --git a/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml b/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml index 7421b0007..04fcc49bc 100644 --- a/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml +++ b/jaxrs/jaxrs-endpoint/src/test/resources/arquillian.xml @@ -1,16 +1,14 @@ - - - - ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1}/standalone/deployments - - - - ${serverRoot:/opt/programs/wildfly-8.0.0.Beta1} - ${serverProfile:standalone-full.xml} - - - \ No newline at end of file + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + diff --git a/pom.xml b/pom.xml index 8675205c7..1877dac5d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ 1.7 - 3.1.0 + 3.0.0 glassfish4x /home/argupta/tools/glassfish-4.0 wildfly8x @@ -20,6 +20,7 @@ /Users/arungup/tools/weblogic/12c/wlserver gfv3ee6 1.1.1.Final + 8.0.0.Beta1 1.3.1 @@ -29,7 +30,7 @@ org.jboss.arquillian arquillian-bom ${org.jboss.arquillian.version} - test + import pom @@ -56,13 +57,11 @@ org.jboss.arquillian.junit arquillian-junit-container - ${org.jboss.arquillian.version} test - org.jboss.arquillian.container - arquillian-container-impl-base - ${org.jboss.arquillian.version} + org.jboss.arquillian.protocol + arquillian-protocol-servlet test @@ -138,35 +137,6 @@ false - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.5 - - - - - org.apache.derby - derby - - - - ${project.build.directory}/derby - - - - - - cargo.datasource.driver=org.apache.derby.jdbc.EmbeddedDriver| - cargo.datasource.url=jdbc:derby:derbyDB;create=true| - cargo.datasource.jndi=jdbc/__default| - cargo.datasource.username=APP| - cargo.datasource.password=APP - - - - - maven-enforcer-plugin @@ -204,87 +174,7 @@ - glassfish - - - maven.java.net - Java.net Repository for Maven - https://maven.java.net/content/groups/promoted/ - - - maven2-repository.dev.java.net - Java.net Repository for Maven - http://download.java.net/maven/glassfish/ - - - - - - org.codehaus.cargo - cargo-maven2-plugin - 1.4.5 - - - ${cargo.container.glassfish.id} - installed - ${cargo.container.glassfish.home} - - - - org.apache.derby - derby - none - - - - - - - org.glassfish.embedded - maven-embedded-glassfish-plugin - 4.0 - - target/${project.artifactId}.war - 8080 - - 8181 - - - - - org.glassfish.main.common - simple-glassfish-api - 4.0 - - - org.glassfish.main.extras - glassfish-embedded-all - 4.0 - - - - - start - integration-test - - start - deploy - - - - stop - post-integration-test - - undeploy - stop - - - - - - + glassfish-embedded-arquillian org.glassfish.tyrus @@ -304,87 +194,40 @@ 2.4 test - - - - wildfly - - - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.wildfly.id} - installed - ${cargo.container.wildfly.home} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - 1.0.0.Beta1 - - - - - - - - org.jboss.resteasy - resteasy-client - 3.0.5.Final - jar - test + org.glassfish.main.extras + glassfish-embedded-all + 4.0 - org.jboss.resteasy - resteasy-jaxb-provider - 3.0.5.Final + org.jboss.arquillian.container + arquillian-glassfish-embedded-3.1 + 1.0.0.CR4 test - wildfly-arquillian + wildfly-managed-arquillian true + chromium-browser standalone-full.xml - /opt/programs/wildfly-8.0.0.Beta1 + ${project.build.directory}/wildfly-${org.wildfly} org.wildfly wildfly-arquillian-container-managed - 8.0.0.Beta1 + ${org.wildfly} test - org.jboss.arquillian.protocol - arquillian-protocol-servlet - ${org.jboss.arquillian.version} + org.jboss.resteasy + resteasy-client + 3.0.4.Final test @@ -395,42 +238,71 @@ true - - - - tomcat - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.tomcat.id} - - http://archive.apache.org/dist/tomcat/tomcat-8/v8.0.0-RC3/bin/apache-tomcat-8.0.0-RC3.zip - - - + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + process-test-classes + + unpack + + + + + org.wildfly + wildfly-dist + ${org.wildfly} + zip + false + ${project.build.directory} + + + + + + + + maven-surefire-plugin + + + ${project.build.directory}/wildfly-${org.wildfly} + + - weblogic + wildfly-remote-arquillian + + standalone-full.xml + /opt/programs/wildfly-8.0.0.Beta1 + + + + org.wildfly + wildfly-arquillian-container-remote + ${org.wildfly} + test + + + org.jboss.resteasy + resteasy-client + 3.0.4.Final + test + + + + + src/test/resources + true + + - - org.codehaus.cargo - cargo-maven2-plugin - - - ${cargo.container.weblogic.id} - installed - ${cargo.container.weblogic.home} - - - @@ -494,4 +366,4 @@ ${maven.min.version} - \ No newline at end of file + From cd75298b896081e34c19d4e49ee2730aac739a58 Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 11:16:27 +0100 Subject: [PATCH 104/785] Added test for send-receive-simple project --- .../send/receive/simple/SendReceiveTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java diff --git a/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java b/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java new file mode 100644 index 000000000..adedc1cf1 --- /dev/null +++ b/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2013 RWE IT Slovakia, s.r.o; RWE IT GmbH + */ + +package org.javaee7.jms.send.receive.simple; + +import org.junit.Test; +import static org.junit.Assert.*; + +import javax.ejb.EJB; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.runner.RunWith; + +/** + * + * @author Patrik Dudits + */ +@RunWith(Arquillian.class) +public class SendReceiveTest { + + @EJB + SimplifiedMessageSender simpleSender; + + @EJB + SimplifiedMessageReceiver simpleReceiver; + + @EJB + ClassicMessageSender classicSender; + + @EJB + ClassicMessageReceiver classicReceiver; + + @Test + public void testSimpleApi() { + String message = "The test message"; + simpleSender.sendMessage(message); + + assertEquals(message, simpleReceiver.receiveMessage()); + } + + @Test + public void testClassicApi() { + String message = "The test message"; + classicSender.sendMessage(message); + + assertEquals(message, classicReceiver.receiveMessage()); + } + + @Deployment + public static WebArchive deploy() { + return ShrinkWrap.create(WebArchive.class) + .addClass(SimplifiedMessageReceiver.class) + .addClass(SimplifiedMessageSender.class) + .addClass(ClassicMessageSender.class) + .addClass(ClassicMessageReceiver.class); + } + +} From 1ef2242367e183b7493bcbae7490fc4ea13ca3c9 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 11:32:17 +0100 Subject: [PATCH 105/785] Add Arquillian section to README * Remove reference to Cargo --- README.md | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3059772e0..e465e8ce8 100644 --- a/README.md +++ b/README.md @@ -36,20 +36,34 @@ I don't plan to write any formal documentation, read the code. The [Java EE 7 Es ### IntelliJ ### -### Cargo ### +### Arquillian ### -Samples can be deployed and run on WildFly and GlassFish 4. +Samples are tested on Wildfly and GlassFish using the Arquillian ecosystem. -Make sure to edit ``glassfish.home`` or ``wildfly.home`` property value in the top-level ``pom.xml`` to point to your local GlassFish or Wildfly directory respectively. This is achieved using Maven profiles. Include ``-P wildfly`` on mvn CLI to run the samples on WildFly and ``-P glassfish`` fo GlassFish. +Only one profile can be active at a given time otherwise there will be dependency conflicts. -Only one profile can be active at a given time otherwise there will be port conflicts. +There are 3 available profiles: -1. In one terminal, ``mvn cargo:run`` at the top-level directory to start container -2. In the sample directory - 1. ``mvn package cargo:deploy`` to deploy for the first time - 2. ``mvn package cargo:redeploy`` to redeploy subsequently - 3. ``mvn cargo:undeploy`` to undeploy -3. Check for application name printed by Cargo output. Access the application at http://localhost:8080/ +* ``wildfly-managed-arquillian`` + The default profile and it will install a Wildfly server and start up the server pr sample. + Useful for CI servers. + +* ``wildfly-remote-arquillian`` + This profile requires you to start up a Wildfly server outside of the build. Each sample will then + reuse this instance to run the tests. + Useful for development to avoid the server start up cost pr sample. + +* ``glassfish-embedded-arquillian`` + This profile uses the GlassFish embedded server and runs in the same JVM as the TestClass. + Useful for development, but has the downside of server startup pr sample. + +To run them in the console do: + +1. In the terminal, ``mvn -Pwildfly-managed-arquillian`` at the top-level directory to start the tests + +When developing and runing them from IDE, remember to activate the profile before running the test. + +To learn more about Arquillian please refer to the [Arquillian Guides](http://arquillian.org/guides/) ### Manual ### From 3f8fd0b6f3e6f7cf87ffdcede55c5e086f2b4acc Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 11:40:21 +0100 Subject: [PATCH 106/785] Added Arquillian test for the el/standalone example. And it's cool !!! --- .../javaee7/el/standalone/ELResolverTest.java | 45 +++++++++++++++++++ .../src/test/resources/arquillian.xml | 14 ++++++ 2 files changed, 59 insertions(+) create mode 100644 el/standalone/src/test/java/org/javaee7/el/standalone/ELResolverTest.java create mode 100644 el/standalone/src/test/resources/arquillian.xml diff --git a/el/standalone/src/test/java/org/javaee7/el/standalone/ELResolverTest.java b/el/standalone/src/test/java/org/javaee7/el/standalone/ELResolverTest.java new file mode 100644 index 000000000..f36e524f7 --- /dev/null +++ b/el/standalone/src/test/java/org/javaee7/el/standalone/ELResolverTest.java @@ -0,0 +1,45 @@ +package org.javaee7.el.standalone; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.el.ELProcessor; + +import static org.junit.Assert.assertEquals; + + +/** + * @author Alexis Hassler + */ +@RunWith(Arquillian.class) +public class ELResolverTest { + + @Deployment + public static Archive deploy() { + return ShrinkWrap.create(JavaArchive.class); + } + private ELProcessor elProcessor; + + @Before + public void setup() { + elProcessor = new ELProcessor(); + } + + @Test + public void should_pick_in_the_array() { + Object result = elProcessor.eval("a = [1, 2, 3]; a[1]"); + assertEquals(2L, result); + } + + @Test + public void should_add() { + Object result = elProcessor.eval("((x,y) -> x+y)(4, 5)"); + assertEquals(9L, result); + } +} diff --git a/el/standalone/src/test/resources/arquillian.xml b/el/standalone/src/test/resources/arquillian.xml new file mode 100644 index 000000000..04fcc49bc --- /dev/null +++ b/el/standalone/src/test/resources/arquillian.xml @@ -0,0 +1,14 @@ + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + From bc5452b8c090246669db01f66669d8ff55c46fdb Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 11:55:28 +0100 Subject: [PATCH 107/785] Commenting the test - need to be fixed --- .../managedexecutor/ExecutorInvokeAllServletTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java b/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java index 8ceacba78..8ecfea58d 100644 --- a/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java +++ b/concurrency/managedexecutor/src/test/java/org/javaee7/concurrency/managedexecutor/ExecutorInvokeAllServletTest.java @@ -58,7 +58,7 @@ public ExecutorInvokeAllServletTest() { /** * Test of invokeAll method. */ - @Test +// @Test public void testProcessRequest() throws Exception { List> results = executor.invokeAll(tasks); int count = 0; From 43117e4ddf6b8cd93f503d1ffb69142213243220 Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 12:40:09 +0100 Subject: [PATCH 108/785] Moved glassfish-embedded dependency up to fix classpath issues --- pom.xml | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 1877dac5d..7ef460a2c 100644 --- a/pom.xml +++ b/pom.xml @@ -176,6 +176,12 @@ glassfish-embedded-arquillian + + org.glassfish.main.extras + glassfish-embedded-all + 4.0 + test + org.glassfish.tyrus tyrus-client @@ -194,11 +200,6 @@ 2.4 test - - org.glassfish.main.extras - glassfish-embedded-all - 4.0 - org.jboss.arquillian.container arquillian-glassfish-embedded-3.1 @@ -366,4 +367,4 @@ ${maven.min.version} - + From 71007a022661cfd2d0dc91af93cd35d0144833ae Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 12:55:01 +0100 Subject: [PATCH 109/785] Dropped servlet and jsp --- .../javaee7/el/standalone/TestServlet.java | 128 ------------------ el/standalone/src/main/webapp/index.jsp | 55 -------- 2 files changed, 183 deletions(-) delete mode 100644 el/standalone/src/main/java/org/javaee7/el/standalone/TestServlet.java delete mode 100644 el/standalone/src/main/webapp/index.jsp diff --git a/el/standalone/src/main/java/org/javaee7/el/standalone/TestServlet.java b/el/standalone/src/main/java/org/javaee7/el/standalone/TestServlet.java deleted file mode 100644 index 4daf31b68..000000000 --- a/el/standalone/src/main/java/org/javaee7/el/standalone/TestServlet.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.el.standalone; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; -import javax.el.ELProcessor; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet TestServlet"); - out.println(""); - out.println(""); - out.println("

ELProcessor

"); - ELProcessor elp = new ELProcessor(); - out.println("Simple array access
"); - out.println((elp.eval("a = [1, 2, 3]; a[1]")) + "
"); - out.println("Lambda expressions
"); - out.println(((elp.eval("((x,y) -> x+y)(4, 5)"))) + "
"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// - -} diff --git a/el/standalone/src/main/webapp/index.jsp b/el/standalone/src/main/webapp/index.jsp deleted file mode 100644 index aa1192b02..000000000 --- a/el/standalone/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - EL standalone processor - - -

EL standalone processor

- Call the processor. - - From 1059dca0ab78e1dee2c2a19c62c863ff932e35f4 Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 13:21:18 +0100 Subject: [PATCH 110/785] Added Arquillian test for the jta/user-transaction example --- .../jta/user/transaction/TestCDIServlet.java | 146 ----------------- .../jta/user/transaction/TestJNDIServlet.java | 150 ------------------ .../src/main/webapp/WEB-INF/beans.xml | 49 ------ .../src/main/webapp/index.jsp | 57 ------- .../org/javaee7/jta/UserTransactionTest.java | 42 +++++ .../src/test/resources/arquillian.xml | 14 ++ 6 files changed, 56 insertions(+), 402 deletions(-) delete mode 100644 jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestCDIServlet.java delete mode 100644 jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestJNDIServlet.java delete mode 100644 jta/user-transaction/src/main/webapp/WEB-INF/beans.xml delete mode 100644 jta/user-transaction/src/main/webapp/index.jsp create mode 100644 jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java create mode 100644 jta/user-transaction/src/test/resources/arquillian.xml diff --git a/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestCDIServlet.java b/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestCDIServlet.java deleted file mode 100644 index 760b5a047..000000000 --- a/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestCDIServlet.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jta.user.transaction; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.inject.Inject; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.UserTransaction; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestCDIServlet"}) -public class TestCDIServlet extends HttpServlet { - - @Inject UserTransaction ut; - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("UserTransaction obtained using @Inject"); - out.println(""); - out.println(""); - out.println("

UserTransaction obtained using @Inject

"); - try { - ut.begin(); - out.println("Something within transaction
"); - ut.commit(); - out.println("Transaction committed
"); - } catch (NotSupportedException - | SystemException - | RollbackException - | HeuristicMixedException - | HeuristicRollbackException - | SecurityException - | IllegalStateException ex) { - ex.printStackTrace(out); - } - out.println("No stack trace, right ?
"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestJNDIServlet.java b/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestJNDIServlet.java deleted file mode 100644 index a8504a4e5..000000000 --- a/jta/user-transaction/src/main/java/org/javaee7/jta/user/transaction/TestJNDIServlet.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jta.user.transaction; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.UserTransaction; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestJNDIServlet"}) -public class TestJNDIServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("UserTransaction obtained using JNDI Lookup"); - out.println(""); - out.println(""); - out.println("

UserTransaction obtained using JNDI Lookup

"); - try { - Context context = new InitialContext(); - UserTransaction ut = (UserTransaction)context.lookup("java:comp/UserTransaction"); - out.println("Obtained UserTransaction using JNDI context
"); - ut.begin(); - out.println("Something within transaction
"); - ut.commit(); - out.println("Transaction committed
"); - } catch (NotSupportedException - | SystemException - | RollbackException - | HeuristicMixedException - | HeuristicRollbackException - | SecurityException - | IllegalStateException - | NamingException ex) { - ex.printStackTrace(out); - } - out.println("No stack trace, right ?
"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jta/user-transaction/src/main/webapp/WEB-INF/beans.xml b/jta/user-transaction/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index aa81c7c3c..000000000 --- a/jta/user-transaction/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - \ No newline at end of file diff --git a/jta/user-transaction/src/main/webapp/index.jsp b/jta/user-transaction/src/main/webapp/index.jsp deleted file mode 100644 index 03c82cbd6..000000000 --- a/jta/user-transaction/src/main/webapp/index.jsp +++ /dev/null @@ -1,57 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - - JTA : UserTransaction - - -

JTA : UserTransaction

- Invoke a Servlet with UserTransaction obtained using @Inject
- Invoke a Servlet with UserTransaction obtained using JNDI
- - \ No newline at end of file diff --git a/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java new file mode 100644 index 000000000..54c399421 --- /dev/null +++ b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java @@ -0,0 +1,42 @@ +package org.javaee7.jta; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.*; + +@RunWith(Arquillian.class) +public class UserTransactionTest { + @Deployment + public static Archive deploy() { + return ShrinkWrap.create(JavaArchive.class) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + // WF 8.0.0.Beta1 needs the beans.xml file. Shouldn't be the case with JavaEE 7 + } + + @Inject UserTransaction ut; + + @Test + public void should_work_with_cdi() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException { + ut.begin(); + ut.commit(); + } + + @Test + public void should_work_with_jndi() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException, NamingException { + Context context = new InitialContext(); + UserTransaction ut = (UserTransaction)context.lookup("java:comp/UserTransaction"); + ut.begin(); + ut.commit(); + } +} diff --git a/jta/user-transaction/src/test/resources/arquillian.xml b/jta/user-transaction/src/test/resources/arquillian.xml new file mode 100644 index 000000000..04fcc49bc --- /dev/null +++ b/jta/user-transaction/src/test/resources/arquillian.xml @@ -0,0 +1,14 @@ + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + From 3941088ea1c13c6a4c9e55d4ad660ea2306c9a14 Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 13:30:25 +0100 Subject: [PATCH 111/785] Arquillian setup for managed WildFly --- .../src/test/resources/arquillian.xml | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 jms/send-receive-simple/src/test/resources/arquillian.xml diff --git a/jms/send-receive-simple/src/test/resources/arquillian.xml b/jms/send-receive-simple/src/test/resources/arquillian.xml new file mode 100644 index 000000000..f45995fda --- /dev/null +++ b/jms/send-receive-simple/src/test/resources/arquillian.xml @@ -0,0 +1,23 @@ + + + + + target + + + + server + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + \ No newline at end of file From 91fc340a4917cb0a5953cccbd6832ed77e88bc5c Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 13:31:05 +0100 Subject: [PATCH 112/785] Removed the test servlet --- .../jms/send/receive/simple/TestServlet.java | 136 ------------------ 1 file changed, 136 deletions(-) delete mode 100644 jms/send-receive-simple/src/main/java/org/javaee7/jms/send/receive/simple/TestServlet.java diff --git a/jms/send-receive-simple/src/main/java/org/javaee7/jms/send/receive/simple/TestServlet.java b/jms/send-receive-simple/src/main/java/org/javaee7/jms/send/receive/simple/TestServlet.java deleted file mode 100644 index 4d228833c..000000000 --- a/jms/send-receive-simple/src/main/java/org/javaee7/jms/send/receive/simple/TestServlet.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jms.send.receive.simple; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.inject.Inject; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - @Inject ClassicMessageSender classicSender; - @Inject ClassicMessageReceiver classicReceiver; - @Inject SimplifiedMessageSender simplifiedSender; - @Inject SimplifiedMessageReceiver simplifiedReceiver; - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet TestServlet"); - out.println(""); - out.println(""); - out.println("

Message sending and receiving using Classic and Simplified API in JMS2

"); - out.println("

Classic API in JMS2

"); - classicSender.sendMessage("Hello from Classic API"); - out.println("Message sent

"); - out.println("Message received: " + classicReceiver.receiveMessage()); - out.println("

Simplified API in JMS2

"); - simplifiedSender.sendMessage("Hello from Simplified API"); - out.println("Message sent

"); - out.println("Message received: " + simplifiedReceiver.receiveMessage()); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} From 62a627c58a55161b0d98ced1a6daadaab08a774a Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 13:56:18 +0100 Subject: [PATCH 113/785] Remove copyright notice --- .../org/javaee7/jms/send/receive/simple/SendReceiveTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java b/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java index adedc1cf1..eafeb9756 100644 --- a/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java +++ b/jms/send-receive-simple/src/test/java/org/javaee7/jms/send/receive/simple/SendReceiveTest.java @@ -1,7 +1,3 @@ -/* - * Copyright (c) 2013 RWE IT Slovakia, s.r.o; RWE IT GmbH - */ - package org.javaee7.jms.send.receive.simple; import org.junit.Test; From 165781f930380e8c724d0c3253d4d7ee020b7907 Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 13:56:40 +0100 Subject: [PATCH 114/785] Remove index.jsp --- .../src/main/webapp/index.jsp | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 jms/send-receive-simple/src/main/webapp/index.jsp diff --git a/jms/send-receive-simple/src/main/webapp/index.jsp b/jms/send-receive-simple/src/main/webapp/index.jsp deleted file mode 100644 index 08fb565d0..000000000 --- a/jms/send-receive-simple/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JMS 2 : Send and Receive Message - - -

JMS 2 : Send and Receive Message

- Send and Receive the message. - - From a3d2e79d02e7b404123058883e03d6680683bbfc Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 14:14:19 +0100 Subject: [PATCH 115/785] Add RestEasy-JAXB-Provider to Wildfly profiles --- pom.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pom.xml b/pom.xml index 1877dac5d..5f9d7dcc9 100644 --- a/pom.xml +++ b/pom.xml @@ -230,6 +230,12 @@ 3.0.4.Final test
+ + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.4.Final + test +
@@ -294,6 +300,12 @@ 3.0.4.Final test
+ + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.4.Final + test + From 3587953936888820f5457db89578001bef7685f8 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 14:37:39 +0100 Subject: [PATCH 116/785] Adding more dependencies for Arquillian --- pom.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pom.xml b/pom.xml index 7ef460a2c..341b55451 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,12 @@ arquillian-protocol-servlet test + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven + test + jar + xmlunit xmlunit @@ -88,6 +94,12 @@ 1.7R1 test + + org.json + json + 20131018 + test + From a842b4b8e44a0030641ba4a2786e5cf6e7d77077 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 14:38:26 +0100 Subject: [PATCH 117/785] Removing redundant and --- json/object-builder/pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/json/object-builder/pom.xml b/json/object-builder/pom.xml index ae94ffd0d..c1764252d 100644 --- a/json/object-builder/pom.xml +++ b/json/object-builder/pom.xml @@ -8,8 +8,6 @@ ../pom.xml - org.javaee.json object-builder - 1.0-SNAPSHOT war From 76d5c5ca6e64b9f0d4d7f516e5dfe5e100b64fd3 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 14:52:14 +0100 Subject: [PATCH 118/785] Converting to unit tests --- .../object/builder/DOMGeneratorServlet.java | 175 ------------------ json/object-builder/src/main/webapp/index.jsp | 57 ------ 2 files changed, 232 deletions(-) delete mode 100644 json/object-builder/src/main/java/org/javaee7/json/object/builder/DOMGeneratorServlet.java delete mode 100644 json/object-builder/src/main/webapp/index.jsp diff --git a/json/object-builder/src/main/java/org/javaee7/json/object/builder/DOMGeneratorServlet.java b/json/object-builder/src/main/java/org/javaee7/json/object/builder/DOMGeneratorServlet.java deleted file mode 100644 index 59d061bf8..000000000 --- a/json/object-builder/src/main/java/org/javaee7/json/object/builder/DOMGeneratorServlet.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.json.object.builder; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.json.Json; -import javax.json.JsonArray; -import javax.json.JsonObject; -import javax.json.JsonWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/DOMGeneratorServlet"}) -public class DOMGeneratorServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println("Using JSON DOMGenerator"); - out.println(""); - out.println(""); - out.println("

Using JSON DOMGenerator

"); - - out.println("Creating an empty object ...
"); - JsonObject jsonObject = Json.createObjectBuilder().build(); - StringWriter w = new StringWriter(); - try (JsonWriter writer = Json.createWriter(w)) { - writer.write(jsonObject); - } - out.println(w); - out.println("
...done
"); - - out.println("
Creating a simple object ...
"); - jsonObject = Json.createObjectBuilder() - .add("apple", "red") - .add("banana", "yellow") - .build(); - w = new StringWriter(); - try (JsonWriter writer = Json.createWriter(w)) { - writer.write(jsonObject); - } - out.println(w); - out.println("
...done
"); - - out.println("
Creating a simple array ...
"); - JsonArray jsonArray = Json.createArrayBuilder() - .add(Json.createObjectBuilder().add("apple","red")) - .add(Json.createObjectBuilder().add("banana","yellow")) - .build(); - w = new StringWriter(); - try (JsonWriter writer = Json.createWriter(w)) { - writer.write(jsonArray); - } - out.println(w); - out.println("
...done
"); - - out.println("
Creating a nested structure ...
"); - jsonObject = Json.createObjectBuilder() - .add("title", "The Matrix") - .add("year", 1999) - .add("cast", Json.createArrayBuilder() - .add("Keanu Reaves") - .add("Laurence Fishburne") - .add("Carrie-Anne Moss")) - .build(); - w = new StringWriter(); - try (JsonWriter writer = Json.createWriter(w)) { - writer.write(jsonObject); - } - out.println(w); - out.println("
...done
"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/json/object-builder/src/main/webapp/index.jsp b/json/object-builder/src/main/webapp/index.jsp deleted file mode 100644 index 2c063a184..000000000 --- a/json/object-builder/src/main/webapp/index.jsp +++ /dev/null @@ -1,57 +0,0 @@ - - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JSON Object Builder: DOM Generator - - -

JSON Object Builder: DOM Generator

- - Generate JSON using DOM generator
- - From 91bf94d641986509296fd6451077b0b34caf66bf Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 14:53:24 +0100 Subject: [PATCH 119/785] Adding unit tests --- .../json/object/builder/DOMGeneratorTest.java | 93 +++++++++++++++++++ .../src/test/resources/arquillian.xml | 14 +++ 2 files changed, 107 insertions(+) create mode 100644 json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java create mode 100644 json/object-builder/src/test/resources/arquillian.xml diff --git a/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java b/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java new file mode 100644 index 000000000..3385876ab --- /dev/null +++ b/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java @@ -0,0 +1,93 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.json.object.builder; + +import java.io.File; +import java.io.StringWriter; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonWriter; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +/** + * @author Arun Gupta + */ +@RunWith(Arquillian.class) +public class DOMGeneratorTest { + + @Deployment + public static Archive deploy() { + File[] requiredLibraries = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("org.json:json", "org.skyscreamer:jsonassert") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(requiredLibraries); + } + + @Test + public void testEmptyObject() throws JSONException { + JsonObject jsonObject = Json.createObjectBuilder().build(); + StringWriter w = new StringWriter(); + try (JsonWriter writer = Json.createWriter(w)) { + writer.write(jsonObject); + } + JSONAssert.assertEquals("{}", w.toString(), JSONCompareMode.STRICT); + } + + @Test + public void testSimpleObject() throws JSONException { + JsonObject jsonObject = Json.createObjectBuilder() + .add("apple", "red") + .add("banana", "yellow") + .build(); + StringWriter w = new StringWriter(); + try (JsonWriter writer = Json.createWriter(w)) { + writer.write(jsonObject); + } + JSONAssert.assertEquals("{\"apple\" : \"red\", \"banana\" : \"yellow\" }", w.toString(), JSONCompareMode.STRICT); + } + + @Test + public void testArray() throws JSONException { + JsonArray jsonArray = Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("apple", "red")) + .add(Json.createObjectBuilder().add("banana", "yellow")) + .build(); + StringWriter w = new StringWriter(); + try (JsonWriter writer = Json.createWriter(w)) { + writer.write(jsonArray); + } + JSONAssert.assertEquals("[{\"apple\":\"red\"},{\"banana\":\"yellow\"}]", w.toString(), JSONCompareMode.STRICT); + } + + public void testNestedStructure() throws JSONException { + JsonObject jsonObject = Json.createObjectBuilder() + .add("title", "The Matrix") + .add("year", 1999) + .add("cast", Json.createArrayBuilder() + .add("Keanu Reaves") + .add("Laurence Fishburne") + .add("Carrie-Anne Moss")) + .build(); + StringWriter w = new StringWriter(); + try (JsonWriter writer = Json.createWriter(w)) { + writer.write(jsonObject); + } + JSONAssert.assertEquals("{\"title\":\"The Matrix\",\"year\":1999,\"cast\":[\"Keanu Reaves\",\"Laurence Fishburne\",\"Carrie-Anne Moss\"]}", w.toString(), JSONCompareMode.STRICT); + } +} diff --git a/json/object-builder/src/test/resources/arquillian.xml b/json/object-builder/src/test/resources/arquillian.xml new file mode 100644 index 000000000..7427c8ea8 --- /dev/null +++ b/json/object-builder/src/test/resources/arquillian.xml @@ -0,0 +1,14 @@ + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + \ No newline at end of file From b9b9149644a7722286c183947b584731ef432567 Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 15:17:02 +0100 Subject: [PATCH 120/785] Added Arquillian test for the jta/tx-exception example --- .../javaee7/jta/tx/exception/TestServlet.java | 154 ------------------ .../jta/tx/exception/EmployeeBeanTest.java | 56 +++++++ .../src/test/resources/arquillian.xml | 14 ++ .../org/javaee7/jta/UserTransactionTest.java | 3 + 4 files changed, 73 insertions(+), 154 deletions(-) delete mode 100644 jta/tx-exception/src/main/java/org/javaee7/jta/tx/exception/TestServlet.java create mode 100644 jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java create mode 100644 jta/tx-exception/src/test/resources/arquillian.xml diff --git a/jta/tx-exception/src/main/java/org/javaee7/jta/tx/exception/TestServlet.java b/jta/tx-exception/src/main/java/org/javaee7/jta/tx/exception/TestServlet.java deleted file mode 100644 index f1979740c..000000000 --- a/jta/tx-exception/src/main/java/org/javaee7/jta/tx/exception/TestServlet.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jta.tx.exception; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.inject.Inject; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - @Inject EmployeeBean bean; - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Checked and Runtime Exception in JTA Transactions"); - out.println(""); - out.println(""); - out.println("

Checked and Runtime Exception in JTA Transactions

"); - out.println("

List employees (before checked exception)

"); - out.println("
    "); - for (Employee e : bean.getEmployees()) { - out.println("
  1. " + e); - } - out.println("
"); - out.println("Number of employees is 7 ?"); - - try { - bean.addAndThrowChecked(); - } catch (Exception ex) { } - - out.println("

List employees (after checked and before runtime exception)

"); - out.println("
    "); - for (Employee e : bean.getEmployees()) { - out.println("
  1. " + e); - } - out.println("
"); - out.println("Number of employees is 8 (new employee is Priya) ?"); - - out.println("

List employees (after runtime exception)

"); - out.println("
    "); - for (Employee e : bean.getEmployees()) { - out.println("
  1. " + e); - } - out.println("
"); - out.println("Number of employees is 8 (no new employee is added because of runtime exception) ?"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java new file mode 100644 index 000000000..c039edc52 --- /dev/null +++ b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java @@ -0,0 +1,56 @@ +package org.javaee7.jta.tx.exception; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; + +import static org.junit.Assert.assertEquals; + +/** + * This test is RED with WildFly 8.0.0.Beta1 because it does not have a standard default DataSource. + * + * @author Alexis Hassler + */ +@RunWith(Arquillian.class) +public class EmployeeBeanTest { + @Deployment + public static Archive deploy() { + return ShrinkWrap.create(JavaArchive.class) + .addClasses(EmployeeBean.class, Employee.class) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") + .addAsResource("META-INF/create.sql", "META-INF/create.sql") + .addAsResource("META-INF/load.sql", "META-INF/load.sql") + .addAsResource("META-INF/drop.sql", "META-INF/drop.sql"); + } + @Inject EmployeeBean bean; + + @Test + public void should_have_7_employees() { + assertEquals(7, bean.getEmployees().size()); + } + + @Test + public void should_have_1_more_employee_after_checked_exception() { + try { + bean.addAndThrowChecked(); + } catch (Exception ex) { } + assertEquals(8, bean.getEmployees().size()); + } + + @Test + public void should_not_have_1_more_employee_after_runtime_exception() { + try { + bean.addAndThrowRuntime(); + } catch (Exception ex) { } + assertEquals(7, bean.getEmployees().size()); + } + +} diff --git a/jta/tx-exception/src/test/resources/arquillian.xml b/jta/tx-exception/src/test/resources/arquillian.xml new file mode 100644 index 000000000..04fcc49bc --- /dev/null +++ b/jta/tx-exception/src/test/resources/arquillian.xml @@ -0,0 +1,14 @@ + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + diff --git a/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java index 54c399421..41fb57e50 100644 --- a/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java +++ b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java @@ -15,6 +15,9 @@ import javax.naming.NamingException; import javax.transaction.*; +/** + * @author Alexis Hassler + */ @RunWith(Arquillian.class) public class UserTransactionTest { @Deployment From 90369ceb3e091d516aa2957e6276dbd2da1eb483 Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 15:35:23 +0100 Subject: [PATCH 121/785] Delete webapp/* files --- .../src/main/webapp/WEB-INF/beans.xml | 49 ---------------- jta/tx-exception/src/main/webapp/index.jsp | 56 ------------------- .../jta/tx/exception/EmployeeBeanTest.java | 8 +-- 3 files changed, 4 insertions(+), 109 deletions(-) delete mode 100644 jta/tx-exception/src/main/webapp/WEB-INF/beans.xml delete mode 100644 jta/tx-exception/src/main/webapp/index.jsp diff --git a/jta/tx-exception/src/main/webapp/WEB-INF/beans.xml b/jta/tx-exception/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index aa81c7c3c..000000000 --- a/jta/tx-exception/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - \ No newline at end of file diff --git a/jta/tx-exception/src/main/webapp/index.jsp b/jta/tx-exception/src/main/webapp/index.jsp deleted file mode 100644 index 178d3a3e9..000000000 --- a/jta/tx-exception/src/main/webapp/index.jsp +++ /dev/null @@ -1,56 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - - JTA : Checked and Runtime Exceptions - - -

JTA : Checked and Runtime Exceptions

- Call bean that throws exceptions
- - \ No newline at end of file diff --git a/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java index c039edc52..6d3842940 100644 --- a/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java +++ b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java @@ -25,10 +25,10 @@ public static Archive deploy() { return ShrinkWrap.create(JavaArchive.class) .addClasses(EmployeeBean.class, Employee.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") - .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") - .addAsResource("META-INF/create.sql", "META-INF/create.sql") - .addAsResource("META-INF/load.sql", "META-INF/load.sql") - .addAsResource("META-INF/drop.sql", "META-INF/drop.sql"); + .addAsResource("META-INF/persistence.xml") + .addAsResource("META-INF/create.sql") + .addAsResource("META-INF/load.sql") + .addAsResource("META-INF/drop.sql"); } @Inject EmployeeBean bean; From 47b5be51dd5d0c238cb7c6f168c30c5048af75c2 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 15:52:02 +0100 Subject: [PATCH 122/785] Removing redundant properties --- pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pom.xml b/pom.xml index 636bc5a88..4a5c89fba 100644 --- a/pom.xml +++ b/pom.xml @@ -296,10 +296,6 @@
wildfly-remote-arquillian - - standalone-full.xml - /opt/programs/wildfly-8.0.0.Beta1 - org.wildfly From 2477b255ffe38f6ad5eb2bc1fa94f8db66c0fbc3 Mon Sep 17 00:00:00 2001 From: Alexis Hassler Date: Tue, 12 Nov 2013 16:08:24 +0100 Subject: [PATCH 123/785] Fix beans.xml issue --- .../org/javaee7/jta/tx/exception/EmployeeBeanTest.java | 2 +- jta/tx-exception/src/test/resources/beans.xml | 7 +++++++ .../src/test/java/org/javaee7/jta/UserTransactionTest.java | 3 +-- jta/user-transaction/src/test/resources/beans.xml | 7 +++++++ 4 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 jta/tx-exception/src/test/resources/beans.xml create mode 100644 jta/user-transaction/src/test/resources/beans.xml diff --git a/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java index 6d3842940..ca1757ea1 100644 --- a/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java +++ b/jta/tx-exception/src/test/java/org/javaee7/jta/tx/exception/EmployeeBeanTest.java @@ -24,7 +24,7 @@ public class EmployeeBeanTest { public static Archive deploy() { return ShrinkWrap.create(JavaArchive.class) .addClasses(EmployeeBean.class, Employee.class) - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsManifestResource("beans.xml") .addAsResource("META-INF/persistence.xml") .addAsResource("META-INF/create.sql") .addAsResource("META-INF/load.sql") diff --git a/jta/tx-exception/src/test/resources/beans.xml b/jta/tx-exception/src/test/resources/beans.xml new file mode 100644 index 000000000..4054ce4a2 --- /dev/null +++ b/jta/tx-exception/src/test/resources/beans.xml @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java index 41fb57e50..a0cf1b2e7 100644 --- a/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java +++ b/jta/user-transaction/src/test/java/org/javaee7/jta/UserTransactionTest.java @@ -23,8 +23,7 @@ public class UserTransactionTest { @Deployment public static Archive deploy() { return ShrinkWrap.create(JavaArchive.class) - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); - // WF 8.0.0.Beta1 needs the beans.xml file. Shouldn't be the case with JavaEE 7 + .addAsManifestResource("beans.xml"); } @Inject UserTransaction ut; diff --git a/jta/user-transaction/src/test/resources/beans.xml b/jta/user-transaction/src/test/resources/beans.xml new file mode 100644 index 000000000..4054ce4a2 --- /dev/null +++ b/jta/user-transaction/src/test/resources/beans.xml @@ -0,0 +1,7 @@ + + + \ No newline at end of file From 1d9fdadbfa0a2d5f42ab74a4f56149054e877fa5 Mon Sep 17 00:00:00 2001 From: Patrik Dudits Date: Tue, 12 Nov 2013 16:10:54 +0100 Subject: [PATCH 124/785] Added support for Remote Glassfish as ARQ Container --- pom.xml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/pom.xml b/pom.xml index 7ef460a2c..cc730f900 100644 --- a/pom.xml +++ b/pom.xml @@ -208,6 +208,17 @@ + + glassfish-remote-arquillian + + + org.jboss.arquillian.container + arquillian-glassfish-remote-3.1 + 1.0.0.CR4 + test + + + wildfly-managed-arquillian From ac4ac475302e6f4656631833aae83efc9af36dbb Mon Sep 17 00:00:00 2001 From: Roberto Cortez Date: Tue, 12 Nov 2013 15:18:33 +0000 Subject: [PATCH 125/785] Added test for batchlet-simple project. Only working for Wildfly for now. --- .../batch/batchlet/simple/MyBatchletTest.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 batch/batchlet-simple/src/test/java/org/javaee7/batch/batchlet/simple/MyBatchletTest.java diff --git a/batch/batchlet-simple/src/test/java/org/javaee7/batch/batchlet/simple/MyBatchletTest.java b/batch/batchlet-simple/src/test/java/org/javaee7/batch/batchlet/simple/MyBatchletTest.java new file mode 100644 index 000000000..58f927f7d --- /dev/null +++ b/batch/batchlet-simple/src/test/java/org/javaee7/batch/batchlet/simple/MyBatchletTest.java @@ -0,0 +1,64 @@ +package org.javaee7.batch.batchlet.simple; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ArchivePaths; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.batch.operations.JobOperator; +import javax.batch.runtime.BatchRuntime; +import javax.batch.runtime.BatchStatus; +import javax.batch.runtime.JobExecution; +import java.util.Properties; + +/** + * @author Roberto Cortez + */ +@RunWith(Arquillian.class) +public class MyBatchletTest { + + @Deployment + public static WebArchive createDeployment() { + WebArchive war = ShrinkWrap.create(WebArchive.class). + addClass(MyBatchlet.class). + addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")). + addAsManifestResource("META-INF/batch-jobs/myJob.xml", "batch-jobs/myJob.xml"); + System.out.println(war.toString(true)); + return war; + } + + @Test + public void testBatchletProcess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("myJob", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + + keepTestAlive(jobExecution); + + Assert.assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + /** + * We need to keep the test running because JobOperator runs the batch job in an asynchronous way, so the + * JobExecution can be properly updated with the running job status. + * + * @param jobExecution the JobExecution of the job that is being runned on JobOperator + * @throws InterruptedException + */ + private void keepTestAlive(JobExecution jobExecution) throws InterruptedException { + int maxTries = 0; + while (!jobExecution.getBatchStatus().equals(BatchStatus.COMPLETED)) { + if (maxTries < 10) { + maxTries++; + Thread.sleep(100); + } else { + break; + } + } + } +} From 5f86c5d1cafc30b0fa41f2da0823638c8ac2aa27 Mon Sep 17 00:00:00 2001 From: Guillaume Scheibel Date: Tue, 12 Nov 2013 16:18:34 +0100 Subject: [PATCH 126/785] #42 Integrate Hibernate OGM - Ehcache Sample --- extra/nosql/hibernate-ogm/pom.xml | 14 ++++ .../extra/nosql/hibernateogm/EhcacheTest.java | 19 +++++ .../hibernateogm/commons/AbstractOgmTest.java | 60 +++++++++++++++ .../nosql/hibernateogm/commons/Person.java | 75 +++++++++++++++++++ .../src/test/resources/arquillian.xml | 14 ++++ .../test/resources/ehcache-persistence.xml | 15 ++++ extra/nosql/pom.xml | 1 + 7 files changed, 198 insertions(+) create mode 100644 extra/nosql/hibernate-ogm/pom.xml create mode 100644 extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/EhcacheTest.java create mode 100644 extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/AbstractOgmTest.java create mode 100644 extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/Person.java create mode 100644 extra/nosql/hibernate-ogm/src/test/resources/arquillian.xml create mode 100644 extra/nosql/hibernate-ogm/src/test/resources/ehcache-persistence.xml diff --git a/extra/nosql/hibernate-ogm/pom.xml b/extra/nosql/hibernate-ogm/pom.xml new file mode 100644 index 000000000..1b7613090 --- /dev/null +++ b/extra/nosql/hibernate-ogm/pom.xml @@ -0,0 +1,14 @@ + + + + extra-nosql-samples + org.javaee7.extra.nosql + 1.0-SNAPSHOT + + 4.0.0 + + hibernate-ogm + + \ No newline at end of file diff --git a/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/EhcacheTest.java b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/EhcacheTest.java new file mode 100644 index 000000000..638ec2e21 --- /dev/null +++ b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/EhcacheTest.java @@ -0,0 +1,19 @@ +package org.javaee7.extra.nosql.hibernateogm; + +import org.javaee7.extra.nosql.hibernateogm.commons.AbstractOgmTest; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.runner.RunWith; + +/** + * @author Guillaume Scheibel + */ +@RunWith(Arquillian.class) +public class EhcacheTest extends AbstractOgmTest { + + @Deployment + public static WebArchive createDeployment() { + return AbstractOgmTest.createDeployment( "ehcache" ); + } +} diff --git a/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/AbstractOgmTest.java b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/AbstractOgmTest.java new file mode 100644 index 000000000..3997cb928 --- /dev/null +++ b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/AbstractOgmTest.java @@ -0,0 +1,60 @@ +package org.javaee7.extra.nosql.hibernateogm.commons; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.UserTransaction; + +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.jboss.shrinkwrap.resolver.api.maven.Maven.resolver; +import static org.junit.Assert.assertThat; + +/** + * @author Guillaume Scheibel + */ +public abstract class AbstractOgmTest { + final static String OGM_VERSION = "4.0.0-SNAPSHOT"; + @PersistenceContext + EntityManager entityManager; + @Inject + UserTransaction ut; + + public static WebArchive createDeployment(String ogmModuleName) { + WebArchive webArchive = ShrinkWrap.create( WebArchive.class ) + .addClass( Person.class ) + .addClass( AbstractOgmTest.class ) + .addAsResource( ogmModuleName + "-persistence.xml", "META-INF/persistence.xml" ) + .addAsWebInfResource( EmptyAsset.INSTANCE, "beans.xml" ) + .addAsLibraries( + resolver().resolve( + "org.hibernate.ogm:hibernate-ogm-core:" + OGM_VERSION, + "org.hibernate.ogm:hibernate-ogm-" + ogmModuleName + ":" + OGM_VERSION + ) + .withTransitivity() + .asFile() + ); + return webArchive; + } + + @Test + public void insertEntityTest() throws Exception { + final String name = "Guillaume"; + final Long id = 1L; + ut.begin(); + Person guillaume = new Person( id, name ); + entityManager.persist( guillaume ); + ut.commit(); + + Person person = entityManager.find( Person.class, id ); + assertThat( person, is( notNullValue() ) ); + assertThat( person.getId(), is( id ) ); + assertThat( person.getName(), is( equalTo( name ) ) ); + } +} diff --git a/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/Person.java b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/Person.java new file mode 100644 index 000000000..f3ee3d9a6 --- /dev/null +++ b/extra/nosql/hibernate-ogm/src/test/java/org/javaee7/extra/nosql/hibernateogm/commons/Person.java @@ -0,0 +1,75 @@ +package org.javaee7.extra.nosql.hibernateogm.commons; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.validation.constraints.NotNull; + +@Entity +public class Person { + + @Id + private Long id = null; + @NotNull + private String name; + + public Person() { + super(); + } + + public Person(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Person{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + + Person person = (Person) o; + + if ( id != null ? !id.equals( person.id ) : person.id != null ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + ( name != null ? name.hashCode() : 0 ); + return result; + } +} diff --git a/extra/nosql/hibernate-ogm/src/test/resources/arquillian.xml b/extra/nosql/hibernate-ogm/src/test/resources/arquillian.xml new file mode 100644 index 000000000..7427c8ea8 --- /dev/null +++ b/extra/nosql/hibernate-ogm/src/test/resources/arquillian.xml @@ -0,0 +1,14 @@ + + + + + + + + ${serverRoot:target/wildfly-8.0.0.Beta1} + ${serverProfile:standalone-full.xml} + + + + \ No newline at end of file diff --git a/extra/nosql/hibernate-ogm/src/test/resources/ehcache-persistence.xml b/extra/nosql/hibernate-ogm/src/test/resources/ehcache-persistence.xml new file mode 100644 index 000000000..d92d6d2ed --- /dev/null +++ b/extra/nosql/hibernate-ogm/src/test/resources/ehcache-persistence.xml @@ -0,0 +1,15 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + org.javaee7.extra.nosql.hibernateogm.commons.Person + + + + + \ No newline at end of file diff --git a/extra/nosql/pom.xml b/extra/nosql/pom.xml index 7aab4e3b3..59dadab39 100644 --- a/extra/nosql/pom.xml +++ b/extra/nosql/pom.xml @@ -23,6 +23,7 @@ hbase voldemort riak + hibernate-ogm From d00f3c46ef5998ef8309b3d1ffc04da8ee165246 Mon Sep 17 00:00:00 2001 From: Roberto Cortez Date: Tue, 12 Nov 2013 15:32:08 +0000 Subject: [PATCH 127/785] Added skip to maven dependency plugin --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index 636bc5a88..36f682e82 100644 --- a/pom.xml +++ b/pom.xml @@ -23,6 +23,7 @@ 8.0.0.Beta1 1.3.1 + false @@ -261,6 +262,9 @@ org.apache.maven.plugins maven-dependency-plugin + + ${maven.test.skip} + unpack From b493c3ac37b6989254f7770af3f09630483f55bc Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 14:16:26 +0100 Subject: [PATCH 128/785] Convert JAX-RS samples to Arquillian: JAX-RS Client Issue: #78 --- .../org/javaee7/jaxrs/client/MyResource.java | 3 +- .../jaxrs/client/TestJAXRS2Client.java | 172 ---------------- .../jaxrs/client/TestURLConnectionClient.java | 187 ------------------ jaxrs/jaxrs-client/src/main/webapp/index.jsp | 56 ------ .../javaee7/jaxrs/client/MyResourceTest.java | 31 ++- 5 files changed, 28 insertions(+), 421 deletions(-) delete mode 100644 jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java delete mode 100644 jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java delete mode 100644 jaxrs/jaxrs-client/src/main/webapp/index.jsp diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/MyResource.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/MyResource.java index eb1d3da6f..4c30da186 100644 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/MyResource.java +++ b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/MyResource.java @@ -40,6 +40,7 @@ package org.javaee7.jaxrs.client; import javax.ejb.EJB; +import javax.enterprise.context.RequestScoped; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; @@ -54,7 +55,7 @@ /** * @author Arun Gupta */ -@Path("persons") +@Path("persons") @RequestScoped public class MyResource { // Ideally this state should be stored in a database @EJB PersonSessionBean bean; diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java deleted file mode 100644 index 6942fc56a..000000000 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestJAXRS2Client.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.client; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestJAXRS2Client"}) -public class TestJAXRS2Client extends HttpServlet { - - - private static final long serialVersionUID = 1975269372645791816L; - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("JAX-RS 2 Client API"); - out.println(""); - out.println(""); - out.println("

JAX-RS 2 Client API

"); - out.println("Initializing client...
"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/persons"); - - out.print("
POSTing...
"); - // POST - MultivaluedHashMap map = new MultivaluedHashMap<>(); - map.add("name", "Name"); - map.add("age", "17"); - target.request().post(Entity.form(map)); - out.print("POSTed a new item ...
"); - - // GET - out.print("
GETTing...
"); - Person[] list = target.request().get(Person[].class); - out.format("GOT %1$s items
", list.length); - for (Person p : list) { - out.print(p + "
"); - } - out.println("... done.
"); - - // GET with path param - out.print("
GETTing with parameter...
"); - Person person = target - .path("{id}") - .resolveTemplate("id", "1") - .request(MediaType.APPLICATION_XML) - .get(Person.class); - out.print("GOT person: " + person + "
"); - out.println("... done.
"); - - // Client-driven content negotiation - out.print("
Client-side content negotiation...
"); - String json = target.request().accept(MediaType.APPLICATION_JSON).get(String.class); - out.print("GOT JSON: " + json + "
"); - out.println("... done."); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java b/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java deleted file mode 100644 index cd158069d..000000000 --- a/jaxrs/jaxrs-client/src/main/java/org/javaee7/jaxrs/client/TestURLConnectionClient.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestURLConnectionClient"}) -public class TestURLConnectionClient extends HttpServlet { - - private static final long serialVersionUID = 4961659627909544506L; - - private static final String CHARSET = "UTF-8"; - - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println("REST Endpoint using HttpURLConnection"); - out.println(""); - out.println(""); - out.println("

REST Endpoint using HttpURLConnection

"); - URL url = new URL("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/persons"); - - out.print("
POSTing...
"); - // POST - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setDoInput(true); - connection.setDoOutput(true); // required to be able to POST - connection.setRequestProperty("Accept-Charset", CHARSET); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHARSET); - String postRequest = String.format("name=%s&age=%s", - URLEncoder.encode("Name", CHARSET), - URLEncoder.encode("17", CHARSET)); - try (OutputStream os = connection.getOutputStream()) { - os.write(postRequest.getBytes(CHARSET)); - } - try (InputStream is = connection.getInputStream()) { - byte[] bytes = new byte[1024]; - is.read(bytes); - out.println(new String(bytes)); - } - connection.disconnect(); - out.print("POSTed a new item ...
"); - - // GET - out.print("
GETTing...
"); - connection = (HttpURLConnection) url.openConnection(); - connection.setDoOutput(false); - connection.setRequestMethod("GET"); -// try (InputStream is = connection.getInputStream()) { -// byte[] bytes = new byte[1024]; -// is.read(bytes); -// out.println(new String(bytes)); -// } - - try { - JAXBContext jc = JAXBContext.newInstance(Person.class, People.class); - Unmarshaller um = jc.createUnmarshaller(); - People people = (People) um.unmarshal(connection.getInputStream()); - out.format("GOT %1$s items
", people.getPerson().length); - for (Person p : people.getPerson()) { - out.print(p + "
"); - } - } catch (JAXBException ex) { - Logger.getLogger(TestURLConnectionClient.class.getName()).log(Level.SEVERE, null, ex); - } - out.println("... done.
"); - - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// - -} diff --git a/jaxrs/jaxrs-client/src/main/webapp/index.jsp b/jaxrs/jaxrs-client/src/main/webapp/index.jsp deleted file mode 100644 index 60d5a41d0..000000000 --- a/jaxrs/jaxrs-client/src/main/webapp/index.jsp +++ /dev/null @@ -1,56 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JAX-RS 2 Client API - - -

JAX-RS 2 Client API

- Invoke using JAX-RS 2 Client API.

- Invoke using HttpUrlConnection. - - diff --git a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java index d5988e153..2e71e7545 100644 --- a/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java +++ b/jaxrs/jaxrs-client/src/test/java/org/javaee7/jaxrs/client/MyResourceTest.java @@ -5,7 +5,10 @@ */ package org.javaee7.jaxrs.client; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -14,24 +17,42 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MyResourceTest { private WebTarget target; - private Client client; + + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses( + MyApplication.class, MyResource.class, People.class, + Person.class, PersonSessionBean.class); + } + + @ArquillianResource + private URL base; @Before - public void setUp() { - client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/jaxrs-client/webresources/persons"); + public void setUp() throws MalformedURLException { + Client client = ClientBuilder.newClient(); + target = client.target(new URL(base, "webresources/persons").toExternalForm()); + target.register(Person.class); } /** From cc180fdafbadd592658d342ce9af52a5b599035a Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 14:20:26 +0100 Subject: [PATCH 129/785] Convert JAX-RS samples to Arquillian: Async Client Issue: #78 --- .../jaxrs/asyncclient/TestServlet.java | 172 ------------------ jaxrs/async-client/src/main/webapp/index.jsp | 55 ------ .../jaxrs/asyncclient/MyResourceTest.java | 29 ++- 3 files changed, 23 insertions(+), 233 deletions(-) delete mode 100644 jaxrs/async-client/src/main/java/org/javaee7/jaxrs/asyncclient/TestServlet.java delete mode 100644 jaxrs/async-client/src/main/webapp/index.jsp diff --git a/jaxrs/async-client/src/main/java/org/javaee7/jaxrs/asyncclient/TestServlet.java b/jaxrs/async-client/src/main/java/org/javaee7/jaxrs/asyncclient/TestServlet.java deleted file mode 100644 index c7f91b82a..000000000 --- a/jaxrs/async-client/src/main/java/org/javaee7/jaxrs/asyncclient/TestServlet.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.asyncclient; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.InvocationCallback; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - final PrintWriter out = response.getWriter(); - response.setContentType("text/html;charset=UTF-8"); - out.println(""); - out.println(""); - out.println("Servlet TestServlet"); - out.println(""); - out.println(""); - out.println("

JAX-RS 2 Async Client

"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/fruits"); - - // Polling (Response) - out.println("Invoking Future<Response>..."); - Future r1 = target.request().async().get(); - out.println("
Received response (Future<Response>): " + r1.get().readEntity(String.class)); - - // Polling (String) - out.println("
Invoking Future<String>..."); - Future r2 = target.request().async().get(String.class); - out.println("
Received response (Future<String>): " + r2.get()); - - // Polling (String) - out.println("
Invoking Future<String>..."); - Future r3 = target.request().async().get(String.class); - out.println("
Received response (Future<String>): " + r3.get()); - - // Callback - out.println("
Invoking InvocationCallback<String>..."); - target.request().async().get(new InvocationCallback() { - - @Override - public void completed(String r) { - System.out.println("Received response (InovcationCallback): " + r); - } - - @Override - public void failed(Throwable t) { - t.printStackTrace(out); - } - - }); - out.print("
Check server.log for InvocationCallback<String> results."); - out.println(""); - out.println(""); - } catch (InterruptedException | ExecutionException ex) { - Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/async-client/src/main/webapp/index.jsp b/jaxrs/async-client/src/main/webapp/index.jsp deleted file mode 100644 index 704b1531e..000000000 --- a/jaxrs/async-client/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - - JAX-RS 2 Async Client - - -

JAX-RS 2 Async Client

- Invoke the Client. - - diff --git a/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java b/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java index 5345a0515..34a5563a7 100644 --- a/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java +++ b/jaxrs/async-client/src/test/java/org/javaee7/jaxrs/asyncclient/MyResourceTest.java @@ -5,33 +5,50 @@ */ package org.javaee7.jaxrs.asyncclient; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.InvocationCallback; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { -// @ArquillianResource URL baseURL; + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class); + } + + @ArquillianResource + private URL base; private static WebTarget target; @Before - public void setUpClass() { + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/async-client/webresources/fruits"); + target = client.target(new URL(base, "webresources/fruits").toExternalForm()); } /** From d5a9aef4a6ea00ce4c34098f4d7a80d8f7641b77 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 14:52:33 +0100 Subject: [PATCH 130/785] Convert JAX-RS samples to Arquillian: Async Server Issue: #78 --- .../javaee7/jaxrs/asyncserver/MyResource.java | 2 +- .../jaxrs/asyncserver/TestServlet.java | 133 ------------------ jaxrs/async-server/src/main/webapp/index.jsp | 14 -- .../jaxrs/asyncserver/MyResourceTest.java | 34 ++++- 4 files changed, 29 insertions(+), 154 deletions(-) delete mode 100644 jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java delete mode 100644 jaxrs/async-server/src/main/webapp/index.jsp diff --git a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/MyResource.java b/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/MyResource.java index 3f1e4e20e..b046baeb4 100644 --- a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/MyResource.java +++ b/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/MyResource.java @@ -41,7 +41,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import javax.annotation.Resource; + import javax.enterprise.concurrent.ManagedThreadFactory; import javax.naming.InitialContext; import javax.naming.NamingException; diff --git a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java b/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java deleted file mode 100644 index 2b0c1a44e..000000000 --- a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.asyncserver; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("JAX-RS Async Server"); - out.println(""); - out.println(""); - out.println("

JAX-RS Async Server

"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/fruits"); - String result = target.request().get(String.class); - out.println("Waited for 3 seconds ...
"); - out.println("Received response: " + result); - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/async-server/src/main/webapp/index.jsp b/jaxrs/async-server/src/main/webapp/index.jsp deleted file mode 100644 index 93ea61077..000000000 --- a/jaxrs/async-server/src/main/webapp/index.jsp +++ /dev/null @@ -1,14 +0,0 @@ -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JSP Page - - -

JAX-RS 2 Async Server

- Invoke the Client. - - diff --git a/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java b/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java index 2d50f1814..76abfadbe 100644 --- a/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java +++ b/jaxrs/async-server/src/test/java/org/javaee7/jaxrs/asyncserver/MyResourceTest.java @@ -6,23 +6,45 @@ package org.javaee7.jaxrs.asyncserver; +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; -import org.junit.BeforeClass; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - private static WebTarget target; - @BeforeClass - public static void setUpClass() { + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class); + } + + private WebTarget target; + + @ArquillianResource + private URL base; + + @Before + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/async-server/webresources/fruits"); + target = client.target(new URL(base, "webresources/fruits").toExternalForm()); } /** From 218a41e90b869a12fdab7e21a422415dea4ab86a Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 15:00:16 +0100 Subject: [PATCH 131/785] Convert JAX-RS samples to Arquillian: JAX-RS Endpoint Issue: #78 --- .../javaee7/jaxrs/endpoint/TestServlet.java | 160 ------------------ .../jaxrs-endpoint/src/main/webapp/index.jsp | 55 ------ 2 files changed, 215 deletions(-) delete mode 100644 jaxrs/jaxrs-endpoint/src/main/java/org/javaee7/jaxrs/endpoint/TestServlet.java delete mode 100644 jaxrs/jaxrs-endpoint/src/main/webapp/index.jsp diff --git a/jaxrs/jaxrs-endpoint/src/main/java/org/javaee7/jaxrs/endpoint/TestServlet.java b/jaxrs/jaxrs-endpoint/src/main/java/org/javaee7/jaxrs/endpoint/TestServlet.java deleted file mode 100644 index e7ebbad97..000000000 --- a/jaxrs/jaxrs-endpoint/src/main/java/org/javaee7/jaxrs/endpoint/TestServlet.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.endpoint; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("JAX-RS Endpoint"); - out.println(""); - out.println(""); - out.println("

JAX-RS Endpoint

"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/fruit"); - out.print("Got a target

"); - - // POST - out.print("POSTing...
"); - target.request().post(Entity.text("apple")); - out.format("POSTed %1$s ...
", "apple"); - - // PUT - out.print("
PUTing...
"); - target.request().put(Entity.text("banana")); - out.format("PUTed %1$s ...
", "banana"); - - // GET (all) - out.print("
GETing...
"); - String r = target.request().get(String.class); - out.format("GETed %1$s items ...
", r); - - // GET (one) - out.print("
GETing...
"); - r = target.path("apple").request().get(String.class); - out.format("GETed %1$s items ...
", r); - - // DELETE - out.print("
DELETEing...
"); - target.path("banana").request().delete(); - out.format("DELETEed %1$s items ...
", "banana"); - - // GET (all) - out.print("
GETing...
"); - r = target.request().get(String.class); - out.format("GETed %1$s items ...
", r); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/jaxrs-endpoint/src/main/webapp/index.jsp b/jaxrs/jaxrs-endpoint/src/main/webapp/index.jsp deleted file mode 100644 index 298fe5903..000000000 --- a/jaxrs/jaxrs-endpoint/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JAX-RS Endpoint - - -

JAX-RS Endpoint

- Invoke the endpoint. - - From 45a50094b83db59b575739e4d401f013e8dbf9fa Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 15:16:08 +0100 Subject: [PATCH 132/785] Convert JAX-RS samples to Arquillian: Beanvalidation Issue: #78 --- .../jaxrs/beanvalidation/TestServlet.java | 142 ------------------ .../beanvalidation/src/main/webapp/index.jsp | 55 ------- .../jaxrs/beanvalidation/MyResourceTest.java | 36 +++-- 3 files changed, 26 insertions(+), 207 deletions(-) delete mode 100644 jaxrs/beanvalidation/src/main/java/org/javaee7/jaxrs/beanvalidation/TestServlet.java delete mode 100644 jaxrs/beanvalidation/src/main/webapp/index.jsp diff --git a/jaxrs/beanvalidation/src/main/java/org/javaee7/jaxrs/beanvalidation/TestServlet.java b/jaxrs/beanvalidation/src/main/java/org/javaee7/jaxrs/beanvalidation/TestServlet.java deleted file mode 100644 index eb36badb6..000000000 --- a/jaxrs/beanvalidation/src/main/java/org/javaee7/jaxrs/beanvalidation/TestServlet.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.beanvalidation; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("BeanValidation with JAX-RS"); - out.println(""); - out.println(""); - out.println("

BeanValidation with JAX-RS

"); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/endpoint"); - - try { - String r = target.request().post(Entity.text("fo"), String.class); - out.println(r); - } catch (BadRequestException e) { - out.println("BadRequestException caught successfully

"); - } - out.println("Was BadRequestException caught ?"); - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/beanvalidation/src/main/webapp/index.jsp b/jaxrs/beanvalidation/src/main/webapp/index.jsp deleted file mode 100644 index 55ec21331..000000000 --- a/jaxrs/beanvalidation/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - Bean Validation with JAX-RS - - -

Bean Validation with JAX-RS

- Invoke the endpoint. - - diff --git a/jaxrs/beanvalidation/src/test/java/org/javaee7/jaxrs/beanvalidation/MyResourceTest.java b/jaxrs/beanvalidation/src/test/java/org/javaee7/jaxrs/beanvalidation/MyResourceTest.java index da14745f7..519ad7d05 100644 --- a/jaxrs/beanvalidation/src/test/java/org/javaee7/jaxrs/beanvalidation/MyResourceTest.java +++ b/jaxrs/beanvalidation/src/test/java/org/javaee7/jaxrs/beanvalidation/MyResourceTest.java @@ -5,32 +5,48 @@ */ package org.javaee7.jaxrs.beanvalidation; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.BadRequestException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; -import org.junit.After; -import org.junit.AfterClass; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class); + } private static WebTarget target; - public MyResourceTest() { - } + @ArquillianResource + private URL base; - @BeforeClass - public static void setUpClass() { + @Before + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/beanvalidation/webresources/endpoint"); + target = client.target(new URL(base, "webresources/endpoint").toExternalForm()); } @Test @@ -46,7 +62,7 @@ public void testInvalidRequest() { @Test public void testValidRequest() { String r = target.request().post(Entity.text("foo"), String.class); - assertEquals("foo", "foo"); + assertEquals("foo", r); } } From 36750847307baedbd01c97b1219f8511fa2df8b5 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 15:50:58 +0100 Subject: [PATCH 133/785] Convert JAX-RS samples to Arquillian: Client Negotiation Issue: #78 --- .../jaxrs/client/negotiation/MyResource.java | 15 +- .../jaxrs/client/negotiation/People.java | 18 +++ .../jaxrs/client/negotiation/TestServlet.java | 145 ------------------ .../src/main/webapp/index.jsp | 55 ------- .../client/negotiation/MyResourceTest.java | 33 +++- 5 files changed, 52 insertions(+), 214 deletions(-) create mode 100644 jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/People.java delete mode 100644 jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/TestServlet.java delete mode 100644 jaxrs/client-negotiation/src/main/webapp/index.jsp diff --git a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java index 7b59f654e..4493f778b 100644 --- a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java +++ b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java @@ -39,6 +39,8 @@ */ package org.javaee7.jaxrs.client.negotiation; +import java.util.List; + import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @@ -50,12 +52,11 @@ public class MyResource { @GET @Produces({"application/xml", "application/json"}) - public Person[] getList() { - Person[] list = new Person[3]; - list[0] = new Person("Penny", 1); - list[1] = new Person("Leonard", 2); - list[2] = new Person("Sheldon", 3); - - return list; + public List getList() { + People people = new People(); + people.add(new Person("Penny", 1)); + people.add(new Person("Leonard", 2)); + people.add(new Person("Sheldon", 3)); + return people; } } diff --git a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/People.java b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/People.java new file mode 100644 index 000000000..61754651a --- /dev/null +++ b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/People.java @@ -0,0 +1,18 @@ +package org.javaee7.jaxrs.client.negotiation; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class People extends ArrayList { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "person") + public List getPeople() { + return this; + } +} diff --git a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/TestServlet.java b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/TestServlet.java deleted file mode 100644 index 96817696f..000000000 --- a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/TestServlet.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.client.negotiation; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("Client-side Content Negotiation"); - out.println(""); - out.println(""); - out.println("

Client-side Content Negotiation

"); - out.println("Initializing client...
"); - Client client = ClientBuilder.newClient(); - WebTarget target = client - .target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/persons"); - - // GET - out.print("
GETTing application/xml ...
"); - String string = target.request("application/xml").get(String.class); - out.format("GOT the representation: " + string); - - // GET - out.print("

GETTing application/json ...
"); - string = target.request("application/json").get(String.class); - out.format("GOT the representation: " + string); - - out.println("

... done.
"); - - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/client-negotiation/src/main/webapp/index.jsp b/jaxrs/client-negotiation/src/main/webapp/index.jsp deleted file mode 100644 index 90e619e88..000000000 --- a/jaxrs/client-negotiation/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - Client-side Content Negotiation - - -

Client-side Content Negotiation

- Invoke the Client. - - diff --git a/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java b/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java index 4af673717..3fb0509a1 100644 --- a/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java +++ b/jaxrs/client-negotiation/src/test/java/org/javaee7/jaxrs/client/negotiation/MyResourceTest.java @@ -7,34 +7,53 @@ package org.javaee7.jaxrs.client.negotiation; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; -import org.junit.BeforeClass; -import org.junit.Test; import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.json.JSONException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.xml.sax.SAXException; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - private static WebTarget target; + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class, People.class, Person.class); + } - @BeforeClass - public static void setUpClass() { + private WebTarget target; + + @ArquillianResource + private URL base; + + @Before + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client - .target("http://localhost:8080/client-negotiation/webresources/persons"); + target = client.target(new URL(base, "webresources/persons").toExternalForm()); } @Test public void testXML() throws SAXException, IOException { String xml = target.request("application/xml").get(String.class); + System.out.println(xml); XMLAssert.assertXMLEqual("1Penny2Leonard3Sheldon", xml); } From 34f1e0d485c2e73b14acc972cbf5132760c5c90b Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 16:12:44 +0100 Subject: [PATCH 134/785] Convert JAX-RS samples to Arquillian: Dynamic Filter Failing on Wildfly 8.0.0.Beta1/2 due to https://issues.jboss.org/browse/WFLY-2495 Issue: #78 --- .../jaxrs/dynamicfilter/TestServlet.java | 139 ------------------ jaxrs/dynamicfilter/src/main/webapp/index.jsp | 55 ------- .../jaxrs/dynamicfilter/MyResourceTest.java | 37 +++-- 3 files changed, 27 insertions(+), 204 deletions(-) delete mode 100644 jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/TestServlet.java delete mode 100644 jaxrs/dynamicfilter/src/main/webapp/index.jsp diff --git a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/TestServlet.java b/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/TestServlet.java deleted file mode 100644 index 4d8a99870..000000000 --- a/jaxrs/dynamicfilter/src/main/java/org/javaee7/jaxrs/dynamicfilter/TestServlet.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.jaxrs.dynamicfilter; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/TestServlet"}) -public class TestServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.println(""); - out.println(""); - out.println("Dynamic JAX-RS Filter"); - out.println(""); - out.println(""); - out.println("

Dynamic JAX-RS Filter

"); - Client client = ClientBuilder.newClient(); -// client.configuration().register(ClientLoggingFilter.class); - WebTarget target = client.target("http://" - + request.getServerName() - + ":" - + request.getServerPort() - + request.getContextPath() - + "/webresources/fruits"); - String result = target.request().get(String.class); - out.println("Received response: " + result + "

"); - out.println("POSTing a request
"); - target.request().post(null); - out.println("POSTed
"); - out.println("

Check server log for server filter output. " - + "Look for statements starting with ContainerRequestFilter<start>" - + "and ContainerResponseFilter<start> "); - out.println(""); - out.println(""); - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/jaxrs/dynamicfilter/src/main/webapp/index.jsp b/jaxrs/dynamicfilter/src/main/webapp/index.jsp deleted file mode 100644 index 04761ef63..000000000 --- a/jaxrs/dynamicfilter/src/main/webapp/index.jsp +++ /dev/null @@ -1,55 +0,0 @@ - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JAX-RS 2 Dynamic Filter - - -

JAX-RS 2 Dynamic Filter

- Invoke the Client and check the server.log for filter output. - - diff --git a/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java b/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java index c6e6d1c86..00569ebc6 100644 --- a/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java +++ b/jaxrs/dynamicfilter/src/test/java/org/javaee7/jaxrs/dynamicfilter/MyResourceTest.java @@ -5,31 +5,48 @@ */ package org.javaee7.jaxrs.dynamicfilter; +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; -import org.junit.After; -import org.junit.AfterClass; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - private static WebTarget target; - - public MyResourceTest() { + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses( + DynamicServerLogggingFilterFeature.class, MyApplication.class, MyResource.class, + ServerLogged.class, ServerLoggingFilter.class); } - @BeforeClass - public static void setUpClass() { + private WebTarget target; + + @ArquillianResource + private URL base; + + @Before + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client.target("http://localhost:8080/dynamicfilter/webresources/fruits"); + target = client.target(new URL(base, "webresources/fruits").toExternalForm()); } @Test From bf2f3b8911c0dd9dceb10575588906724d7d6df6 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 16:28:41 +0100 Subject: [PATCH 135/785] Convert JAX-RS samples to Arquillian: Filter Issue: #78 --- .../javaee7/jaxrs/filter/MyResourceTest.java | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java b/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java index 92dd85c01..bdae4fe9b 100644 --- a/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java +++ b/jaxrs/filter/src/test/java/org/javaee7/jaxrs/filter/MyResourceTest.java @@ -5,26 +5,47 @@ */ package org.javaee7.jaxrs.filter; +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; -import org.junit.BeforeClass; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - private static WebTarget target; + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class, ServerLoggingFilter.class); + } + + private WebTarget target; + + @ArquillianResource + private URL base; - @BeforeClass - public static void setUpClass() { + @Before + public void setUpClass() throws MalformedURLException { Client client = ClientBuilder.newClient(); client.register(ClientLoggingFilter.class); - target = client.target("http://localhost:8080/filter/webresources/fruits"); + target = client.target(new URL(base, "webresources/fruits").toExternalForm()); } /** From af9326d318e1e3b224043a320c25635eec6ad640 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 17:09:33 +0100 Subject: [PATCH 136/785] Converting to unit tests --- .../object/reader/JsonReaderFromReader.java | 162 ------------------ .../object/reader/JsonReaderFromStream.java | 149 ---------------- json/object-reader/src/main/webapp/index.jsp | 58 ------- .../reader/JsonReaderFromReaderTest.java | 112 ++++++++++++ .../reader/JsonReaderFromStreamTest.java | 113 ++++++++++++ .../{main/webapp => test/resources}/1.json | 0 .../{main/webapp => test/resources}/2.json | 0 .../{main/webapp => test/resources}/3.json | 0 .../{main/webapp => test/resources}/4.json | 0 9 files changed, 225 insertions(+), 369 deletions(-) delete mode 100644 json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromReader.java delete mode 100644 json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromStream.java delete mode 100644 json/object-reader/src/main/webapp/index.jsp create mode 100644 json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromReaderTest.java create mode 100644 json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromStreamTest.java rename json/object-reader/src/{main/webapp => test/resources}/1.json (100%) rename json/object-reader/src/{main/webapp => test/resources}/2.json (100%) rename json/object-reader/src/{main/webapp => test/resources}/3.json (100%) rename json/object-reader/src/{main/webapp => test/resources}/4.json (100%) diff --git a/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromReader.java b/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromReader.java deleted file mode 100644 index 6861ddf62..000000000 --- a/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromReader.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.json.object.reader; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import javax.json.Json; -import javax.json.JsonArray; -import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/JsonReaderFromReader"}) -public class JsonReaderFromReader extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet TestJsonParser"); - out.println(""); - out.println(""); - out.println("

Reading JSON from a Reader

"); - - out.println("Reading an empty object
"); - JsonReader jsonReader = Json.createReader(new StringReader("{}")); - JsonObject json = jsonReader.readObject(); - out.println(json); - - out.println("

Reading an object with two elements
"); - jsonReader = Json.createReader(new StringReader("{" - + " \"apple\":\"red\"," - + " \"banana\":\"yellow\"" - + "}")); - json = jsonReader.readObject(); - out.println(json); - - out.println("

Reading an array with two objects
"); - jsonReader = Json.createReader(new StringReader("[" - + " { \"apple\":\"red\" }," - + " { \"banana\":\"yellow\" }" - + "]")); - JsonArray jsonArr = jsonReader.readArray(); - out.println(jsonArr); - - out.println("

Reading a nested structure
"); - jsonReader = Json.createReader(new StringReader("{" - + " \"title\":\"The Matrix\"," - + " \"year\":1999," - + " \"cast\":[" - + " \"Keanu Reaves\"," - + " \"Laurence Fishburne\"," - + " \"Carrie-Anne Moss\"" - + " ]" - + "}")); - json = jsonReader.readObject(); - out.println(json); - - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromStream.java b/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromStream.java deleted file mode 100644 index 08626be1f..000000000 --- a/json/object-reader/src/main/java/org/javaee7/json/object/reader/JsonReaderFromStream.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.json.object.reader; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.json.Json; -import javax.json.JsonArray; -import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/JsonReaderFromStream"}) -public class JsonReaderFromStream extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet TestJsonReaderFromStream"); - out.println(""); - out.println(""); - out.println("

Reading JSON from a stream packaged with the application

"); - - ServletContext servletContext = request.getServletContext(); - out.println("Reading an empty object
"); - JsonReader jsonReader = Json.createReader(servletContext.getResourceAsStream("/1.json")); - JsonObject json = jsonReader.readObject(); - out.println(json); - - out.println("

Reading an object with two elements
"); - jsonReader = Json.createReader(servletContext.getResourceAsStream("/2.json")); - json = jsonReader.readObject(); - out.println(json); - - out.println("

Reading an array with two objects
"); - jsonReader = Json.createReader(servletContext.getResourceAsStream("/3.json")); - JsonArray jsonArr = jsonReader.readArray(); - out.println(jsonArr); - - out.println("

Reading a nested structure
"); - jsonReader = Json.createReader(servletContext.getResourceAsStream("/4.json")); - json = jsonReader.readObject(); - out.println(json); - - out.println(""); - out.println(""); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/json/object-reader/src/main/webapp/index.jsp b/json/object-reader/src/main/webapp/index.jsp deleted file mode 100644 index 0c19f8918..000000000 --- a/json/object-reader/src/main/webapp/index.jsp +++ /dev/null @@ -1,58 +0,0 @@ - - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JSON Object Model : JSONReader from Reader and Stream - - -

JSON Object Model : JSONReader from Reader and Stream

- - Read JSON using JsonReader (using Reader)
- Read JSON using JsonReader (using Stream)
- - diff --git a/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromReaderTest.java b/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromReaderTest.java new file mode 100644 index 000000000..052a9a463 --- /dev/null +++ b/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromReaderTest.java @@ -0,0 +1,112 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.json.object.reader; + +import java.io.File; +import java.io.StringReader; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonReader; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.json.JSONException; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +/** + * @author Arun Gupta + */ +@RunWith(Arquillian.class) +public class JsonReaderFromReaderTest { + + @Deployment + public static Archive deploy() { + File[] requiredLibraries = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("org.json:json", "org.skyscreamer:jsonassert") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(requiredLibraries); + } + + @Test + public void testEmptyObject() throws JSONException { + JsonReader jsonReader = Json.createReader(new StringReader("{}")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertTrue(json.isEmpty()); + } + + @Test + public void testSimpleObjectWithTwoElements() throws JSONException { + JsonReader jsonReader = Json.createReader(new StringReader("{" + + " \"apple\":\"red\"," + + " \"banana\":\"yellow\"" + + "}")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertFalse(json.isEmpty()); + assertTrue(json.containsKey("apple")); + assertEquals("red", json.getString("apple")); + assertTrue(json.containsKey("banana")); + assertEquals("yellow", json.getString("banana")); + } + + @Test + public void testArray() throws JSONException { + JsonReader jsonReader = Json.createReader(new StringReader("[" + + " { \"apple\":\"red\" }," + + " { \"banana\":\"yellow\" }" + + "]")); + JsonArray jsonArr = jsonReader.readArray(); + assertNotNull(jsonArr); + assertEquals(2, jsonArr.size()); + + JSONAssert.assertEquals("{\"apple\":\"red\"}", jsonArr.get(0).toString(), JSONCompareMode.STRICT); + JSONAssert.assertEquals("{\"banana\":\"yellow\"}", jsonArr.get(1).toString(), JSONCompareMode.STRICT); + } + + @Test + public void testNestedStructure() throws JSONException { + JsonReader jsonReader = Json.createReader(new StringReader("{" + + " \"title\":\"The Matrix\"," + + " \"year\":1999," + + " \"cast\":[" + + " \"Keanu Reaves\"," + + " \"Laurence Fishburne\"," + + " \"Carrie-Anne Moss\"" + + " ]" + + "}")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertFalse(json.isEmpty()); + assertTrue(json.containsKey("title")); + assertEquals("The Matrix", json.getString("title")); + assertTrue(json.containsKey("year")); + assertEquals(1999, json.getInt("year")); + assertTrue(json.containsKey("cast")); + JsonArray jsonArr = json.getJsonArray("cast"); + assertNotNull(jsonArr); + assertEquals(3, jsonArr.size()); + + JSONAssert.assertEquals("[" + + " \"Keanu Reaves\"," + + " \"Laurence Fishburne\"," + + " \"Carrie-Anne Moss\"" + + " ]", jsonArr.toString(), JSONCompareMode.STRICT); + } +} diff --git a/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromStreamTest.java b/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromStreamTest.java new file mode 100644 index 000000000..b44059b38 --- /dev/null +++ b/json/object-reader/src/test/java/org/javaee7/json/object/reader/JsonReaderFromStreamTest.java @@ -0,0 +1,113 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.json.object.reader; + +import java.io.File; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonReader; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.json.JSONException; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +/** + * @author Arun Gupta + */ +@RunWith(Arquillian.class) +public class JsonReaderFromStreamTest { + + @Deployment + public static Archive deploy() { + File[] requiredLibraries = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("org.json:json", "org.skyscreamer:jsonassert") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsResource("1.json") + .addAsResource("2.json") + .addAsResource("3.json") + .addAsResource("4.json") + .addAsLibraries(requiredLibraries); + } + + @Test + public void testEmptyObject() throws JSONException { + JsonReader jsonReader = Json.createReader(Thread + .currentThread() + .getContextClassLoader() + .getResourceAsStream("/1.json")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertTrue(json.isEmpty()); + } + + @Test + public void testSimpleObjectWithTwoElements() throws JSONException { + JsonReader jsonReader = Json.createReader(Thread + .currentThread() + .getContextClassLoader() + .getResourceAsStream("/2.json")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertFalse(json.isEmpty()); + assertTrue(json.containsKey("apple")); + assertEquals("red", json.getString("apple")); + assertTrue(json.containsKey("banana")); + assertEquals("yellow", json.getString("banana")); + } + + @Test + public void testArray() throws JSONException { + JsonReader jsonReader = Json.createReader(Thread + .currentThread() + .getContextClassLoader() + .getResourceAsStream("/3.json")); + JsonArray jsonArr = jsonReader.readArray(); + assertNotNull(jsonArr); + assertEquals(2, jsonArr.size()); + + JSONAssert.assertEquals("{\"apple\":\"red\"}", jsonArr.get(0).toString(), JSONCompareMode.STRICT); + JSONAssert.assertEquals("{\"banana\":\"yellow\"}", jsonArr.get(1).toString(), JSONCompareMode.STRICT); + } + + @Test + public void testNestedStructure() throws JSONException { + JsonReader jsonReader = Json.createReader(Thread + .currentThread() + .getContextClassLoader() + .getResourceAsStream("/4.json")); + JsonObject json = jsonReader.readObject(); + + assertNotNull(json); + assertFalse(json.isEmpty()); + assertTrue(json.containsKey("title")); + assertEquals("The Matrix", json.getString("title")); + assertTrue(json.containsKey("year")); + assertEquals(1999, json.getInt("year")); + assertTrue(json.containsKey("cast")); + JsonArray jsonArr = json.getJsonArray("cast"); + assertNotNull(jsonArr); + assertEquals(3, jsonArr.size()); + + JSONAssert.assertEquals("[" + + " \"Keanu Reaves\"," + + " \"Laurence Fishburne\"," + + " \"Carrie-Anne Moss\"" + + " ]", jsonArr.toString(), JSONCompareMode.STRICT); + } +} diff --git a/json/object-reader/src/main/webapp/1.json b/json/object-reader/src/test/resources/1.json similarity index 100% rename from json/object-reader/src/main/webapp/1.json rename to json/object-reader/src/test/resources/1.json diff --git a/json/object-reader/src/main/webapp/2.json b/json/object-reader/src/test/resources/2.json similarity index 100% rename from json/object-reader/src/main/webapp/2.json rename to json/object-reader/src/test/resources/2.json diff --git a/json/object-reader/src/main/webapp/3.json b/json/object-reader/src/test/resources/3.json similarity index 100% rename from json/object-reader/src/main/webapp/3.json rename to json/object-reader/src/test/resources/3.json diff --git a/json/object-reader/src/main/webapp/4.json b/json/object-reader/src/test/resources/4.json similarity index 100% rename from json/object-reader/src/main/webapp/4.json rename to json/object-reader/src/test/resources/4.json From 5eecbe5d3833fc5113efc8a7923c5439849dc1d0 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 17:11:36 +0100 Subject: [PATCH 137/785] Convert JAX-RS samples to Arquillian: Mapping Exception Issue: #78 --- .../mapping/exceptions/MyResourceTest.java | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java b/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java index 122b62d88..d815279dd 100644 --- a/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java +++ b/jaxrs/mapping-exceptions/src/test/java/org/javaee7/jaxrs/mapping/exceptions/MyResourceTest.java @@ -6,26 +6,50 @@ package org.javaee7.jaxrs.mapping.exceptions; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.ClientErrorException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; /** * * @author argupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - WebTarget target; + + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses( + MyApplication.class, MyResource.class, + OrderNotFoundException.class, OrderNotFoundExceptionMapper.class); + } + @ArquillianResource + private URL base; + + private WebTarget target; @Before - public void setUp() { + public void setUp() throws MalformedURLException { Client client = ClientBuilder.newClient(); target = client - .target("http://localhost:8080/mapping-exceptions/webresources/order"); + .target(new URL(base, "webresources/order").toExternalForm()); } /** From e2f69c5b365ce5ed6929100b5ee44a129ffa2543 Mon Sep 17 00:00:00 2001 From: Aslak Knutsen Date: Tue, 12 Nov 2013 17:20:47 +0100 Subject: [PATCH 138/785] Convert JAX-RS samples to Arquillian: Server Negotiation Issue: #78 --- .../jaxrs/server/negotiation/MyResource.java | 12 ++++--- .../jaxrs/server/negotiation/People.java | 18 ++++++++++ .../server/negotiation/MyResourceTest.java | 35 +++++++++++++------ 3 files changed, 50 insertions(+), 15 deletions(-) create mode 100644 jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/People.java diff --git a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java index 91707e26f..966b1bc58 100644 --- a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java +++ b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java @@ -39,6 +39,8 @@ */ package org.javaee7.jaxrs.server.negotiation; +import java.util.List; + import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @@ -51,11 +53,11 @@ public class MyResource { @GET @Produces({"application/xml; qs=0.75", "application/json; qs=1.0"}) // @Produces({"application/xml", "application/json"}) - public Person[] getList() { - Person[] list = new Person[3]; - list[0] = new Person("Penny", 1); - list[1] = new Person("Leonard", 2); - list[2] = new Person("Sheldon", 3); + public List getList() { + People list = new People(); + list.add(new Person("Penny", 1)); + list.add(new Person("Leonard", 2)); + list.add(new Person("Sheldon", 3)); return list; } diff --git a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/People.java b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/People.java new file mode 100644 index 000000000..ca87e5bd6 --- /dev/null +++ b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/People.java @@ -0,0 +1,18 @@ +package org.javaee7.jaxrs.server.negotiation; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class People extends ArrayList { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "person") + public List getPeople() { + return this; + } +} diff --git a/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java b/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java index c9dc9e1ea..0b8bd08b6 100644 --- a/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java +++ b/jaxrs/server-negotiation/src/test/java/org/javaee7/jaxrs/server/negotiation/MyResourceTest.java @@ -7,17 +7,23 @@ package org.javaee7.jaxrs.server.negotiation; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; + import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; import org.json.JSONException; -import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.xml.sax.SAXException; @@ -25,15 +31,24 @@ /** * @author Arun Gupta */ +@RunWith(Arquillian.class) public class MyResourceTest { - WebTarget target; - + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class) + .addClasses(MyApplication.class, MyResource.class, People.class, Person.class); + } + + @ArquillianResource + private URL base; + + private WebTarget target; + @Before - public void setUp() { + public void setUp() throws MalformedURLException { Client client = ClientBuilder.newClient(); - target = client - .target("http://localhost:8080/server-negotiation/webresources/persons"); + target = client.target(new URL(base, "webresources/persons").toExternalForm()); } @Test @@ -55,7 +70,7 @@ public void testJson2() throws JSONException { @Test public void testXml() throws JSONException, SAXException, IOException { String response = target.request().accept("application/xml").get(String.class); - XMLAssert.assertXMLEqual("1Penny2Leonard3Sheldon", + XMLAssert.assertXMLEqual("1Penny2Leonard3Sheldon", response); } From 43e23de265afb4aba0976d516eb5f365af847fdc Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 18:22:48 +0100 Subject: [PATCH 139/785] Converting to unit tests --- .../generate/StreamingGeneratorServlet.java | 176 ------------------ .../src/main/webapp/index.jsp | 57 ------ .../generate/StreamingGeneratorTest.java | 109 +++++++++++ 3 files changed, 109 insertions(+), 233 deletions(-) delete mode 100644 json/streaming-generate/src/main/java/org/javaee7/json/streaming/generate/StreamingGeneratorServlet.java delete mode 100644 json/streaming-generate/src/main/webapp/index.jsp create mode 100644 json/streaming-generate/src/test/java/org/javaee7/json/streaming/generate/StreamingGeneratorTest.java diff --git a/json/streaming-generate/src/main/java/org/javaee7/json/streaming/generate/StreamingGeneratorServlet.java b/json/streaming-generate/src/main/java/org/javaee7/json/streaming/generate/StreamingGeneratorServlet.java deleted file mode 100644 index c0f947025..000000000 --- a/json/streaming-generate/src/main/java/org/javaee7/json/streaming/generate/StreamingGeneratorServlet.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -package org.javaee7.json.streaming.generate; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.json.Json; -import javax.json.stream.JsonGenerator; -import javax.json.stream.JsonGeneratorFactory; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Arun Gupta - */ -@WebServlet(urlPatterns = {"/StreamingGeneratorServlet"}) -public class StreamingGeneratorServlet extends HttpServlet { - - /** - * Processes requests for both HTTP - * GET and - * POST methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - out.println(""); - out.println(""); - out.println("Create JSON structures"); - out.println(""); - out.println(""); - out.println("

Generate JSON using JsonGeneratorFactory

"); -// JsonGeneratorFactory factory = Json.createGeneratorFactory(new JsonConfiguration().withPrettyPrinting()); - JsonGeneratorFactory factory = Json.createGeneratorFactory(null); -// JsonGenerator gen = factory.createGenerator(System.out); - - out.println("Creating an empty object ...
"); - JsonGenerator gen = factory.createGenerator(out); -// JsonGenerator gen = Json.createGenerator(out); - gen.writeStartObject().writeEnd(); - gen.flush(); - out.println("
...done
"); - - out.println("
Creating a simple object ...
"); - gen = factory.createGenerator(out); - gen - .writeStartObject() - .write("apple", "red") - .write("banana", "yellow") - .writeEnd(); - gen.flush(); - out.println("
...done
"); - - out.println("
Creating a simple array ...
"); - gen = factory.createGenerator(out); - gen - .writeStartArray() - .writeStartObject() - .write("apple", "red") - .writeEnd() - .writeStartObject() - .write("banana", "yellow") - .writeEnd() - .writeEnd(); - gen.flush(); - out.println("
...done
"); - - out.println("
Creating a nested structure ...
"); - gen = factory.createGenerator(out); - gen - .writeStartObject() - .write("title", "The Matrix") - .write("year", 1999) - .writeStartArray("cast") - .write("Keanu Reaves") - .write("Laurence Fishburne") - .write("Carrie-Anne Moss") - .writeEnd() - .writeEnd(); - gen.flush(); - out.println("
...done
"); - - out.println("
...done"); - out.println(""); - out.println(""); - gen.close(); - } - } - - // - /** - * Handles the HTTP - * GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Handles the HTTP - * POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - processRequest(request, response); - } - - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ - @Override - public String getServletInfo() { - return "Short description"; - }// -} diff --git a/json/streaming-generate/src/main/webapp/index.jsp b/json/streaming-generate/src/main/webapp/index.jsp deleted file mode 100644 index f65ee89f1..000000000 --- a/json/streaming-generate/src/main/webapp/index.jsp +++ /dev/null @@ -1,57 +0,0 @@ - - -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - - JSON Streaming : Generate using JsonGeneratorFactory - - -

JSON Streaming : Generate using JsonGeneratorFactory

- - Generate JSON using streaming generator
- - diff --git a/json/streaming-generate/src/test/java/org/javaee7/json/streaming/generate/StreamingGeneratorTest.java b/json/streaming-generate/src/test/java/org/javaee7/json/streaming/generate/StreamingGeneratorTest.java new file mode 100644 index 000000000..eff87b6ce --- /dev/null +++ b/json/streaming-generate/src/test/java/org/javaee7/json/streaming/generate/StreamingGeneratorTest.java @@ -0,0 +1,109 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.javaee7.json.streaming.generate; + +import java.io.File; +import java.io.StringWriter; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonWriter; +import javax.json.stream.JsonGenerator; +import javax.json.stream.JsonGeneratorFactory; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.json.JSONException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +/** + * + * @author Arun Gupta + */ +@RunWith(Arquillian.class) +public class StreamingGeneratorTest { + + @Deployment + public static Archive deploy() { + File[] requiredLibraries = Maven.resolver().loadPomFromFile("pom.xml") + .resolve("org.json:json", "org.skyscreamer:jsonassert") + .withTransitivity().asFile(); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(requiredLibraries); + } + + @Test + public void testEmptyObject() throws JSONException { + JsonGeneratorFactory factory = Json.createGeneratorFactory(null); + StringWriter w = new StringWriter(); + JsonGenerator gen = factory.createGenerator(w); + gen.writeStartObject().writeEnd(); + gen.flush(); + + JSONAssert.assertEquals("{}", w.toString(), JSONCompareMode.STRICT); + } + + @Test + public void testSimpleObject() throws JSONException { + JsonGeneratorFactory factory = Json.createGeneratorFactory(null); + StringWriter w = new StringWriter(); + JsonGenerator gen = factory.createGenerator(w); + + gen + .writeStartObject() + .write("apple", "red") + .write("banana", "yellow") + .writeEnd(); + gen.flush(); + JSONAssert.assertEquals("{\"apple\" : \"red\", \"banana\" : \"yellow\" }", w.toString(), JSONCompareMode.STRICT); + } + + @Test + public void testArray() throws JSONException { + JsonGeneratorFactory factory = Json.createGeneratorFactory(null); + StringWriter w = new StringWriter(); + JsonGenerator gen = factory.createGenerator(w); + + gen + .writeStartArray() + .writeStartObject() + .write("apple", "red") + .writeEnd() + .writeStartObject() + .write("banana", "yellow") + .writeEnd() + .writeEnd(); + gen.flush(); + JSONAssert.assertEquals("[{\"apple\":\"red\"},{\"banana\":\"yellow\"}]", w.toString(), JSONCompareMode.STRICT); + } + + @Test + public void testNestedStructure() throws JSONException { + JsonGeneratorFactory factory = Json.createGeneratorFactory(null); + StringWriter w = new StringWriter(); + JsonGenerator gen = factory.createGenerator(w); + + gen + .writeStartObject() + .write("title", "The Matrix") + .write("year", 1999) + .writeStartArray("cast") + .write("Keanu Reaves") + .write("Laurence Fishburne") + .write("Carrie-Anne Moss") + .writeEnd() + .writeEnd(); + gen.flush(); + JSONAssert.assertEquals("{\"title\":\"The Matrix\",\"year\":1999,\"cast\":[\"Keanu Reaves\",\"Laurence Fishburne\",\"Carrie-Anne Moss\"]}", w.toString(), JSONCompareMode.STRICT); + } +} From cbb14995918c57460221561078531aad36ff3ae9 Mon Sep 17 00:00:00 2001 From: Arun Gupta Date: Tue, 12 Nov 2013 18:23:50 +0100 Subject: [PATCH 140/785] Enabling one more test --- .../java/org/javaee7/json/object/builder/DOMGeneratorTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java b/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java index 3385876ab..0420b57de 100644 --- a/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java +++ b/json/object-builder/src/test/java/org/javaee7/json/object/builder/DOMGeneratorTest.java @@ -75,6 +75,7 @@ public void testArray() throws JSONException { JSONAssert.assertEquals("[{\"apple\":\"red\"},{\"banana\":\"yellow\"}]", w.toString(), JSONCompareMode.STRICT); } + @Test public void testNestedStructure() throws JSONException { JsonObject jsonObject = Json.createObjectBuilder() .add("title", "The Matrix") From 1b184a7741b5535a354b03705f8e9e97376a42b0 Mon Sep 17 00:00:00 2001 From: jfarcand Date: Tue, 12 Nov 2013 12:57:17 -0500 Subject: [PATCH 141/785] Add Atmosphere Sample --- websocket/atmosphere-chat/pom.xml | 53 + .../websocket/atmosphere/ChatEndpoint.java | 76 + .../websocket/atmosphere/JacksonDecoder.java | 38 + .../websocket/atmosphere/JacksonEncoder.java | 38 + .../javaee7/websocket/atmosphere/Message.java | 60 + .../src/main/webapp/WEB-INF/web.xml | 25 + .../src/main/webapp/index.html | 29 + .../src/main/webapp/javascript/application.js | 119 + .../main/webapp/javascript/jquery-1.9.0.js | 9555 +++++++++++++++++ 9 files changed, 9993 insertions(+) create mode 100644 websocket/atmosphere-chat/pom.xml create mode 100644 websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/ChatEndpoint.java create mode 100644 websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonDecoder.java create mode 100644 websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonEncoder.java create mode 100644 websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/Message.java create mode 100644 websocket/atmosphere-chat/src/main/webapp/WEB-INF/web.xml create mode 100644 websocket/atmosphere-chat/src/main/webapp/index.html create mode 100755 websocket/atmosphere-chat/src/main/webapp/javascript/application.js create mode 100644 websocket/atmosphere-chat/src/main/webapp/javascript/jquery-1.9.0.js diff --git a/websocket/atmosphere-chat/pom.xml b/websocket/atmosphere-chat/pom.xml new file mode 100644 index 000000000..f627751e2 --- /dev/null +++ b/websocket/atmosphere-chat/pom.xml @@ -0,0 +1,53 @@ + + + + org.javaee7.websocket + websocket-samples + 1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + org.javaee7.websocket + atmosphere-chat + war + 1.0-SNAPSHOT + atmosphere-chat + http://maven.apache.org + + + org.atmosphere.client + javascript + 2.0.7 + war + + + ch.qos.logback + logback-classic + 1.0.13 + + + + ch.qos.logback + logback-core + 1.0.13 + + + org.atmosphere + atmosphere-runtime + 2.0.3 + + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.3 + + + diff --git a/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/ChatEndpoint.java b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/ChatEndpoint.java new file mode 100644 index 000000000..f9da334b7 --- /dev/null +++ b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/ChatEndpoint.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Jeanfrancois Arcand + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.javaee7.websocket.atmosphere; + +import org.atmosphere.config.service.Disconnect; +import org.atmosphere.config.service.ManagedService; +import org.atmosphere.config.service.Ready; +import org.atmosphere.cpr.AtmosphereResource; +import org.atmosphere.cpr.AtmosphereResourceEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +/** + * Simple annotated class that demonstrate the power of Atmosphere. This class supports all transports, support + * message length guarantee, heart beat, message cache thanks to the @ManagedAService. + * + * The client will first try with WebSocket and then fallback using the client's preference. + */ +@ManagedService(path = "/chat") +public class ChatEndpoint { + private final Logger logger = LoggerFactory.getLogger(ChatEndpoint.class); + + /** + * Invoked when the connection as been fully established and suspended, e.g ready for receiving messages. + * + * @param r + */ + @Ready + public void onReady(final AtmosphereResource r) { + logger.info("Browser {} connected.", r.uuid()); + } + + /** + * Invoked when the client disconnect or when an unexpected closing of the underlying connection happens. + * + * @param event + */ + @Disconnect + public void onDisconnect(AtmosphereResourceEvent event) { + if (event.isCancelled()) { + logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid()); + } else if (event.isClosedByClient()) { + logger.info("Browser {} closed the connection", event.getResource().uuid()); + } + } + + /** + * Simple annotated class that demonstrate how {@link org.atmosphere.config.managed.Encoder} and {@link org.atmosphere.config.managed.Decoder + * can be used. + * + * @param message an instance of {@link Message} + * @return + * @throws IOException + */ + @org.atmosphere.config.service.Message(encoders = {JacksonEncoder.class}, decoders = {JacksonDecoder.class}) + public Message onMessage(Message message) throws IOException { + logger.info("{} just send {}", message.getAuthor(), message.getMessage()); + return message; + } + +} \ No newline at end of file diff --git a/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonDecoder.java b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonDecoder.java new file mode 100644 index 000000000..94ef5505f --- /dev/null +++ b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonDecoder.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Jeanfrancois Arcand + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.javaee7.websocket.atmosphere; + +import org.atmosphere.config.managed.Decoder; +import org.codehaus.jackson.map.ObjectMapper; + +import java.io.IOException; + +/** + * Decode a String into a {@link Message}. + */ +public class JacksonDecoder implements Decoder { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Override + public Message decode(String s) { + try { + return mapper.readValue(s, Message.class); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonEncoder.java b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonEncoder.java new file mode 100644 index 000000000..22bb32b19 --- /dev/null +++ b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/JacksonEncoder.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Jeanfrancois Arcand + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.javaee7.websocket.atmosphere; + +import org.atmosphere.config.managed.Encoder; +import org.codehaus.jackson.map.ObjectMapper; + +import java.io.IOException; + +/** + * Encode a {@link Message} into a String + */ +public class JacksonEncoder implements Encoder { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Override + public String encode(Message m) { + try { + return mapper.writeValueAsString(m); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/Message.java b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/Message.java new file mode 100644 index 000000000..0cc082a9f --- /dev/null +++ b/websocket/atmosphere-chat/src/main/java/org/javaee7/websocket/atmosphere/Message.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Jeanfrancois Arcand + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.javaee7.websocket.atmosphere; + +import java.util.Date; + +public class Message { + + private String message; + private String author; + private long time; + + public Message() { + this("", ""); + } + + public Message(String author, String message) { + this.author = author; + this.message = message; + this.time = new Date().getTime(); + } + + public String getMessage() { + return message; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public void setMessage(String message) { + this.message = message; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + +} diff --git a/websocket/atmosphere-chat/src/main/webapp/WEB-INF/web.xml b/websocket/atmosphere-chat/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000..2a823e28c --- /dev/null +++ b/websocket/atmosphere-chat/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,25 @@ + + + + Atmosphere Chat + Atmosphere Chat + + AtmosphereServlet + AtmosphereServlet + org.atmosphere.cpr.AtmosphereServlet + + org.atmosphere.cpr.packages + org.javaee7.websocket.atmosphere + + true + 0 + + + AtmosphereServlet + /chat/* + + + diff --git a/websocket/atmosphere-chat/src/main/webapp/index.html b/websocket/atmosphere-chat/src/main/webapp/index.html new file mode 100644 index 000000000..b8b13be91 --- /dev/null +++ b/websocket/atmosphere-chat/src/main/webapp/index.html @@ -0,0 +1,29 @@ + + + + + Atmosphere Chat + + + + + + + + + +
+
+ Connecting... + +
+ + \ No newline at end of file diff --git a/websocket/atmosphere-chat/src/main/webapp/javascript/application.js b/websocket/atmosphere-chat/src/main/webapp/javascript/application.js new file mode 100755 index 000000000..22754852d --- /dev/null +++ b/websocket/atmosphere-chat/src/main/webapp/javascript/application.js @@ -0,0 +1,119 @@ +$(function () { + "use strict"; + + var header = $('#header'); + var content = $('#content'); + var input = $('#input'); + var status = $('#status'); + var myName = false; + var author = null; + var logged = false; + var socket = atmosphere; + var subSocket; + var transport = 'websocket'; + + // We are now ready to cut the request + var request = { url: document.location.toString() + 'chat', + contentType : "application/json", + logLevel : 'debug', + transport : transport , + trackMessageLength : true, + reconnectInterval : 5000, + enableXDR: true, + timeout : 60000 }; + + + request.onOpen = function(response) { + content.html($('

', { text: 'Atmosphere connected using ' + response.transport })); + input.removeAttr('disabled').focus(); + status.text('Choose name:'); + transport = response.transport; + }; + + request.onClientTimeout = function(r) { + content.html($('

', { text: 'Client closed the connection after a timeout. Reconnecting in ' + request.reconnectInterval })); + subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: 'is inactive and closed the connection. Will reconnect in ' + request.reconnectInterval })); + input.attr('disabled', 'disabled'); + setTimeout(function (){ + subSocket = socket.subscribe(request); + }, request.reconnectInterval); + }; + + request.onReopen = function(response) { + input.removeAttr('disabled').focus(); + content.html($('

', { text: 'Atmosphere re-connected using ' + response.transport })); + }; + + + request.onTransportFailure = function(errorMsg, request) { + atmosphere.util.info(errorMsg); + request.fallbackTransport = "long-polling"; + header.html($('

', { text: 'Atmosphere Chat. Default transport is WebSocket, fallback is ' + request.fallbackTransport })); + }; + + request.onMessage = function (response) { + + var message = response.responseBody; + try { + var json = atmosphere.util.parseJSON(message); + } catch (e) { + console.log('This doesn\'t look like a valid JSON: ', message); + return; + } + + input.removeAttr('disabled').focus(); + if (!logged && myName) { + logged = true; + status.text(myName + ': ').css('color', 'blue'); + } else { + var me = json.author == author; + var date = typeof(json.time) == 'string' ? parseInt(json.time) : json.time; + addMessage(json.author, json.message, me ? 'blue' : 'black', new Date(date)); + } + }; + + request.onClose = function(response) { + content.html($('

', { text: 'Server closed the connection after a timeout' })); + subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: 'disconnecting' })); + input.attr('disabled', 'disabled'); + }; + + request.onError = function(response) { + content.html($('

', { text: 'Sorry, but there\'s some problem with your ' + + 'socket or the server is down' })); + logged = false; + }; + + request.onReconnect = function(request, response) { + content.html($('

', { text: 'Connection lost, trying to reconnect. Trying to reconnect ' + request.reconnectInterval})); + input.attr('disabled', 'disabled'); + }; + + subSocket = socket.subscribe(request); + + input.keydown(function(e) { + if (e.keyCode === 13) { + var msg = $(this).val(); + + // First message is always the author's name + if (author == null) { + author = msg; + } + + subSocket.push(atmosphere.util.stringifyJSON({ author: author, message: msg })); + $(this).val(''); + + input.attr('disabled', 'disabled'); + if (myName === false) { + myName = msg; + } + } + }); + + function addMessage(author, message, color, datetime) { + content.append('

' + author + ' @ ' + + + (datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours()) + ':' + + (datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes()) + + ': ' + message + '

'); + } +}); diff --git a/websocket/atmosphere-chat/src/main/webapp/javascript/jquery-1.9.0.js b/websocket/atmosphere-chat/src/main/webapp/javascript/jquery-1.9.0.js new file mode 100644 index 000000000..67e31603d --- /dev/null +++ b/websocket/atmosphere-chat/src/main/webapp/javascript/jquery-1.9.0.js @@ -0,0 +1,9555 @@ +/*! + * jQuery JavaScript Library v1.9.0 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-1-14 + */ +(function( window, undefined ) { +"use strict"; +var + // A central reference to the root jQuery(document) + rootjQuery, + + // The deferred used on DOM ready + readyList, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + location = window.location, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // [[Class]] -> type pairs + class2type = {}, + + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "1.9.0", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }, + + // The ready event handler and self cleanup method + DOMContentLoaded = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + } else if ( document.readyState === "complete" ) { + // we're here because readyState === "complete" in oldIE + // which is good enough for us to call the dom ready! + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + if ( obj == null ) { + return String( obj ); + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ); + if ( scripts ) { + jQuery( scripts ).remove(); + } + return jQuery.merge( [], parsed.childNodes ); + }, + + parseJSON: function( data ) { + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + if ( data === null ) { + return data; + } + + if ( typeof data === "string" ) { + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + if ( data ) { + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + } + } + } + + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + core_push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return core_concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + return jQuery.inArray( fn, list ) > -1; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function() { + + var support, all, a, select, opt, input, fragment, eventName, isSupported, i, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
a"; + + // Support tests won't run in some limited or non-browser environments + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + if ( !all || !a || !all.length ) { + return {}; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + support = { + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) + checkOn: !!input.value, + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Tests for enctype support on a form (#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: document.compatMode === "CSS1Compat", + + // Will be defined later + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Support: IE<9 + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + // Check if we can trust getAttribute("value") + input = document.createElement("input"); + input.setAttribute( "value", "" ); + support.input = input.getAttribute( "value" ) === ""; + + // Check if an input maintains its value after becoming a radio + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); + + fragment = document.createDocumentFragment(); + fragment.appendChild( input ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php + for ( i in { submit: true, change: true, focusin: true }) { + div.setAttribute( eventName = "on" + i, "t" ); + + support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; + } + + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, tds, + divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + body.appendChild( container ).appendChild( div ); + + // Support: IE8 + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + div.innerHTML = "
t
"; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Support: IE8 + // Check if empty table cells still have offsetWidth/Height + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Support: IE6 + // Check if elements with layout shrink-wrap their children + div.style.display = "block"; + div.innerHTML = "
"; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + body.style.zoom = 1; + } + + body.removeChild( container ); + + // Null elements to avoid leaks in IE + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + all = select = fragment = opt = a = input = null; + + return support; +})(); + +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +function internalData( elem, name, data, pvt /* Internal Use Only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt /* For internal use only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data, false ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name, false ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + // Try to fetch any internally stored data first + return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; + } + + this.each(function() { + jQuery.data( this, key, value ); + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + hooks.cur = fn; + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rfocusable = /^(?:input|select|textarea|button|object)$/i, + rclickable = /^(?:a|area)$/i, + rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, + ruseDefault = /^(?:checked|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + getSetInput = jQuery.support.input; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); + } + + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); + + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); + } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + // Toggle whole class name + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attr: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + + } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + // In IE9+, Flash objects don't have .getAttribute (#12945) + // Support: IE9+ + if ( typeof elem.getAttribute !== "undefined" ) { + ret = elem.getAttribute( name ); + } + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( rboolean.test( name ) ) { + // Set corresponding property to false for boolean attributes + // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 + if ( !getSetAttribute && ruseDefault.test( name ) ) { + elem[ jQuery.camelCase( "default-" + name ) ] = + elem[ propName ] = false; + } else { + elem[ propName ] = false; + } + + // See #9699 for explanation of this approach (setting first, then removal) + } else { + jQuery.attr( elem, name, "" ); + } + + elem.removeAttribute( getSetAttribute ? name : propName ); + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + var + // Use .prop to determine if this attribute is understood as boolean + prop = jQuery.prop( elem, name ), + + // Fetch it accordingly + attr = typeof prop === "boolean" && elem.getAttribute( name ), + detail = typeof prop === "boolean" ? + + getSetInput && getSetAttribute ? + attr != null : + // oldIE fabricates an empty string for missing boolean attributes + // and conflates checked/selected into attroperties + ruseDefault.test( name ) ? + elem[ jQuery.camelCase( "default-" + name ) ] : + !!attr : + + // fetch an attribute node for properties not recognized as boolean + elem.getAttributeNode( name ); + + return detail && detail.value !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + // IE<8 needs the *property* name + elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); + + // Use defaultChecked and defaultSelected for oldIE + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; + } + + return name; + } +}; + +// fix oldIE value attroperty +if ( !getSetInput || !getSetAttribute ) { + jQuery.attrHooks.value = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return jQuery.nodeName( elem, "input" ) ? + + // Ignore the value *property* by using defaultValue + elem.defaultValue : + + ret && ret.specified ? ret.value : undefined; + }, + set: function( elem, value, name ) { + if ( jQuery.nodeName( elem, "input" ) ) { + // Does not return so that setAttribute is also used + elem.defaultValue = value; + } else { + // Use nodeHook if defined (#1954); otherwise setAttribute is fine + return nodeHook && nodeHook.set( elem, value, name ); + } + } + }; +} + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + elem.setAttributeNode( + (ret = elem.ownerDocument.createAttribute( name )) + ); + } + + ret.value = value += ""; + + // Break association with cloned elements by also using setAttribute (#9646) + return name === "value" || value === elem.getAttribute( name ) ? + value : + undefined; + } + }; + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + nodeHook.set( elem, value === "" ? false : value, name ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); +} + + +// Some attributes require a special call on IE +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret == null ? undefined : ret; + } + }); + }); + + // href/src property should get the full normalized URL (#10299/#12915) + jQuery.each([ "href", "src" ], function( i, name ) { + jQuery.propHooks[ name ] = { + get: function( elem ) { + return elem.getAttribute( name, 4 ); + } + }; + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Note: IE uppercases css property names, but if we were to .toLowerCase() + // .cssText, that would destroy case senstitivity in URL's, like in "background" + return elem.style.cssText || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + // Don't attach events to noData or text/comment nodes (but allow plain objects) + elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data( elem ); + + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = event.type || event, + namespaces = event.namespace ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + event.isTrigger = true; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur != this; cur = cur.parentNode || this ) { + + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + } + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== document.activeElement && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === document.activeElement && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + + beforeunload: { + postDispatch: function( event ) { + + // Even when returnValue equals to undefined Firefox will still show alert + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === "undefined" ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + hasDuplicate, + outermostContext, + + // Local document vars + setDocument, + document, + docElem, + documentIsXML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + sortOrder, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rsibling = /[\x20\t\r\n\f]*[+~]/, + + rnative = /\{\s*\[native code\]\s*\}/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, + funescape = function( _, escaped ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + return high !== high ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Use a stripped-down slice if we can't use a native one +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +/** + * For feature detection + * @param {Function} fn The function to test for native support + */ +function isNative( fn ) { + return rnative.test( fn + "" ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var cache, + keys = []; + + return (cache = function( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + }); +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( !documentIsXML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.test(selector) ) { + old = true; + nid = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsXML = isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.tagNameNoComments = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if attributes should be retrieved by attribute nodes + support.attributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }); + + // Check if getElementsByClassName can be trusted + support.getByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }); + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
"; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = doc.getElementsByName && + // buggy browsers will return fewer than the correct 2 + doc.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + doc.getElementsByName( expando + 0 ).length; + support.getIdNotName = !doc.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }) ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }; + + // ID find and filter + if ( support.getIdNotName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && !documentIsXML ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.tagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { + return context.getElementsByClassName( className ); + } + }; + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21), + // no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ]; + + if ( (support.qsa = isNative(doc.querySelectorAll)) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE8 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = ""; + if ( div.querySelectorAll("[i^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + var compare; + + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { + if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { + if ( a === doc || contains( preferredDoc, a ) ) { + return -1; + } + if ( b === doc || contains( preferredDoc, b ) ) { + return 1; + } + return 0; + } + return compare & 4 ? -1 : 1; + } + + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE ); + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + // Always assume the presence of duplicates if sort doesn't + // pass them to our comparison function (as in Google Chrome). + hasDuplicate = false; + [0, 0].sort( sortOrder ); + support.detectDuplicates = hasDuplicate; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyQSA always contains :focus, so no need for an existence check + if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [elem] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + var val; + + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + if ( !documentIsXML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( documentIsXML || support.attributes ) { + return elem.getAttribute( name ); + } + return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? + name : + val && val.specified ? val.value : null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + i = 1, + j = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +function siblingCheck( a, b ) { + var cur = a && b && a.nextSibling; + + for ( ; cur; cur = cur.nextSibling ) { + if ( cur === b ) { + return -1; + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[4] ) { + match[2] = match[4]; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + + nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.substr( result.length - check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifider + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsXML ? + elem.getAttribute("xml:lang") || elem.getAttribute("lang") : + elem.lang) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push( { + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && combinator.dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Nested matchers should use non-integer dirruns + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + for ( j = 0; (matcher = elementMatchers[j]); j++ ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + // `i` starts as a string, so matchedCount would equal "00" if there are no elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + for ( j = 0; (matcher = setMatchers[j]); j++ ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !documentIsXML && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + documentIsXML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Initialize with the default document +setDocument(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, ret, self; + + if ( typeof selector !== "string" ) { + self = this; + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < self.length; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + ret = []; + for ( i = 0; i < this.length; i++ ) { + jQuery.find( selector, this[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( jQuery.unique( ret ) ); + ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false) ); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true) ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( jQuery.unique(all) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, false, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function( value ) { + var isFunc = jQuery.isFunction( value ); + + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( !isFunc && typeof value !== "string" ) { + value = jQuery( value ).not( this ).detach(); + } + + return this.domManip( [ value ], true, function( elem ) { + var next = this.nextSibling, + parent = this.parentNode; + + if ( parent && this.nodeType === 1 || this.nodeType === 11 ) { + + jQuery( this ).remove(); + + if ( next ) { + next.parentNode.insertBefore( elem, next ); + } else { + parent.appendChild( elem ); + } + } + }); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = core_concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, table ? self.html() : undefined ); + } + self.domManip( args, table, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + node, + i + ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Hope ajax is available... + jQuery.ajax({ + url: node.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + var attr = elem.getAttributeNode("type"); + elem.type = ( attr && attr.specified ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, data, e; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + core_push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( manipulation_rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, srcElements, node, i, clone, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var contains, elem, tag, tmp, wrap, tbody, j, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var data, id, elem, type, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== "undefined" ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + core_deletedIds.push( id ); + } + } + } + } + } +}); +var curCSS, getStyles, iframe, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity\s*=\s*([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var elem, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + values[ index ] = jQuery._data( elem, "olddisplay" ); + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && elem.style.display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else if ( !values[ index ] && !isHidden( elem ) ) { + jQuery._data( elem, "olddisplay", jQuery.css( elem, "display" ) ); + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + var bool = typeof state === "boolean"; + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "columnCount": true, + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, + // but it would mean to define eight (for every problematic property) identical functions + if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( extra ) { + num = parseFloat( val ); + return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: we've included the "window" in window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + getStyles = function( elem ) { + return window.getComputedStyle( elem, null ); + }; + + curCSS = function( elem, name, _computed ) { + var width, minWidth, maxWidth, + computed = _computed || getStyles( elem ), + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, + style = elem.style; + + if ( computed ) { + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + getStyles = function( elem ) { + return elem.currentStyle; + }; + + curCSS = function( elem, name, _computed ) { + var left, rs, rsLeft, + computed = _computed || getStyles( elem ), + ret = computed ? computed[ name ] : undefined, + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rs = elem.runtimeStyle; + rsLeft = rs && rs.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + rs.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + rs.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + // at this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + // Use the already-created iframe if possible + iframe = ( iframe || + jQuery("