repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/JaxrsAppTwoTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic;
import java.net.URL;
import jakarta.ws.rs.core.Response;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppResourceTwo;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppTwo;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JaxrsAppTwoTestCase {
@ArquillianResource
URL baseUrl;
private static final String CONTENT_ERROR_MESSAGE = "Wrong content of response";
@Deployment
public static Archive<?> deploySimpleResource() {
WebArchive war = ShrinkWrap.create(WebArchive.class, JaxrsAppTwoTestCase.class.getSimpleName() + ".war");
war.addAsWebInfResource(JaxrsAppTwoTestCase.class.getPackage(), "JaxrsAppTwoWeb.xml", "web.xml");
war.addClasses(JaxrsAppResource.class, JaxrsAppResourceTwo.class,
JaxrsAppTwo.class);
return war;
}
/**
* The jaxrs 2.0 spec says that when a Application subclass returns
* values for getClasses or getSingletons methods the returned classes
* should be the only ones used.
* This test confirms that returning a value for getClasses is
* handled properly by the server.
*/
@Test
public void testDemo() throws Exception {
// check the returned resource class is available
Client client = ClientBuilder.newClient();
try {
String url = baseUrl.toString() + "resources";
WebTarget base = client.target(url);
String value = base.path("example").request().get(String.class);
Assert.assertEquals(CONTENT_ERROR_MESSAGE, "Hello world!", value);
} finally {
client.close();
}
// check the undeclared resource class is NOT available
client = ClientBuilder.newClient();
try {
String url = baseUrl.toString() + "resources";
WebTarget base = client.target(url);
Response r = base.path("exampleTwo").request().get();
Assert.assertEquals("404 error not received", 404, r.getStatus());
} finally {
client.close();
}
}
}
| 3,828 | 38.885417 | 113 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/JaxrsContextParamTwoMgtApiTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsApp;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppResource;
import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.Assert;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JaxrsContextParamTwoMgtApiTestCase extends ContainerResourceMgmtTestBase {
@Deployment
public static Archive<?> deploySimpleResource() {
WebArchive war = ShrinkWrap.create(WebArchive.class, JaxrsContextParamTwoMgtApiTestCase.class.getSimpleName() + ".war");
war.addAsWebInfResource(JaxrsContextParamTwoMgtApiTestCase.class.getPackage(), "JaxrsContextParamTwoWeb.xml", "web.xml");
war.addClasses(JaxrsAppResource.class, JaxrsApp.class);
return war;
}
/**
* When web.xml is present in the archive and the Application subclass is
* declared only in the context-param element. When the subclass does not
* provide a list of classes to use in the getClasses or getSingletons method,
* then the RESTEasy Configuration Switch must be declared in a context-param.
* confirm resource class is registered in the (CLI) management model
* Corresponding CLI cmd:
* ./jboss-cli.sh -c --command="/deployment=JaxrsContextParamTwoMgtApiTestCase.war/subsystem=jaxrs:read-resource(include-runtime=true,recursive=true)"
*
*/
@Test
public void testContextParam() throws IOException, MgmtOperationException {
ModelNode op = Util.createOperation(READ_RESOURCE_OPERATION,
PathAddress.pathAddress(DEPLOYMENT, JaxrsContextParamTwoMgtApiTestCase.class.getSimpleName() + ".war")
.append(SUBSYSTEM, "jaxrs")
.append("rest-resource", JaxrsAppResource.class.getCanonicalName()));
op.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true);
ModelNode result = executeOperation(op);
Assert.assertFalse("Subsystem is empty.", result.keys().size() == 0);
ModelNode resClass = result.get("resource-class");
Assert.assertNotNull("No resource-class present.", resClass);
Assert.assertTrue("Expected resource-class not found.",
resClass.toString().contains(JaxrsAppResource.class.getSimpleName()));
}
}
| 4,345 | 48.386364 | 154 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/JaxrsAppNoXmlTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsApp;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppResource;
import org.jboss.as.test.integration.jaxrs.spec.basic.resource.JaxrsAppThree;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
/**
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JaxrsAppNoXmlTestCase {
@ArquillianResource
URL baseUrl;
private static final String CONTENT_ERROR_MESSAGE = "Wrong content of response";
@Deployment
public static Archive<?> deploySimpleResource() {
WebArchive war = ShrinkWrap.create(WebArchive.class, JaxrsAppNoXmlTestCase.class.getSimpleName() + ".war");
war.addClasses(JaxrsAppResource.class, JaxrsApp.class, JaxrsAppThree.class);
return war;
}
/**
* The jaxrs 2.0 spec says when no web.xml file is present the
* archive is scanned for Application subclasses, resource and
* provider classes.
*/
@Test
public void testDemo() throws Exception {
// check 1st Application subclass
Client client = ClientBuilder.newClient();
try {
String url = baseUrl.toString() + "resourcesAppPath";
WebTarget base = client.target(url);
String value = base.path("example").request().get(String.class);
Assert.assertEquals(CONTENT_ERROR_MESSAGE, "Hello world!", value);
} finally {
client.close();
}
// check 2nd Application subclass
client = ClientBuilder.newClient();
try {
String url = baseUrl.toString() + "resourcesThree";
WebTarget base = client.target(url);
String value = base.path("example").request().get(String.class);
Assert.assertEquals(CONTENT_ERROR_MESSAGE, "Hello world!", value);
} finally {
client.close();
}
}
}
| 3,514 | 37.626374 | 115 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/resource/JaxrsApp.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic.resource;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/resourcesAppPath")
public class JaxrsApp extends Application {
}
| 1,260 | 41.033333 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/resource/JaxrsAppTwo.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic.resource;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class JaxrsAppTwo extends Application {
public static Set<Class<?>> classes = new HashSet<Class<?>>();
@Override
public Set<Class<?>> getClasses() {
classes.add(JaxrsAppResource.class);
return classes;
}
}
| 1,433 | 36.736842 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/resource/JaxrsAppThree.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic.resource;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/resourcesThree")
public class JaxrsAppThree extends Application {
}
| 1,263 | 41.133333 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/resource/JaxrsAppResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic.resource;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
/**
* User: rsearls
* Date: 2/2/17
*/
@Path("example")
public class JaxrsAppResource {
@GET
@Produces("text/plain")
public String get() {
return "Hello world!";
}
}
| 1,375 | 33.4 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/spec/basic/resource/JaxrsAppResourceTwo.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.spec.basic.resource;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
/**
* User: rsearls
* Date: 2/2/17
*/
@Path("exampleTwo")
public class JaxrsAppResourceTwo {
@GET
@Produces("text/plain")
public String get() {
return "Two Hello world!";
}
}
| 1,385 | 33.65 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/yaml/YamlResource.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.yaml;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
/**
* @author Stuart Douglas
*/
@Path("/atom")
public class YamlResource {
@GET
@Produces("text/x-yaml")
public Customer get() {
return new Customer("John", "Citizen");
}
}
| 1,352 | 32.825 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/yaml/JaxrsYamlProviderTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.yaml;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the resteasy multipart provider
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
// TODO (jrp) what do we do here?
@Ignore("YAML is not built into RESTEasy any more. We need to look at this.")
public class JaxrsYamlProviderTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrsnoap.war");
war.addPackage(HttpRequest.class.getPackage());
war.addPackage(JaxrsYamlProviderTestCase.class.getPackage());
war.addAsResource(new StringAsset("org.jboss.resteasy.plugins.providers.YamlProvider"), "META-INF/services/jakarta.ws.rs.ext.Providers");
war.addAsWebInfResource(WebXml.get("<servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/myjaxrs/*</url-pattern>\n" +
" </servlet-mapping>\n" +
"\n"),"web.xml");
return war;
}
@ArquillianResource
private URL url;
private String performCall(String urlPattern) throws Exception {
return HttpRequest.get(url + urlPattern, 10, TimeUnit.SECONDS);
}
@Test
public void testJaxRsWithNoApplication() throws Exception {
String result = performCall("myjaxrs/atom");
Assert.assertEquals("!!org.jboss.as.test.integration.jaxrs.yaml.Customer {first: John, last: Citizen}\n", result);
}
}
| 3,230 | 37.927711 | 145 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/yaml/Customer.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.yaml;
/**
* @author Stuart Douglas
*/
public class Customer {
private String first;
private String last;
public Customer(String first, String last) {
this.first = first;
this.last = last;
}
public Customer() {
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
| 1,586 | 27.339286 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/MyApplication.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* A Jakarta RESTful Web Services application.
*
* @author Josef Cacek
*/
@ApplicationPath(MyApplication.APPLICATION_PATH)
public class MyApplication extends Application {
public static final String APPLICATION_PATH = "/";
}
| 1,392 | 37.694444 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/ExceptionMapperProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
/**
* A Jakarta RESTful Web Services test implementation for {@link ExceptionMapper}. If an Exception occurs, returns HTTP OK (200) and prints
* {@value #ERROR_MESSAGE} as the response body.
*
* @author Josef Cacek
*/
@Provider
@Path("/")
public class ExceptionMapperProvider implements ExceptionMapper<Exception> {
private static final Logger LOGGER = Logger.getLogger(ExceptionMapperProvider.class);
public static final String ERROR_MESSAGE = "ERROR OCCURRED";
public static final String PATH_EXCEPTION = "/exception";
// Public methods --------------------------------------------------------
/**
* Responds {@value #ERROR_MESSAGE} to the OK (200) response.
*
* @param exception
*
* @return
*
* @see jakarta.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
*/
@Override
public Response toResponse(Exception exception) {
LOGGER.trace("Mapped exception", exception);
return Response.ok().entity(ERROR_MESSAGE).build();
}
/**
* Test method for the Provider. Throws an IllegalArgumentException.
*
* @return
*/
@GET
@Path(PATH_EXCEPTION)
public Response testExceptionMapper() {
LOGGER.trace("Throwing exception");
throw new IllegalArgumentException("Exception expected.");
}
}
| 2,618 | 33.012987 | 139 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/CustomProvidersTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import java.util.Currency;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.logging.Logger;
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 org.junit.runner.RunWith;
/**
* A JUnit 4 test for testing deployment multiple Jakarta RESTful Web Services providers from different modules. It's mainly a regression test for
* JBPAPP-9963 issue.
*
* @author Josef Cacek
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CustomProvidersTestCase {
private static Logger LOGGER = Logger.getLogger(CustomProvidersTestCase.class);
private static final String WEBAPP_TEST_EXCEPTION_MAPPER = "test-exception-mapper";
private static final String WEBAPP_TEST_CONVERTER = "test-converter";
// Public methods --------------------------------------------------------
/**
* Creates {@value #WEBAPP_TEST_EXCEPTION_MAPPER} web application.
*
* @return
*/
@Deployment(name = WEBAPP_TEST_EXCEPTION_MAPPER)
public static WebArchive deployMapperApp() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEBAPP_TEST_EXCEPTION_MAPPER + ".war");
war.addClasses(MyApplication.class, ExceptionMapperProvider.class);
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return war;
}
/**
* Creates {@value #WEBAPP_TEST_CONVERTER} web application.
*
* @return
*/
@Deployment(name = WEBAPP_TEST_CONVERTER)
public static WebArchive deployConverterApp() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEBAPP_TEST_CONVERTER + ".war");
war.addClasses(MyApplication.class, CurrencyConverterProvider.class, CurrencyParamConverter.class);
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return war;
}
/**
* Test Jakarta RESTful Web Services providers deployment, when 2 web applications are used.
*
* @param webAppURL
* @throws Exception
*/
@Test
@OperateOnDeployment(WEBAPP_TEST_EXCEPTION_MAPPER)
public void testProvidersInTwoWars(@ArquillianResource URL webAppURL) throws Exception {
final String path = webAppURL.toExternalForm() + ExceptionMapperProvider.PATH_EXCEPTION.substring(1);
LOGGER.trace("Requested path: " + path);
assertEquals(ExceptionMapperProvider.ERROR_MESSAGE, HttpRequest.get(path, 10, TimeUnit.SECONDS));
final String converterPath = webAppURL.toExternalForm().replace(WEBAPP_TEST_EXCEPTION_MAPPER, WEBAPP_TEST_CONVERTER)
+ CurrencyConverterProvider.PATH_CONVERTER.substring(1).replace(
"{" + CurrencyConverterProvider.PARAM_CURRENCY + "}", "USD");
LOGGER.trace("Requested path: " + converterPath);
assertEquals(Currency.getInstance("USD").getSymbol(), HttpRequest.get(converterPath, 10, TimeUnit.SECONDS));
}
}
| 4,453 | 40.626168 | 146 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/CurrencyConverterProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider;
import java.util.Currency;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.ext.ParamConverter;
import org.jboss.logging.Logger;
/**
* A Jakarta RESTful Web Services {@link ParamConverter} test implementation for Currency.
*
* @author Josef Cacek
*/
@Path("/")
public class CurrencyConverterProvider {
private static final Logger LOGGER = Logger.getLogger(CurrencyConverterProvider.class);
public static final String PARAM_CURRENCY = "currency";
public static final String PATH_CONVERTER = "/converter/{" + PARAM_CURRENCY + "}";
/**
* Test method for currency converter.
*
* @param currency
*
* @return
*/
@GET
@Path(PATH_CONVERTER)
public String testCurrencyConverter(@PathParam(PARAM_CURRENCY) Currency currency) {
LOGGER.trace("Returning currency symbol");
return currency.getSymbol();
}
}
| 2,015 | 33.169492 | 91 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/CurrencyParamConverter.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* 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.jboss.as.test.integration.jaxrs.provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Currency;
import jakarta.ws.rs.ext.ParamConverter;
import jakarta.ws.rs.ext.ParamConverterProvider;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@Provider
public class CurrencyParamConverter implements ParamConverter<Currency>, ParamConverterProvider {
private static final Logger LOGGER = Logger.getLogger(CurrencyParamConverter.class);
// Public methods --------------------------------------------------------
/**
* Converts from a provided String currency code to a Currency instance.
*
* @param str
*
* @return
*/
@Override
public Currency fromString(String str) {
LOGGER.trace("Converting to currency: " + str);
return Currency.getInstance(str);
}
/**
* Returns Currency code.
*
* @param currency
*
* @return
*/
@Override
public String toString(Currency currency) {
return currency.getCurrencyCode();
}
@Override
@SuppressWarnings("unchecked")
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType, final Annotation[] annotations) {
if (Currency.class.isAssignableFrom(rawType)) {
return (ParamConverter<T>) this;
}
return null;
}
}
| 2,096 | 28.125 | 127 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/preference/CustomMessageBodyWriter.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider.preference;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.MessageBodyWriter;
import jakarta.ws.rs.ext.Provider;
@Provider
@Produces("text/plain")
public class CustomMessageBodyWriter implements MessageBodyWriter<Object> {
public long getSize(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
return -1;
}
public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
return true;
}
public void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(arg6,StandardCharsets.UTF_8));
bw.write(arg0.toString());
bw.flush();
}
}
| 2,290 | 38.5 | 113 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/preference/CustomProviderPreferenceTest.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider.preference;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
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.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Tests that user-provided providers are given priority over built-in providers.
*
* AS7-1400
*
* @author Jozef Hartinger
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CustomProviderPreferenceTest {
@Deployment(testable = false)
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "providers.war");
war.add(EmptyAsset.INSTANCE, "WEB-INF/beans.xml");
war.addClasses(CustomProviderPreferenceTest.class, CustomMessageBodyWriter.class, Resource.class);
war.addAsWebInfResource(WebXml.get("<servlet-mapping>\n"
+ " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n"
+ " <url-pattern>/api/*</url-pattern>\n" + " </servlet-mapping>\n" + "\n"), "web.xml");
return war;
}
@ArquillianResource
private URL url;
private String performCall(String urlPattern) throws Exception {
return HttpRequest.get(url + urlPattern, 10, TimeUnit.SECONDS);
}
@Test
public void testCustomMessageBodyWriterIsUsed() throws Exception {
assertEquals("true", performCall("api/user"));
}
}
| 2,946 | 37.776316 | 113 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/provider/preference/Resource.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.provider.preference;
import java.lang.annotation.Annotation;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.ext.MessageBodyWriter;
import jakarta.ws.rs.ext.Providers;
@Path("/user")
@Produces("text/plain")
public class Resource {
@Context
private Providers providers;
@GET
public boolean getUser() {
MessageBodyWriter<?> writer = providers.getMessageBodyWriter(Object.class, Object.class, new Annotation[0], MediaType.TEXT_PLAIN_TYPE);
return writer instanceof CustomMessageBodyWriter;
}
}
| 1,721 | 35.638298 | 143 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingFeatureOnDemandModeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.URL;
import java.util.Map;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.tracing.api.RESTEasyTracing;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(TracingFeatureOnDemandModeTestCase.TracingSetupServerSetupTask.class)
public class TracingFeatureOnDemandModeTestCase {
public static class TracingSetupServerSetupTask extends JaxrsSubsystemServerSetupTask {
@Override
protected Map<String, Object> subsystemAttributes() {
return Map.of("tracing-type", "ON_DEMAND");
}
}
@Deployment
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "tracing.war")
.addClasses(TracingConfigResource.class, TracingApp.class);
}
@ArquillianResource
private URL url;
private jakarta.ws.rs.core.Response performCall(Client client, String urlPattern) {
return client.target(url + urlPattern).request().header(RESTEasyTracing.HEADER_ACCEPT, "").
header(RESTEasyTracing.HEADER_THRESHOLD, ResteasyContextParameters.RESTEASY_TRACING_LEVEL_VERBOSE)
.get();
}
@Test
public void testTracingConfig() throws Exception {
try (Client client = ClientBuilder.newClient()) {
String result2 = performCall(client, "type").readEntity(String.class);
assertEquals("ON_DEMAND", result2);
String result3 = performCall(client, "logger").getHeaderString(RESTEasyTracing.HEADER_TRACING_PREFIX + "001");
assertNotNull(result3);
}
}
}
| 3,321 | 38.547619 | 122 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingApp.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/")
public class TracingApp extends Application {
@Override
public Set<Object> getSingletons() {
Set<Object> set = new HashSet<>();
set.add(new TracingConfigResource());
return set;
}
}
| 1,445 | 35.15 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/JaxrsSubsystemServerSetupTask.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import java.util.Map;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public abstract class JaxrsSubsystemServerSetupTask extends SnapshotRestoreSetupTask {
@Override
protected void doSetup(final ManagementClient client, final String containerId) throws Exception {
final ModelNode address = Operations.createAddress("subsystem", "jaxrs");
// Write each attribute in a composite operation
final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
subsystemAttributes().forEach((name, value) -> {
if (value instanceof String) {
builder.addStep(Operations.createWriteAttributeOperation(address, name, (String) value));
} else if (value instanceof Boolean) {
builder.addStep(Operations.createWriteAttributeOperation(address, name, (Boolean) value));
} else if (value instanceof Integer) {
builder.addStep(Operations.createWriteAttributeOperation(address, name, (Integer) value));
} else if (value instanceof Long) {
builder.addStep(Operations.createWriteAttributeOperation(address, name, (Long) value));
} else if (value instanceof ModelNode) {
builder.addStep(Operations.createWriteAttributeOperation(address, name, (ModelNode) value));
} else {
builder.addStep(Operations.createWriteAttributeOperation(address, name, String.valueOf(value)));
}
});
final ModelNode result = client.getControllerClient().execute(builder.build());
if (!Operations.isSuccessfulOutcome(result)) {
throw new RuntimeException("Failed to write attributes: " + Operations.getFailureDescription(result).asString());
}
// Reload if required
ServerReload.reloadIfRequired(client);
}
protected abstract Map<String, Object> subsystemAttributes();
}
| 3,374 | 47.214286 | 125 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingFeatureDefaultModeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.net.URL;
import java.util.Map;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(TracingFeatureDefaultModeTestCase.TracingSetupServerSetupTask.class)
public class TracingFeatureDefaultModeTestCase {
public static class TracingSetupServerSetupTask extends JaxrsSubsystemServerSetupTask {
@Override
protected Map<String, Object> subsystemAttributes() {
return Map.of("tracing-type", "ALL", "tracing-threshold", "VERBOSE");
}
}
@Deployment
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "tracing.war")
.addClasses(TracingConfigResource.class, TracingApp.class);
}
@ArquillianResource
private URL url;
private String performCall(Client client, String urlPattern) throws Exception {
return client.target(url + urlPattern).request().get().readEntity(String.class);
}
@Test
public void testTracingConfig() throws Exception {
try (Client client = ClientBuilder.newClient()) {
String result = performCall(client, "level");
assertEquals("VERBOSE", result);
String result2 = performCall(client, "type");
assertEquals("ALL", result2);
String result3 = performCall(client, "logger");
assertNotEquals("", result3);
}
}
}
| 3,077 | 36.536585 | 91 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingFeatureOnDemandModeWebXmlTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.tracing.api.RESTEasyTracing;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class TracingFeatureOnDemandModeWebXmlTestCase {
@Deployment
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "tracing.war")
.addClasses(TracingConfigResource.class, TracingApp.class)
.addAsWebInfResource(WebXml.get(
" <context-param>\n" +
" <param-name>resteasy.server.tracing.type</param-name>\n" +
" <param-value>ON_DEMAND</param-value>\n" +
" </context-param>\n"), "web.xml");
}
@ArquillianResource
private URL url;
private jakarta.ws.rs.core.Response performCall(Client client, String urlPattern) {
return client.target(url + urlPattern).request().header(RESTEasyTracing.HEADER_ACCEPT, "").
header(RESTEasyTracing.HEADER_THRESHOLD, ResteasyContextParameters.RESTEASY_TRACING_LEVEL_VERBOSE)
.get();
}
@Test
public void testTracingConfig() {
try (Client client = ClientBuilder.newClient()) {
String result2 = performCall(client, "type").readEntity(String.class);
assertEquals("ON_DEMAND", result2);
String result3 = performCall(client, "logger").getHeaderString(RESTEasyTracing.HEADER_TRACING_PREFIX + "001");
assertNotNull(result3);
}
}
}
| 3,329 | 40.625 | 122 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingFeatureDefaultModeWebXmlTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
public class TracingFeatureDefaultModeWebXmlTestCase {
@Deployment
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "tracing.war")
.addClasses(TracingConfigResource.class, TracingApp.class)
.addAsWebInfResource(WebXml.get(
" <context-param>\n" +
" <param-name>resteasy.server.tracing.type</param-name>\n" +
" <param-value>ALL</param-value>\n" +
" </context-param>\n" +
" <context-param>\n" +
" <param-name>resteasy.server.tracing.threshold</param-name>\n" +
" <param-value>VERBOSE</param-value>\n" +
" </context-param>\n"), "web.xml");
}
@ArquillianResource
private URL url;
private String performCall(Client client, String urlPattern) throws Exception {
return client.target(url + urlPattern).request().get().readEntity(String.class);
}
@Test
public void testTracingConfig() throws Exception {
try (Client client = ClientBuilder.newClient()) {
String result = performCall(client, "level");
assertEquals("VERBOSE", result);
String result2 = performCall(client, "type");
assertEquals("ALL", result2);
String result3 = performCall(client, "logger");
assertNotEquals("", result3);
}
}
}
| 3,374 | 40.158537 | 104 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/tracing/TracingConfigResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.tracing;
import org.jboss.resteasy.tracing.RESTEasyTracingLogger;
import org.jboss.resteasy.tracing.api.RESTEasyTracing;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Configuration;
import jakarta.ws.rs.core.Context;
@Path("/")
public class TracingConfigResource {
@GET
@Path("/type")
public String type(@Context Configuration config) {
return RESTEasyTracingLogger.getTracingConfig(config);
}
@GET
@Path("/level")
public String level(@Context Configuration config) {
return RESTEasyTracingLogger.getTracingThreshold(config);
}
@GET
@Path("/logger")
public String logger(@Context HttpServletRequest request) {
RESTEasyTracingLogger logger = (RESTEasyTracingLogger) request.getAttribute(RESTEasyTracing.PROPERTY_NAME);
if (logger == null) {
return "";
} else {
return RESTEasyTracingLogger.class.getName();
}
}
}
| 2,088 | 33.245902 | 115 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/multipart/JaxrsMultipartProviderTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.multipart;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import jakarta.activation.DataSource;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.util.ByteArrayDataSource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the resteasy multipart provider
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JaxrsMultipartProviderTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrsnoap.war");
war.addPackage(HttpRequest.class.getPackage());
war.addPackage(JaxrsMultipartProviderTestCase.class.getPackage());
war.addAsWebInfResource(WebXml.get("<servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/myjaxrs/*</url-pattern>\n" +
" </servlet-mapping>\n" +
"\n"),"web.xml");
return war;
}
@ArquillianResource
private URL url;
private String performCall(String urlPattern) throws Exception {
return HttpRequest.get(url + urlPattern, 10, TimeUnit.SECONDS);
}
@Test
public void testJaxRsWithNoApplication() throws Exception {
String result = performCall("myjaxrs/form");
DataSource mimeData = new ByteArrayDataSource(result.getBytes(StandardCharsets.UTF_8),"multipart/related");
MimeMultipart mime = new MimeMultipart(mimeData);
String string = (String)mime.getBodyPart(0).getContent();
Assert.assertEquals("Hello", string);
string = (String)mime.getBodyPart(1).getContent();
Assert.assertEquals("World", string);
}
}
| 3,350 | 37.517241 | 115 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/multipart/MultipartResource.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.multipart;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
/**
* @author Stuart Douglas
*/
@Path("/form")
public class MultipartResource {
@GET
@Produces("multipart/related")
public MultipartFormDataOutput get() {
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addPart("Hello", MediaType.TEXT_PLAIN_TYPE);
output.addPart("World", MediaType.TEXT_PLAIN_TYPE);
return output;
}
}
| 1,667 | 35.26087 | 78 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/EJB_Resource1.java
|
/*
* Copyright (C) 2019 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import jakarta.ejb.Stateless;
import jakarta.ws.rs.Path;
@Stateless
@Path("/")
public class EJB_Resource1 {
}
| 1,113 | 36.133333 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/ResteasyScanProvidersTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.jaxrs.cfg.applicationclasses.HelloWorldApplication;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for RESTEasy configuration parameter 'resteasy.scan.providers'
*
* @author Pavel Janousek
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ResteasyScanProvidersTestCase {
private static final String depNameTrue = "dep_true";
private static final String depNameFalse = "dep_false";
private static final String depNameInvalid = "dep_invalid";
private static final String depNameTrueApp = "dep_true_app";
private static final String depNameFalseApp = "dep_false_app";
private static final String depNameInvalidApp = "dep_invalid_app";
@Deployment(name = depNameTrue, managed = true)
public static Archive<?> deploy_true() {
return ShrinkWrap
.create(WebArchive.class, depNameTrue + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class)
.setWebXML(webXmlwithMapping("resteasy.scan.providers", "true"));
}
@Deployment(name = depNameFalse, managed = true)
public static Archive<?> deploy_false() {
return ShrinkWrap
.create(WebArchive.class, depNameFalse + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class)
.setWebXML(webXmlwithMapping("resteasy.scan.providers", "false"));
}
@Deployment(name = depNameInvalid, managed = false)
public static Archive<?> deploy_invalid() {
return ShrinkWrap
.create(WebArchive.class, depNameInvalid + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class)
.setWebXML(webXmlwithMapping("resteasy.scan.providers", "blah"));
}
@Deployment(name = depNameTrueApp, managed = true)
public static Archive<?> deploy_true_app() {
return ShrinkWrap
.create(WebArchive.class, depNameTrueApp + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.providers", "true"));
}
@Deployment(name = depNameFalseApp, managed = true)
public static Archive<?> deploy_false_app() {
return ShrinkWrap
.create(WebArchive.class, depNameFalseApp + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.providers", "false"));
}
@Deployment(name = depNameInvalidApp, managed = false)
public static Archive<?> deploy_invalid_app() {
return ShrinkWrap
.create(WebArchive.class, depNameInvalidApp + ".war")
.addClasses(ResteasyScanProvidersTestCase.class,
HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.providers", "blah"));
}
private static StringAsset webXml(final String paramName,
final String paramValue) {
return WebXml.get(getCfgString(paramName, paramValue));
}
private static StringAsset webXmlwithMapping(final String paramName,
final String paramValue) {
return WebXml
.get("<servlet-mapping>\n"
+ " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n"
+ " <url-pattern>/myjaxrs/*</url-pattern>\n"
+ "</servlet-mapping>\n"
+ getCfgString(paramName, paramValue));
}
private static String getCfgString(final String paramName,
final String paramValue) {
return "<context-param>\n" + " <param-name>" + paramName
+ "</param-name>\n" + " <param-value>" + paramValue
+ "</param-value>\n" + "</context-param>\n" + "\n";
}
@ArquillianResource
private Deployer deployer;
@Test
@OperateOnDeployment(depNameTrue)
public void testDeployTrue(@ArquillianResource URL url) throws Exception {
String result = HttpRequest.get(url.toExternalForm()
+ "myjaxrs/helloworld", 10, TimeUnit.SECONDS);
assertEquals("Hello World!", result);
}
@Test
@OperateOnDeployment(depNameFalse)
public void testDeployFalse(@ArquillianResource URL url) throws Exception {
try {
String result = HttpRequest.get(url.toExternalForm()
+ "myjaxrs/helloworld", 10, TimeUnit.SECONDS);
Assert.assertEquals("Hello World!", result);
} catch (Exception e) {
}
}
//@Ignore("AS7-4254")
@Test
public void testDeployInvalid() throws Exception {
try {
deployer.deploy(depNameInvalid);
Assert.fail("Test should not go here - invalid deployment (invalid value of resteasy.scan.providers)!");
} catch (Exception e) {
}
}
@Test
@OperateOnDeployment(depNameTrueApp)
public void testDeployTrueApp(@ArquillianResource URL url) throws Exception {
String result = HttpRequest.get(url.toExternalForm()
+ "app1/helloworld", 10, TimeUnit.SECONDS);
assertEquals("Hello World!", result);
}
@Test
@OperateOnDeployment(depNameFalseApp)
public void testDeployFalseApp(@ArquillianResource URL url)
throws Exception {
String result = HttpRequest.get(url.toExternalForm()
+ "app1/helloworld", 10, TimeUnit.SECONDS);
Assert.assertEquals("Hello World!", result);
}
@Test
public void testDeployInvalidApp() throws Exception {
try {
deployer.deploy(depNameInvalidApp);
Assert.fail("Test should not go here - invalid deployment (invalid value of resteasy.scan.providers)!");
} catch (Exception e) {
}
}
}
| 8,084 | 39.833333 | 116 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/EJB_Resource2.java
|
/*
* Copyright (C) 2019 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import jakarta.ejb.Stateless;
import jakarta.ws.rs.Path;
@Stateless
@Path("/")
public class EJB_Resource2 {
}
| 1,113 | 36.133333 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/ResteasyAttributeTestCase.java
|
/*
* Copyright (C) 2019 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Invocation.Builder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.jaxrs.JaxrsAttribute;
import org.jboss.as.jaxrs.JaxrsConstants;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.SnapshotRestoreSetupTask;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
import org.jboss.dmr.ValueExpression;
import org.jboss.resteasy.plugins.providers.FileProvider;
import org.jboss.resteasy.plugins.providers.SourceProvider;
import org.jboss.resteasy.plugins.providers.StringTextStar;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for setting RESTEasy context parameters using the Wildfly management model.
*
* @author <a href="[email protected]">Ron Sigal</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(ResteasyAttributeTestCase.AttributeTestCaseDeploymentSetup.class)
public class ResteasyAttributeTestCase {
private static final Map<AttributeDefinition, ModelNode> expectedValues = new HashMap<AttributeDefinition, ModelNode>();
private static final Map<ModelType, Class<?>> modelTypeMap = new HashMap<ModelType, Class<?>>();
private static Client jaxrsClient;
@ArquillianResource
private static URL url;
@ArquillianResource
private ManagementClient client;
static {
modelTypeMap.put(ModelType.BOOLEAN, Boolean.class);
modelTypeMap.put(ModelType.INT, Integer.class);
modelTypeMap.put(ModelType.STRING, String.class);
modelTypeMap.put(ModelType.LIST, String.class);
modelTypeMap.put(ModelType.OBJECT, String.class);
}
private static final ModelNode ADDRESS = Operations.createAddress("subsystem", "jaxrs");
private static final String OUTCOME = "outcome";
private static final String SUCCESS = "success";
private static final String FAILED = "failed";
private static final String RESTEASY_MEDIA_TYPE_PARAM_MAPPING_CONTEXT_VALUE = "resteasy.media.type.param.mapping.context.value";
private static final ModelNode VALUE_EXPRESSION_BOOLEAN_TRUE = new ModelNode(new ValueExpression("${rest.test.dummy:true}"));
private static final ModelNode VALUE_EXPRESSION_BOOLEAN_FALSE = new ModelNode(new ValueExpression("${rest.test.dummy:false}"));
private static final ModelNode VALUE_EXPRESSION_INT = new ModelNode(new ValueExpression("${rest.test.dummy:1717}"));
private static final ModelNode VALUE_EXPRESSION_STRING = new ModelNode(new ValueExpression("${rest.test.dummy:xyz}"));
private static final ModelNode VALUE_EXPRESSION_FILENAME_1 = new ModelNode(new ValueExpression("${rest.test.dummy:" + FileProvider.class.getName() + "}"));
private static final ModelNode VALUE_EXPRESSION_FILENAME_2 = new ModelNode(new ValueExpression("${rest.test.dummy:" + SourceProvider.class.getName() + "}"));
private static final ModelNode VALUE_EXPRESSION_SPANISH = new ModelNode(new ValueExpression("${rest.test.dummy:es-es}"));
private static final ModelNode VALUE_EXPRESSION_APPLICATION_UNUSUAL = new ModelNode(new ValueExpression("${rest.test.dummy:application/unusual}"));
private static final ModelNode VALUE_EXPRESSION_RESOURCE = new ModelNode(new ValueExpression("${rest.test.dummy:java:global/jaxrsnoap/" + EJB_Resource1.class.getSimpleName() + "}"));
private static final ModelNode VALUE_EXPRESSION_PROVIDER = new ModelNode(new ValueExpression("${rest.test.dummy:" + StringTextStar.class.getName() + "}"));
static class AttributeTestCaseDeploymentSetup extends SnapshotRestoreSetupTask {
@Override
protected void doSetup(final ManagementClient client, final String containerId) throws Exception {
setAttributeValues(client.getControllerClient());
ServerReload.reloadIfRequired(client);
}
}
/**
* Define the deployment
*
* @return The deployment archive
*/
@Deployment
public static Archive<?> createDeployment() throws Exception {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrsnoap.war");
war.addClasses(ResteasyAttributeResource.class);
war.addClasses(EJB_Resource1.class, EJB_Resource2.class);
// Put "resteasy.media.type.param.mapping" in web.xml to verify that it overrides value set in Wildfly management model.
war.addAsWebInfResource(WebXml.get(
"<context-param>\n" +
" <param-name>resteasy.media.type.param.mapping</param-name>\n" +
" <param-value>" + RESTEASY_MEDIA_TYPE_PARAM_MAPPING_CONTEXT_VALUE + "</param-value>\n" +
"</context-param>" +
"<servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/myjaxrs/*</url-pattern>\n" +
" </servlet-mapping>\n" +
"\n"), "web.xml");
return war;
}
@BeforeClass
public static void beforeClass() throws IOException {
jaxrsClient = ClientBuilder.newClient();
}
@AfterClass
public static void afterClass() throws IOException {
jaxrsClient.close();
}
//////////////////////////////////////////////////////////////////////////////////////
///////////////////// Configuration methods ////////////////////
//////////////////////////////////////////////////////////////////////////////////////
/*
* Set attributes to testable values.
*
* Note that StringTextStar is added to 'resteasy.providers" to compensate for the fact that
* "resteasy.use.builtin.providers" is set to "false".
*/
static void setAttributeValues(final ModelControllerClient client) throws IOException {
setAttributeValue(client, JaxrsAttribute.JAXRS_2_0_REQUEST_MATCHING, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_ADD_CHARSET, VALUE_EXPRESSION_BOOLEAN_FALSE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_BUFFER_EXCEPTION_ENTITY, VALUE_EXPRESSION_BOOLEAN_FALSE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_DISABLE_HTML_SANITIZER, VALUE_EXPRESSION_BOOLEAN_TRUE);
ModelNode list = new ModelNode().setEmptyList();
list.add(VALUE_EXPRESSION_FILENAME_1);
list.add(VALUE_EXPRESSION_FILENAME_2);
setAttributeValue(client, JaxrsAttribute.RESTEASY_DISABLE_PROVIDERS, list);
list.clear();
setAttributeValue(client, JaxrsAttribute.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS, VALUE_EXPRESSION_BOOLEAN_FALSE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE, VALUE_EXPRESSION_BOOLEAN_FALSE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_GZIP_MAX_INPUT, VALUE_EXPRESSION_INT);
list.add(VALUE_EXPRESSION_RESOURCE);
list.add("java:global/jaxrsnoap/" + EJB_Resource2.class.getSimpleName());
setAttributeValue(client, JaxrsAttribute.RESTEASY_JNDI_RESOURCES, list);
list.clear();
ModelNode map = new ModelNode();
map.add(new Property("en", new ModelNode("en-US")));
map.add(new Property("es", VALUE_EXPRESSION_SPANISH));
map.add(new Property("fr", new ModelNode("fr")));
setAttributeValue(client, JaxrsAttribute.RESTEASY_LANGUAGE_MAPPINGS, map);
map.clear();
map.add(new Property("unusual", VALUE_EXPRESSION_APPLICATION_UNUSUAL));
map.add(new Property("xml", new ModelNode("application/xml")));
setAttributeValue(client, JaxrsAttribute.RESTEASY_MEDIA_TYPE_MAPPINGS, map);
map.clear();
setAttributeValue(client, JaxrsAttribute.RESTEASY_PREFER_JACKSON_OVER_JSONB, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_MEDIA_TYPE_PARAM_MAPPING, VALUE_EXPRESSION_STRING);
list.add(VALUE_EXPRESSION_PROVIDER);
setAttributeValue(client, JaxrsAttribute.RESTEASY_PROVIDERS, list);
list.clear();
setAttributeValue(client, JaxrsAttribute.RESTEASY_RFC7232_PRECONDITIONS, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_ROLE_BASED_SECURITY, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_SECURE_RANDOM_MAX_USE, VALUE_EXPRESSION_INT);
setAttributeValue(client, JaxrsAttribute.RESTEASY_USE_BUILTIN_PROVIDERS, VALUE_EXPRESSION_BOOLEAN_FALSE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_USE_CONTAINER_FORM_PARAMS, VALUE_EXPRESSION_BOOLEAN_TRUE);
setAttributeValue(client, JaxrsAttribute.RESTEASY_WIDER_REQUEST_MATCHING, VALUE_EXPRESSION_BOOLEAN_TRUE);
}
static void setAttributeValue(final ModelControllerClient client, AttributeDefinition attribute, ModelNode value) throws IOException {
ModelNode expectedValue = null;
ModelNode resolvedValue = value.resolve();
switch (attribute.getType()) {
case LIST:
expectedValue = textifyList(resolvedValue);
break;
case OBJECT:
expectedValue = textifyMap(resolvedValue);
break;
default:
expectedValue = resolvedValue;
break;
}
expectedValues.put(attribute, expectedValue);
ModelNode op = Operations.createWriteAttributeOperation(ADDRESS, attribute.getName(), value);
ModelNode result = client.execute(op);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
}
private static ModelNode textifyList(ModelNode modelNode) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (ModelNode value : modelNode.asList()) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(value.asString());
}
return new ModelNode(sb.toString());
}
private static ModelNode textifyMap(ModelNode modelNode) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : modelNode.asObject().keys()) {
ModelNode value = modelNode.asObject().get(key);
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(key + ":" + value.asString());
}
return new ModelNode(sb.toString());
}
//////////////////////////////////////////////////////////////////////////////////////
///////////////////// Test methods ////////////////////
//////////////////////////////////////////////////////////////////////////////////////
/**
* Verify that all values are passed correctly to RESTEasy.
*/
@Test
public void testAttributes() throws IOException {
WebTarget target = jaxrsClient.target(url.toString() + "myjaxrs/attribute");
for (AttributeDefinition attribute : JaxrsAttribute.ATTRIBUTES) {
// Ignore these attributes as they are not set in the context as the attributes are not public. These are
// also tested elsewhere
if ("tracing-type".equals(attribute.getName()) || "tracing-threshold".equals(attribute.getName())) {
continue;
}
testAttribute(target, attribute);
}
}
void testAttribute(WebTarget target, AttributeDefinition attribute) {
String resteasyName = attribute.getName();
if (resteasyName.equals(JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB)) {
resteasyName = ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB;
} else {
resteasyName = changeHyphensToDots(resteasyName);
}
Response response = target.path(resteasyName).request().get();
Assert.assertEquals("Failed to get value for " + resteasyName,200, response.getStatus());
Object result = response.readEntity(modelTypeMap.get(attribute.getType()));
final String msg = "Invalid value found for " + resteasyName;
switch (attribute.getType()) {
case BOOLEAN:
Assert.assertEquals(msg, expectedValues.get(attribute).asBoolean(), result);
return;
case INT:
Assert.assertEquals(msg, expectedValues.get(attribute).asInt(), result);
return;
case STRING:
Assert.assertEquals(msg, expectedValues.get(attribute).asString(), result);
return;
case LIST:
Assert.assertEquals(msg, expectedValues.get(attribute).asString(), result);
return;
case OBJECT:
Assert.assertEquals(msg, expectedValues.get(attribute).asString(), result);
return;
default:
Assert.fail("Unexpected ModelNode type for " + resteasyName);
}
}
String changeHyphensToDots(String attribute) {
return attribute.replace("-", ".");
}
/**
* Verify that syntactically incorrect values get kicked out.
*/
@Test
public void testBadSyntax() throws Exception {
for (AttributeDefinition attribute : JaxrsAttribute.ATTRIBUTES) {
// Strings need to be ignored
if (attribute.getType() == ModelType.STRING) {
continue;
}
ModelNode op = Operations.createWriteAttributeOperation(ADDRESS, attribute.getName(), mangleAttribute(attribute));
ModelNode result = client.getControllerClient().execute(op);
Assert.assertEquals(FAILED, result.get(OUTCOME).asString());
}
}
static String mangleAttribute(AttributeDefinition attribute) {
switch (attribute.getType()) {
case BOOLEAN:
return "abc";
case INT:
return "def";
case LIST:
return "ghi";
case OBJECT:
return "jkl";
default:
throw new RuntimeException("Unexpected ModelNode type: " + attribute.getType());
}
}
/**
* Verify that updating parameters doesn't affect existing deployments.
*/
@Test
public void testExistingDeploymentsUnchanged() throws IOException {
// Get current value of "resteasy.add.charset".
WebTarget base = jaxrsClient.target(url.toString() + "myjaxrs/attribute");
Builder builder = base.path(changeHyphensToDots(JaxrsAttribute.RESTEASY_ADD_CHARSET.getName())).request();
Response response = builder.get();
Assert.assertEquals(200, response.getStatus());
boolean oldValue = response.readEntity(boolean.class);
// Update "resteasy.add.charset" value to a new value.
ModelNode op = Operations.createWriteAttributeOperation(ADDRESS, JaxrsAttribute.RESTEASY_ADD_CHARSET.getName(), !oldValue);
ModelNode result = client.getControllerClient().execute(op);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
// Verify that value of "resteasy.add.charset" hasn't changed in existing deployment.
response = builder.get();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(oldValue, response.readEntity(boolean.class));
// Reset "resteasy.add.charset" to original value.
op = Operations.createWriteAttributeOperation(ADDRESS, JaxrsAttribute.RESTEASY_ADD_CHARSET.getName(), oldValue);
result = client.getControllerClient().execute(op);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
}
}
| 17,966 | 45.187661 | 186 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/ResteasyScanResourcesTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.jaxrs.cfg.applicationclasses.HelloWorldApplication;
import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for RESTEasy configuration parameter 'resteasy.scan.resources'
*
* @author Pavel Janousek
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ResteasyScanResourcesTestCase {
private static final String depNameTrue = "dep_true";
private static final String depNameFalse = "dep_false";
private static final String depNameInvalid = "dep_invalid";
private static final String depNameTrueApp = "dep_true_app";
private static final String depNameFalseApp = "dep_false_app";
private static final String depNameInvalidApp = "dep_invalid_app";
@Deployment(name = depNameTrue, managed = true)
public static Archive<?> deploy_true() {
return ShrinkWrap.create(WebArchive.class, depNameTrue + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class)
.setWebXML(webXmlWithMapping("resteasy.scan.resources", "true"));
}
@Deployment(name = depNameFalse, managed = true)
public static Archive<?> deploy_false() {
return ShrinkWrap.create(WebArchive.class, depNameFalse + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class)
.setWebXML(webXmlWithMapping("resteasy.scan.resources", "false"));
}
@Deployment(name = depNameInvalid, managed = false)
public static Archive<?> deploy_invalid() {
return ShrinkWrap.create(WebArchive.class, depNameInvalid + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class)
.setWebXML(webXmlWithMapping("resteasy.scan.resources", "blah"));
}
@Deployment(name = depNameTrueApp, managed = true)
public static Archive<?> deploy_true_app() {
return ShrinkWrap.create(WebArchive.class, depNameTrueApp + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.resources", "true"));
}
@Deployment(name = depNameFalseApp, managed = true)
public static Archive<?> deploy_false_app() {
return ShrinkWrap.create(WebArchive.class, depNameFalseApp + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.resources", "false"));
}
@Deployment(name = depNameInvalidApp, managed = false)
public static Archive<?> deploy_invalid_app() {
return ShrinkWrap.create(WebArchive.class, depNameInvalidApp + ".war")
.addClasses(ResteasyScanResourcesTestCase.class, HelloWorldResource.class, HelloWorldApplication.class)
.setWebXML(webXml("resteasy.scan.resources", "blah"));
}
private static StringAsset webXml(final String paramName, final String paramValue) {
return WebXml.get(getCfgString(paramName, paramValue));
}
private static StringAsset webXmlWithMapping(final String paramName, final String paramValue) {
return WebXml.get("<servlet-mapping>\n" + " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n"
+ " <url-pattern>/myjaxrs/*</url-pattern>\n" + "</servlet-mapping>\n"
+ getCfgString(paramName, paramValue));
}
private static String getCfgString(final String paramName, final String paramValue) {
return "<context-param>\n" + " <param-name>" + paramName + "</param-name>\n" + " <param-value>"
+ paramValue + "</param-value>\n" + "</context-param>\n" + "\n";
}
@ArquillianResource
private Deployer deployer;
@Test
@OperateOnDeployment(depNameTrue)
public void testDeployTrue(@ArquillianResource URL url) throws Exception {
String result = HttpRequest.get(url.toExternalForm() + "myjaxrs/helloworld", 10, TimeUnit.SECONDS);
assertEquals("Hello World!", result);
}
@Test
@OperateOnDeployment(depNameFalse)
public void testDeployFalse(@ArquillianResource URL url) throws Exception {
try {
@SuppressWarnings("unused")
String result = HttpRequest.get(url.toExternalForm() + "myjaxrs/helloworld", 10, TimeUnit.SECONDS);
Assert.fail("Scan of Resources is disabled so we should not pass to there - HTTP 404 must occur!");
} catch (Exception e) {
Assert.assertTrue(e.toString().contains("HTTP Status 404"));
}
}
@Test
public void testDeployInvalid() throws Exception {
try {
deployer.deploy(depNameInvalid);
Assert.fail("Test should not go here - invalid deployment (invalid value of resteasy.scan.resources)!");
} catch (Exception e) {
}
}
@Test
@OperateOnDeployment(depNameTrueApp)
public void testDeployTrueApp(@ArquillianResource URL url) throws Exception {
String result = HttpRequest.get(url.toExternalForm() + "app1/helloworld", 10, TimeUnit.SECONDS);
assertEquals("Hello World!", result);
}
@Test
@OperateOnDeployment(depNameFalseApp)
public void testDeployFalseApp(@ArquillianResource URL url) throws Exception {
try {
@SuppressWarnings("unused")
String result = HttpRequest.get(url.toExternalForm() + "app1/helloworld", 10, TimeUnit.SECONDS);
Assert.fail("Scan of Resources is disabled so we should not pass to there - HTTP 404 must occur!");
} catch (Exception e) {
Assert.assertTrue(e.toString().contains("HTTP Status 404"));
}
}
@Test
public void testDeployInvalidApp() throws Exception {
try {
deployer.deploy(depNameInvalidApp);
Assert.fail("Test should not go here - invalid deployment (invalid value of resteasy.scan.resources)!");
} catch (Exception e) {
}
}
}
| 7,907 | 43.426966 | 121 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/ResteasyAttributeResource.java
|
/*
* Copyright (C) 2019 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import javax.naming.NamingException;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.UriInfo;
@Path("attribute")
public class ResteasyAttributeResource {
@Path("{param}")
@GET
@Produces("text/plain")
public String getParameter(@PathParam("param") String param, @Context UriInfo info, @Context ServletContext context) throws NamingException {
return context.getInitParameter(param);
}
}
| 1,586 | 36.785714 | 145 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/HelloWorldResource.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.cfg;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
@Path("helloworld")
@Produces({"text/plain"})
public class HelloWorldResource {
@GET
public String getMessage() {
return "Hello World!";
}
}
| 1,312 | 35.472222 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/applicationclasses/HelloWorldApplication2.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.cfg.applicationclasses;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Application with no path
*
* @author Stuart Douglas
*/
@ApplicationPath("app2")
public class HelloWorldApplication2 extends Application {
}
| 1,313 | 36.542857 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/cfg/applicationclasses/HelloWorldApplication.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jaxrs.cfg.applicationclasses;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Application with no path
*
* @author Stuart Douglas
*/
@ApplicationPath("app1")
public class HelloWorldApplication extends Application {
}
| 1,312 | 36.514286 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/BeanValidationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation;
import jakarta.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.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests Jakarta Bean Validation within a Jakarta EE component
* <p/>
* User: Jaikiran Pai
*/
@RunWith(Arquillian.class)
public class BeanValidationTestCase {
@EJB(mappedName = "java:module/StatelessBean")
private StatelessBean slsb;
@Deployment
public static JavaArchive getDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "bean-validation-test.jar");
jar.addClass(StatelessBean.class);
return jar;
}
/**
* Test that {@link jakarta.validation.Validation#buildDefaultValidatorFactory()} works fine within an EJB
*/
@Test
public void testBuildDefaultValidatorFactory() {
this.slsb.buildDefaultValidatorFactory();
}
/**
* Test that {@link jakarta.validation.Validator} and {@link jakarta.validation.ValidatorFactory} are injected in a
* EJB
*/
@Test
public void testValidatorInjection() {
Assert.assertTrue("Validator wasn't injected in EJB", this.slsb.isValidatorInjected());
Assert.assertTrue("ValidatorFactory wasn't injected in EJB", this.slsb.isValidatorFactoryInjected());
}
/**
* Tests that {@link jakarta.validation.ValidatorFactory#getValidator()} returns a validator
*/
@Test
public void testGetValidatorFromValidatorFactory() {
Assert.assertNotNull("Validator from ValidatorFactory was null", this.slsb.getValidatorFromValidatorFactory());
}
}
| 2,837 | 34.475 | 119 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/StatelessBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
/**
* User: Jaikiran Pai
*/
@Stateless
public class StatelessBean {
@Resource
private Validator validator;
@Resource
private ValidatorFactory validatorFactory;
public void buildDefaultValidatorFactory() {
Validation.buildDefaultValidatorFactory();
}
public boolean isValidatorInjected() {
return this.validator != null;
}
public boolean isValidatorFactoryInjected() {
return this.validatorFactory != null;
}
public Validator getValidatorFromValidatorFactory() {
return this.validatorFactory.getValidator();
}
}
| 1,864 | 30.610169 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/BeanValidationEE8TestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.valueextraction.ExtractedValue;
import jakarta.validation.valueextraction.UnwrapByDefault;
import jakarta.validation.valueextraction.ValueExtractor;
import org.hibernate.validator.HibernateValidatorPermission;
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.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* A test validating the Jakarta Bean Validation 2.0 support.
*
* @author <a href="mailto:[email protected]">Guillaume Smet</a>
*/
@RunWith(Arquillian.class)
public class BeanValidationEE8TestCase {
@Deployment
public static WebArchive deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "beanvalidation-ee8-test-case.war");
war.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
), "permissions.xml");
return war;
}
@Test
public void testMapKeySupport() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<MapKeyBean>> violations = validator.validate(MapKeyBean.valid());
Assert.assertTrue(violations.isEmpty());
violations = validator.validate(MapKeyBean.invalid());
Assert.assertEquals(1, violations.size());
ConstraintViolation<MapKeyBean> violation = violations.iterator().next();
Assert.assertEquals(NotNull.class, violation.getConstraintDescriptor().getAnnotation().annotationType());
}
@Test
public void testValueExtractor() {
Validator validator = Validation.byDefaultProvider().configure()
.addValueExtractor(new ContainerValueExtractor())
.buildValidatorFactory()
.getValidator();
Set<ConstraintViolation<ContainerBean>> violations = validator.validate(ContainerBean.valid());
Assert.assertTrue(violations.isEmpty());
violations = validator.validate(ContainerBean.invalid());
Assert.assertEquals(1, violations.size());
ConstraintViolation<ContainerBean> violation = violations.iterator().next();
Assert.assertEquals(NotNull.class, violation.getConstraintDescriptor().getAnnotation().annotationType());
}
private static class MapKeyBean {
private Map<@NotNull String, String> mapProperty;
private static MapKeyBean valid() {
MapKeyBean validatedBean = new MapKeyBean();
validatedBean.mapProperty = new HashMap<>();
validatedBean.mapProperty.put("Paul Auster", "4 3 2 1");
return validatedBean;
}
private static MapKeyBean invalid() {
MapKeyBean validatedBean = new MapKeyBean();
validatedBean.mapProperty = new HashMap<>();
validatedBean.mapProperty.put(null, "4 3 2 1");
return validatedBean;
}
}
private static class ContainerBean {
@NotNull
private Container containerProperty;
private static ContainerBean valid() {
ContainerBean validatedBean = new ContainerBean();
validatedBean.containerProperty = new Container("value");
return validatedBean;
}
private static ContainerBean invalid() {
ContainerBean validatedBean = new ContainerBean();
validatedBean.containerProperty = new Container(null);
return validatedBean;
}
}
private static class Container {
private String value;
private Container(String value) {
this.value = value;
}
private String getValue() {
return value;
}
}
@UnwrapByDefault
private class ContainerValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Container> {
@Override
public void extractValues(Container originalValue, ValueReceiver receiver) {
receiver.value(null, originalValue.getValue());
}
}
}
| 5,721 | 35.21519 | 117 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/UserBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
/**
* @author Madhumita Sadhukhan
*/
public class UserBean {
@NotEmpty
private String firstName;
@NotBlank
private String lastName;
@Email
private String email;
public UserBean(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@NotBlank(message = "Please get a valid address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
| 2,274 | 25.764706 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/BootStrapValidationTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Set;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.HibernateValidatorPermission;
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.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that bootstrapping works correctly for Hibernate Validator.
*
* @author Madhumita Sadhukhan
*/
@RunWith(Arquillian.class)
public class BootStrapValidationTestCase {
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "testbootstrapvalidation.war");
war.addPackage(BootStrapValidationTestCase.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
), "permissions.xml");
return war;
}
@Test
public void testBootstrapAsServiceDefault() {
HibernateValidatorFactory factory = (HibernateValidatorFactory) Validation.buildDefaultValidatorFactory();
assertNotNull(factory);
}
@Test
public void testCustomConstraintValidatorFactory() {
HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
assertNotNull(configuration);
ValidatorFactory factory = configuration.buildValidatorFactory();
Validator validator = factory.getValidator();
Employee emp = new Employee();
// create employee
emp.setEmpId("M1234");
emp.setFirstName("MADHUMITA");
emp.setLastName("SADHUKHAN");
emp.setEmail("[email protected]");
Set<ConstraintViolation<Employee>> constraintViolations = validator.validate(emp);
assertEquals("Wrong number of constraints", constraintViolations.size(), 1);
assertEquals("Created by default factory", constraintViolations.iterator().next().getMessage());
// get a new factory using a custom configuration
configuration.constraintValidatorFactory(new CustomConstraintValidatorFactory(configuration
.getDefaultConstraintValidatorFactory()));
factory = configuration.buildValidatorFactory();
validator = factory.getValidator();
constraintViolations = validator.validate(emp);
assertEquals("Wrong number of constraints", constraintViolations.size(), 1);
assertEquals("Created by custom factory", constraintViolations.iterator().next().getMessage());
}
/**
* A custom constraint validator factory.
*/
private static class CustomConstraintValidatorFactory implements ConstraintValidatorFactory {
private final ConstraintValidatorFactory delegate;
CustomConstraintValidatorFactory(ConstraintValidatorFactory delegate) {
this.delegate = delegate;
}
@Override
@SuppressWarnings("unchecked")
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
if (key == CustomConstraint.Validator.class) {
return (T) new CustomConstraint.Validator("Created by custom factory");
}
return delegate.getInstance(key);
}
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
delegate.releaseInstance(instance);
}
}
}
| 5,184 | 39.193798 | 116 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/Employee.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import org.hibernate.validator.constraints.Email;
/**
* @author Madhumita Sadhukhan
*/
public class Employee {
@CustomConstraint
private String empId;
private String firstName;
private String lastName;
@Email
private String email;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 1,941 | 25.60274 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/CarGroupSequenceProvider.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;
/**
* @author Madhumita Sadhukhan
*/
public class CarGroupSequenceProvider implements DefaultGroupSequenceProvider<Car> {
private static final List<Class<?>> DEFAULT_SEQUENCE = Arrays.asList(Car.class, CarChecks.class);
@Override
public List<Class<?>> getValidationGroups(Car car) {
if (car == null || !car.inspectionCompleted()) {
return DEFAULT_SEQUENCE;
} else {
List<Class<?>> finalInspectionSequence = new ArrayList<>(3);
finalInspectionSequence.addAll(DEFAULT_SEQUENCE);
finalInspectionSequence.add(FinalInspection.class);
return finalInspectionSequence;
}
}
}
| 1,912 | 37.26 | 101 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/FinalInspection.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
/**
* @author Madhumita Sadhukhan
*/
public interface FinalInspection {
}
| 1,168 | 37.966667 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/Car.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Min;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.group.GroupSequenceProvider;
/**
* @author Madhumita Sadhukhan
*/
@GroupSequenceProvider(CarGroupSequenceProvider.class)
public class Car {
private String model;
@NotBlank
private String number;
@NotEmpty
@Valid
private List<UserBean> passengers = new ArrayList<UserBean>();
@AssertTrue(message = "The rent for the Car has to be paid before being driven", groups = FinalInspection.class)
public boolean hasBeenPaid;
@Min(value = 4, message = "Car should have minimum 4 seats", groups = FinalInspection.class)
public int seats;
@Valid
private Driver driver;
@AssertTrue(message = "The Car has to pass the fuel test and inspection test before being driven", groups = CarChecks.class)
public boolean passedvehicleInspection;
public Car(String number, List<UserBean> passengers) {
this.number = number;
this.passengers = passengers;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public List<UserBean> getPassengers() {
return passengers;
}
public void setPassengers(List<UserBean> passengers) {
this.passengers = passengers;
}
public boolean inspectionCompleted() {
return passedvehicleInspection;
}
public void setPassedVehicleInspection(boolean passedvehicleInspection) {
this.passedvehicleInspection = passedvehicleInspection;
}
public void setHasBeenPaid(boolean hasBeenPaid) {
this.hasBeenPaid = hasBeenPaid;
}
public Driver getDriver() {
return driver;
}
public void setDriver(Driver driver) {
this.driver = driver;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
}
| 3,407 | 26.707317 | 128 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/ExpressionLanguageTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.HibernateValidatorPermission;
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.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that Unified EL expressions can be used in Bean Violation messages as supported since BV 1.1.
*
* @author Gunnar Morling
*/
@RunWith(Arquillian.class)
public class ExpressionLanguageTestCase {
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "expression-language-validation.war");
war.addClass(ExpressionLanguageTestCase.class);
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
), "permissions.xml");
return war;
}
@Test
public void testValidationUsingExpressionLanguage() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<TestBean>> violations = validator.validate(new TestBean());
assertEquals(1, violations.size());
assertEquals("'Bob' is too short, it should at least be 5 characters long.", violations.iterator().next().getMessage());
}
private static class TestBean {
@Size(min = 5, message = "'${validatedValue}' is too short, it should at least be {min} characters long.")
private final String name = "Bob";
}
}
| 3,007 | 38.578947 | 128 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/ConstraintValidationTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidatorPermission;
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.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that hibernate validator works correctly for WAR(Web Applications)
*
* @author Madhumita Sadhukhan
*/
@RunWith(Arquillian.class)
public class ConstraintValidationTestCase {
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "testconstraintvalidation.war");
war.addPackage(ConstraintValidationTestCase.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
), "permissions.xml");
return war;
}
@Test
public void testConstraintValidation() throws NamingException {
Validator validator = (Validator) new InitialContext().lookup("java:comp/Validator");
UserBean user1 = new UserBean("MADHUMITA", "");
user1.setEmail("madhumita_gmail");
user1.setAddress("");
final Set<ConstraintViolation<UserBean>> result = validator.validate(user1);
Iterator<ConstraintViolation<UserBean>> it = result.iterator();
String message = "";
while (it.hasNext()) {
ConstraintViolation<UserBean> cts = it.next();
String mess = cts.getMessage();
if (mess.contains("Please get a valid address")) { message = mess; }
}
assertEquals(3, result.size());
assertTrue(message.contains("Please get a valid address"));
}
@Test
public void testObjectGraphValidation() throws NamingException {
Validator validator = (Validator) new InitialContext().lookup("java:comp/Validator");
// create first passenger
UserBean user1 = new UserBean("MADHUMITA", "SADHUKHAN");
user1.setEmail("[email protected]");
user1.setAddress("REDHAT Brno");
// create second passenger
UserBean user2 = new UserBean("Mickey", "Mouse");
user2.setAddress("");
List<UserBean> passengers = new ArrayList<UserBean>();
passengers.add(user1);
passengers.add(user2);
// Create a Car
Car car = new Car("CET5678", passengers);
car.setModel("SKODA Octavia");
final Set<ConstraintViolation<Car>> errorresult = validator.validate(car);
Iterator<ConstraintViolation<Car>> it1 = errorresult.iterator();
String message = "";
while (it1.hasNext()) {
ConstraintViolation<Car> cts = it1.next();
String mess = cts.getMessage();
if (mess.contains("Please get a valid address")) { message = mess; }
}
assertEquals(2, errorresult.size());
assertTrue(message.contains("Please get a valid address"));
}
}
| 4,568 | 36.146341 | 99 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/CarChecks.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
/**
* @author Madhumita Sadhukhan
*/
public interface CarChecks {
}
| 1,163 | 36.548387 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/Driver.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Min;
//import org.hibernate.validator.group.*;
/**
* @author Madhumita Sadhukhan
*/
// @GroupSequenceProvider(CarGroupSequenceProvider.class)
public class Driver extends UserBean {
@Min(value = 18, message = "You have to be 18 to drive a car", groups = DriverChecks.class)
private int age;
@AssertTrue(message = "You have to pass the driving test and own a valid Driving License", groups = DriverChecks.class)
public boolean hasDrivingLicense;
public Driver(String firstName, String lastName) {
super(firstName, lastName);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean hasValidDrivingLicense() {
return hasDrivingLicense;
}
public void setHasValidDrivingLicense(boolean hasValidDrivingLicense) {
this.hasDrivingLicense = hasValidDrivingLicense;
}
}
| 2,091 | 32.741935 | 123 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/MessageInterpolationValidationTestCase.java
|
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Locale;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.MessageInterpolator;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.HibernateValidatorPermission;
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.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that message interpolation works correctly for Hibernate Validator.
*
* @author Madhumita Sadhukhan
*/
@RunWith(Arquillian.class)
public class MessageInterpolationValidationTestCase {
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "testmessageinterpolationvalidation.war");
war.addPackage(MessageInterpolationValidationTestCase.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
), "permissions.xml");
return war;
}
@Test
public void testCustomMessageInterpolation() {
HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
assertNotNull(configuration);
final MessageInterpolator messageInterpolator = new CustomMessageInterpolator();
configuration.messageInterpolator(messageInterpolator);
ValidatorFactory factory = configuration.buildValidatorFactory();
Validator validator = factory.getValidator();
// create employee
Employee emp = new Employee();
emp.setEmail("MADHUMITA");
Set<ConstraintViolation<Employee>> constraintViolations = validator.validate(emp);
assertEquals("Wrong number of constraints", constraintViolations.size(), 1);
assertEquals(CustomMessageInterpolator.MESSAGE, constraintViolations.iterator().next().getMessage());
}
private static class CustomMessageInterpolator implements MessageInterpolator {
public static final String MESSAGE = "Message created by custom interpolator";
@Override
public String interpolate(String messageTemplate, Context context) {
return MESSAGE;
}
@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
return MESSAGE;
}
}
}
| 2,979 | 35.790123 | 116 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/DriverChecks.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
/**
* @author Madhumita Sadhukhan
*/
public interface DriverChecks {
}
| 1,166 | 36.645161 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/CustomConstraint.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
/**
* A custom constraint which expects a custom constraint validator factory.
*
* @author Gunnar Morling
*/
@Constraint(validatedBy = CustomConstraint.Validator.class)
@Documented
@Target(FIELD)
@Retention(RUNTIME)
public @interface CustomConstraint {
String message() default "my custom constraint";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
public class Validator implements ConstraintValidator<CustomConstraint, String> {
private final String message;
public Validator() {
this.message = "Created by default factory";
}
public Validator(String message) {
this.message = message;
}
@Override
public void initialize(CustomConstraint parameters) {
}
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintValidatorContext) {
if (object == null) {
return true;
}
constraintValidatorContext.disableDefaultConstraintViolation();
constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
return false;
}
}
}
| 2,516 | 32.118421 | 110 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/validator/GroupandGroupSequenceValidationTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.validator;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidatorPermission;
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.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests GroupSequenceProvider feature in Hibernate Validator.
*
* @author Madhumita Sadhukhan
*/
@RunWith(Arquillian.class)
public class GroupandGroupSequenceValidationTestCase {
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "testgroupvalidation.war");
war.addPackage(GroupandGroupSequenceValidationTestCase.class.getPackage());
war.addAsManifestResource(createPermissionsXmlAsset(
HibernateValidatorPermission.ACCESS_PRIVATE_MEMBERS
),"permissions.xml");
return war;
}
@Test
public void testGroupValidation() throws NamingException {
Validator validator = (Validator) new InitialContext().lookup("java:comp/Validator");
// create first passenger
UserBean user1 = new UserBean("MADHUMITA", "SADHUKHAN");
user1.setEmail("[email protected]");
user1.setAddress("REDHAT Brno");
// create second passenger
UserBean user2 = new UserBean("Mickey", "Mouse");
user2.setEmail("[email protected]");
user2.setAddress("DISNEY CA USA");
List<UserBean> passengers = new ArrayList<UserBean>();
passengers.add(user1);
passengers.add(user2);
// Create a Car
Car car = new Car("CET5678", passengers);
car.setModel("SKODA Octavia");
// validate Car with default group as per GroupSequenceProvider
Set<ConstraintViolation<Car>> result = validator.validate(car);
assertEquals(1, result.size());
assertEquals("The Car has to pass the fuel test and inspection test before being driven", result.iterator().next()
.getMessage());
Driver driver = new Driver("Sebastian", "Vettel");
driver.setAge(25);
driver.setAddress("ABC");
result = validator.validate(car);
assertEquals(1, result.size());
assertEquals("The Car has to pass the fuel test and inspection test before being driven", result.iterator().next()
.getMessage());
car.setPassedVehicleInspection(true);
result = validator.validate(car);
// New group set in defaultsequence for Car as per CarGroupSequenceProvider should be implemented now
assertEquals(2, result.size());
car.setDriver(driver);
// implementing validation for group associated with associated objects of Car(in this case Driver)
Set<ConstraintViolation<Car>> driverResult = validator.validate(car, DriverChecks.class);
assertEquals(1, driverResult.size());
driver.setHasValidDrivingLicense(true);
assertEquals(0, validator.validate(car, DriverChecks.class).size());
car.setSeats(5);
car.setHasBeenPaid(true);
assertEquals(0, validator.validate(car).size());
}
}
| 4,663 | 38.193277 | 122 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/scriptassert/ScriptAssertBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.scriptassert;
import org.hibernate.validator.constraints.ScriptAssert;
/**
*
* @author Stuart Douglas
*/
@ScriptAssert(lang = "javascript", script = "false")
public class ScriptAssertBean {
}
| 1,276 | 37.69697 | 76 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/beanvalidation/hibernate/scriptassert/ScriptAssertTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.beanvalidation.hibernate.scriptassert;
import java.sql.SQLException;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* AS7-1110
* <p/>
* Tests that hibernate validator @ScriptAssert works correctly
* <p/>
* This is a non-standard extension provided by hibernate validator
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class ScriptAssertTestCase {
private static final Logger logger = Logger.getLogger(ScriptAssertTestCase.class);
@BeforeClass
public static void beforeClass() {
// https://issues.redhat.com/browse/WFLY-15719
AssumeTestGroupUtil.assumeJDKVersionBefore(15);
}
@Before
public void runOnlyAgainstSunJDK() {
// Since this test apparently fails (https://issues.jboss.org/browse/AS7-2166) against OpenJDK, due to missing Javascript engine, let's just enable this test against Sun/Oracle JDK (which is known/expected to pass).
// If an org.junit.Assume fails, then the @Test(s) are ignored http://stackoverflow.com/questions/1689242/conditionally-ignoring-tests-in-junit-4
final boolean compatibleJRE = isCompatibleJRE();
logger.trace("Current JRE is " + (compatibleJRE ? "compatible, running " : "incompatible, skipping ") + " tests in " + ScriptAssertTestCase.class.getSimpleName());
Assume.assumeTrue(compatibleJRE);
}
@Deployment
public static Archive<?> deploy() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "testscriptassert.war");
war.addPackage(ScriptAssertTestCase.class.getPackage());
return war;
}
@Test
public void testScriptAssert() throws NamingException, SQLException {
Validator validator = (Validator) new InitialContext().lookup("java:comp/Validator");
final Set<ConstraintViolation<ScriptAssertBean>> result = validator.validate(new ScriptAssertBean());
Assert.assertEquals(1, result.size());
}
/**
* Returns true if this testcase is expected to pass against the current Java runtime. Else returns false.
*
* @return
*/
private boolean isCompatibleJRE() {
final String javaRuntimeName = System.getProperty("java.runtime.name");
// The OpenJDK runtime has a value of "OpenJDK Runtime Environment" for the java.runtime.name system property. Since this test isn't passing against OpenJDK, we classify it as incompatible and return false
// if OpenJDK runtime is identified.
// Note, if this test is failing against other JREs (like IBM), add another check with the appropriate value for IBM here.
return !javaRuntimeName.contains("OpenJDK");
}
}
| 4,333 | 40.673077 | 223 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/multipleinjections/MultiplePersistenceContextInjectionsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.multipleinjections;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* AS7-1118
* <p>
* Tests that injecting multiple persistence units into the same EJB works as expected
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class MultiplePersistenceContextInjectionsTestCase {
@ArquillianResource
private InitialContext iniCtx;
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "multiplepuinjections.war");
war.addPackage(MultiplePersistenceContextInjectionsTestCase.class.getPackage());
// WEB-INF/classes is implied
war.addAsResource(MultiplePersistenceContextInjectionsTestCase.class.getPackage(), "persistence.xml", "META-INF/persistence.xml");
return war;
}
@Test
public void testMultiplePersistenceUnitInjectionsIntoSameBean() throws NamingException {
MultipleInjectionsSfsb bean = (MultipleInjectionsSfsb) iniCtx.lookup("java:module/" + MultipleInjectionsSfsb.class.getSimpleName());
Assert.assertNotNull(bean.getEntityManager());
Assert.assertNotNull(bean.getEntityManager2());
Assert.assertNotNull(bean.getExtendedEntityManager());
Assert.assertNotNull(bean.getExtendedEntityManager2());
}
}
| 2,761 | 37.901408 | 140 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/multipleinjections/MultipleInjectionsSfsb.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.multipleinjections;
import jakarta.ejb.Stateful;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContextType;
/**
* @author Stuart Douglas
*/
@Stateful
public class MultipleInjectionsSfsb {
@PersistenceContext
private EntityManager entityManager;
@PersistenceContext
private EntityManager entityManager2;
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager extendedEntityManager;
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager extendedEntityManager2;
public EntityManager getEntityManager() {
return entityManager;
}
public EntityManager getExtendedEntityManager() {
return extendedEntityManager;
}
public EntityManager getEntityManager2() {
return entityManager2;
}
public EntityManager getExtendedEntityManager2() {
return extendedEntityManager2;
}
}
| 2,065 | 30.784615 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/multipleinjections/Car.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.multipleinjections;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* @author Stuart Douglas
*/
@Entity
public class Car {
@Id
private int id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,507 | 26.418182 | 73 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestPersistenceProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.ProviderUtil;
/**
* TestPersistenceProvider
*
* @author Scott Marlow
*/
public class TestPersistenceProvider implements PersistenceProvider {
// key = pu name
private static Map<String, PersistenceUnitInfo> persistenceUnitInfo = new HashMap<String, PersistenceUnitInfo>();
public static PersistenceUnitInfo getPersistenceUnitInfo(String name) {
return persistenceUnitInfo.get(name);
}
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, Map map) {
return null;
}
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
persistenceUnitInfo.put(info.getPersistenceUnitName(), info);
TestClassTransformer testClassTransformer = new TestClassTransformer();
info.addTransformer(testClassTransformer);
TestEntityManagerFactory testEntityManagerFactory =
new TestEntityManagerFactory(info.getProperties());
Class[] targetInterfaces = jakarta.persistence.EntityManagerFactory.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(jakarta.persistence.EntityManagerFactory.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = jakarta.persistence.EntityManagerFactory.class;
}
EntityManagerFactory proxyEntityManagerFactory = (EntityManagerFactory) Proxy.newProxyInstance(
testEntityManagerFactory.getClass().getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
testEntityManagerFactory
);
return proxyEntityManagerFactory;
}
@Override
public void generateSchema(PersistenceUnitInfo persistenceUnitInfo, Map map) {
}
@Override
public boolean generateSchema(String s, Map map) {
return false;
}
@Override
public ProviderUtil getProviderUtil() {
return null;
}
public static void clearLastPersistenceUnitInfo() {
persistenceUnitInfo.clear();
}
}
| 4,069 | 38.134615 | 130 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestEntityManagerFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.EntityManager;
/**
* TestEntityManagerFactory
*
* @author Scott Marlow
*/
public class TestEntityManagerFactory implements InvocationHandler {
private Properties properties;
public TestEntityManagerFactory(Properties properties) {
this.properties = properties;
}
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
public static List<String> getInvocations() {
return invocations;
}
public static void clear() {
invocations.clear();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
if (method.getName().equals("toString")) {
return "xxx TestEntityManagerFactory proxy";
}
if (method.getName().equals("isOpen")) {
return true;
} else if(method.getName().equals("createEntityManager")) {
TestEntityManager testEntityManager =
new TestEntityManager(properties);
Class[] targetInterfaces = jakarta.persistence.EntityManager.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(jakarta.persistence.EntityManager.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = jakarta.persistence.EntityManager.class;
}
EntityManager proxyEntityManager = (EntityManager) Proxy.newProxyInstance(
testEntityManager.getClass().getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
testEntityManager
);
return proxyEntityManager;
} else if(method.getName().equals("getProperties")) {
return properties;
}
return null;
}
}
| 3,877 | 38.979381 | 127 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestClassTransformer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.spi.ClassTransformer;
/**
* TestClassTransformer
*
* @author Scott Marlow
*/
public class TestClassTransformer implements ClassTransformer {
// track class names that would of been transformed of this class was capable of doing so.
private static final List<String> transformedClasses = Collections.synchronizedList(new ArrayList<String>());
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
transformedClasses.add(className);
return classfileBuffer;
}
public static Collection getTransformedClasses() {
return transformedClasses;
}
public static void clearTransformedClasses() {
transformedClasses.clear();
}
}
| 2,093 | 35.736842 | 157 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/SkipquerydetachTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Hibernate "hibernate.ejb.use_class_enhancer" test that causes hibernate to add a
* jakarta.persistence.spi.ClassTransformer to the pu.
*
* @author Scott Marlow
*/
@RunWith(Arquillian.class)
public class SkipquerydetachTestCase {
private static final String ARCHIVE_NAME = "jpa_skipquerydetachTestWithMockProvider";
@Deployment
public static Archive<?> deploy() {
JavaArchive persistenceProvider = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar");
persistenceProvider.addClasses(
TestClassTransformer.class,
TestEntityManagerFactory.class,
TestEntityManager.class,
TestQuery.class,
TestPersistenceProvider.class,
TestAdapter.class
);
// META-INF/services/jakarta.persistence.spi.PersistenceProvider
persistenceProvider.addAsResource(new StringAsset("org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach.TestPersistenceProvider"),
"META-INF/services/jakarta.persistence.spi.PersistenceProvider");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear");
JavaArchive ejbjar = ShrinkWrap.create(JavaArchive.class, "ejbjar.jar");
ejbjar.addAsManifestResource(emptyEjbJar(), "ejb-jar.xml");
ejbjar.addClasses(SkipquerydetachTestCase.class,
SFSB1.class
);
ejbjar.addAsManifestResource(SkipquerydetachTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
ear.addAsModule(ejbjar); // add ejbjar to root of ear
ear.addAsLibraries(persistenceProvider);
return ear;
}
private static StringAsset emptyEjbJar() {
return new StringAsset(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" \n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n" +
" version=\"3.0\">\n" +
" \n" +
"</ejb-jar>");
}
@ArquillianResource
private InitialContext iniCtx;
@Test
public void test_withSkipQueryDetachEnabled() throws NamingException {
SFSB1 sfsb1 = (SFSB1)iniCtx.lookup("java:module/" + SFSB1.class.getSimpleName());
try {
assertNotNull("EJB injection of SFSB1 failed",sfsb1);
assertNull(sfsb1.queryWithSkipQueryDetachEnabled());
} finally {
TestAdapter.clearInitialized();
TestEntityManager.clear();
TestEntityManagerFactory.clear();
}
}
@Test
public void test_withSkipQueryDetachDisabled() throws NamingException {
SFSB1 sfsb1 = (SFSB1)iniCtx.lookup("java:module/" + SFSB1.class.getSimpleName());
try {
assertNotNull("EJB injection of SFSB1 failed",sfsb1);
assertNull(sfsb1.queryWithSkipQueryDetachDisabled());
} finally {
TestAdapter.clearInitialized();
TestEntityManager.clear();
TestEntityManagerFactory.clear();
}
}
}
| 5,089 | 39.07874 | 148 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestQuery.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* TestQuery
*
* @author Scott Marlow
*/
public class TestQuery implements InvocationHandler {
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
return null;
}
}
| 1,657 | 35.043478 | 106 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestEntityManager.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.Query;
/**
* TestEntityManager that implements createQuery
*
* @author Scott Marlow
*/
public class TestEntityManager implements InvocationHandler {
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
private Properties properties;
public TestEntityManager(Properties properties) {
this.properties = properties;
}
public static List<String> getInvocations() {
return invocations;
}
public static void clear() {
invocations.clear();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
if (method.getName().equals("isOpen")) {
return true;
} else if (method.getName().equals("createQuery")) {
TestQuery testQuery =
new TestQuery();
Class[] targetInterfaces = Query.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(jakarta.persistence.Query.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = jakarta.persistence.Query.class;
}
Query proxyQuery = (Query) Proxy.newProxyInstance(
testQuery.getClass().getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
testQuery
);
return proxyQuery;
} else if (method.getName().equals("close")) {
}
return null;
}
}
| 3,586 | 37.98913 | 122 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/SFSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.Query;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class SFSB1 {
@PersistenceUnit(unitName = "queryresultsaremanaged")
EntityManagerFactory emf;
@PersistenceContext(unitName = "queryresultsaremanaged")
EntityManager em;
@PersistenceContext(unitName = "queryresultsaredetached")
EntityManager emQueryResultsAreDetached;
/**
* verify that entitymanager.clear is not called after executing returned query.
*
* Return null for success, otherwise for test failure return fail message.
*/
public String queryWithSkipQueryDetachEnabled() {
if(TestEntityManager.getInvocations().contains("close")) {
return "invalid state, entity manager has already been previously closed";
}
if(TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager has already been previously cleared";
}
Query query = em.createQuery("mock query");
if(TestEntityManager.getInvocations().contains("close")) {
return "invalid state, entity manager was closed before query was executed, " +
"which means that 'wildfly.jpa.skipquerydetach=true' couldn't work, as the " +
"persistence context was closed too early";
}
if(TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager was cleared (detached) before query was executed, " +
"which means that 'wildfly.jpa.skipquerydetach=true' didn't work";
}
query.getSingleResult();
if(TestEntityManager.getInvocations().contains("close")) {
return "invalid state, entity manager was closed before SFSB1 bean call completed, " +
"which means that 'wildfly.jpa.skipquerydetach=true' couldn't work, as the " +
"persistence context was closed too early";
}
if(TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager was cleared (detached) before SFSB1 bean call completed, " +
"which means that 'wildfly.jpa.skipquerydetach=true' didn't work";
}
return null; // success
}
/**
* verify that entitymanager.clear is called after executing returned query.
*
* Return null for success, otherwise for test failure return fail message.
*/
public String queryWithSkipQueryDetachDisabled() {
if(TestEntityManager.getInvocations().contains("close")) {
return "invalid state, entity manager has already been previously closed";
}
if(TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager has already been previously cleared";
}
Query query = emQueryResultsAreDetached.createQuery("mock query");
if(TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager was cleared (detached) after query was created but before executed," +
"which means that 'wildfly.jpa.skipquerydetach=false' (default) behaviour didn't work";
}
query.getSingleResult();
if(TestEntityManager.getInvocations().contains("close")) {
return "invalid state, entity manager was closed before SFSB1 bean call completed, " +
"which means that 'wildfly.jpa.skipquerydetach=false' couldn't work, as the " +
"persistence context was closed too early";
}
if(!TestEntityManager.getInvocations().contains("clear")) {
return "invalid state, entity manager was not cleared (detached) as expected," +
"which means that 'wildfly.jpa.skipquerydetach=false' (default) behaviour didn't work";
}
return null; // success
}
}
| 5,429 | 45.410256 | 120 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/skipquerydetach/TestAdapter.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.skipquerydetach;
import java.util.Map;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jipijapa.plugin.spi.JtaManager;
import org.jipijapa.plugin.spi.ManagementAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.Platform;
/**
* persistence provider adaptor test class
*
* @author Scott Marlow
*/
public class TestAdapter implements PersistenceProviderAdaptor {
private static volatile boolean initialized = false;
@Override
public void injectJtaManager(JtaManager jtaManager) {
}
@Override
public void injectPlatform(Platform platform) {
}
@Override
public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
}
@Override
public void addProviderDependencies(PersistenceUnitMetadata pu) {
}
@Override
public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
initialized = true;
}
@Override
public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
}
@Override
public ManagementAdaptor getManagementAdaptor() {
return null;
}
@Override
public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) {
return false;
}
@Override
public void cleanup(PersistenceUnitMetadata pu) {
}
@Override
public Object beanManagerLifeCycle(BeanManager beanManager) {
return null;
}
@Override
public void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle) {
}
public static boolean wasInitialized() {
return initialized;
}
public static void clearInitialized() {
initialized = false;
}
}
| 2,928 | 26.373832 | 101 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* Employee entity class
*
* @author Scott Marlow
*/
@Entity
public class Employee {
@Id
private int id;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,727 | 24.411765 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/TestPersistenceProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.ProviderUtil;
/**
* TestPersistenceProvider
*
* @author Scott Marlow
*/
public class TestPersistenceProvider implements PersistenceProvider {
// key = pu name
private static Map<String, PersistenceUnitInfo> persistenceUnitInfo = new HashMap<String, PersistenceUnitInfo>();
public static PersistenceUnitInfo getPersistenceUnitInfo(String name) {
return persistenceUnitInfo.get(name);
}
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, Map map) {
return null;
}
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
persistenceUnitInfo.put(info.getPersistenceUnitName(), info);
TestEntityManagerFactory testEntityManagerFactory =
new TestEntityManagerFactory();
Class[] targetInterfaces = EntityManagerFactory.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(EntityManagerFactory.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = EntityManagerFactory.class;
}
EntityManagerFactory proxyEntityManagerFactory = (EntityManagerFactory) Proxy.newProxyInstance(
testEntityManagerFactory.getClass().getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
testEntityManagerFactory
);
return proxyEntityManagerFactory;
}
@Override
public void generateSchema(PersistenceUnitInfo persistenceUnitInfo, Map map) {
}
@Override
public boolean generateSchema(String s, Map map) {
return false;
}
@Override
public ProviderUtil getProviderUtil() {
return null;
}
public static void clearLastPersistenceUnitInfo() {
persistenceUnitInfo.clear();
}
}
| 3,836 | 36.617647 | 130 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/TxTimeoutTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import static org.junit.Assert.assertFalse;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Transaction timeout test that ensures that the entity manager is not closed concurrently while application
* is using EntityManager.
* AS7-6586
*
* @author Scott Marlow
*/
@RunWith(Arquillian.class)
public class TxTimeoutTestCase {
private static final String ARCHIVE_NAME = "jpa_txTimeoutTestWithMockProvider";
@Deployment
public static Archive<?> deploy() {
JavaArchive persistenceProvider = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar");
persistenceProvider.addClasses(
TestEntityManagerFactory.class,
TestEntityManager.class,
TestPersistenceProvider.class
);
// META-INF/services/jakarta.persistence.spi.PersistenceProvider
persistenceProvider.addAsResource(new StringAsset("org.jboss.as.test.integration.jpa.mockprovider.txtimeout.TestPersistenceProvider"),
"META-INF/services/jakarta.persistence.spi.PersistenceProvider");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear");
JavaArchive ejbjar = ShrinkWrap.create(JavaArchive.class, "ejbjar.jar");
ejbjar.addAsManifestResource(emptyEjbJar(), "ejb-jar.xml");
ejbjar.addClasses(TxTimeoutTestCase.class,
SFSB1.class
);
ejbjar.addAsManifestResource(TxTimeoutTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
ear.addAsModule(ejbjar); // add ejbjar to root of ear
JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar");
lib.addClasses(Employee.class, TxTimeoutTestCase.class);
ear.addAsLibraries(lib, persistenceProvider);
ear.addAsManifestResource(new StringAsset("Dependencies: org.jboss.jboss-transaction-spi export \n"), "MANIFEST.MF");
return ear;
}
private static StringAsset emptyEjbJar() {
return new StringAsset(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" \n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n" +
" version=\"3.0\">\n" +
" \n" +
"</ejb-jar>");
}
@ArquillianResource
private InitialContext iniCtx;
protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException {
try {
return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName()));
} catch (NamingException e) {
throw e;
}
}
/**
* Tests if the entity manager is closed by the application thread.
* The transaction does not timeout for this test, so the EntityManager.close() will happen in the application
* thread.
*
* @throws Exception
*/
@Test
@InSequence(1)
public void test_positiveTxTimeoutTest() throws Exception {
TestEntityManager.clearState();
assertFalse("entity manager state is not reset", TestEntityManager.getClosedByReaperThread());
SFSB1 sfsb1 = lookup("ejbjar/SFSB1", SFSB1.class);
sfsb1.createEmployee("Wily", "1 Appletree Lane", 10);
assertFalse("entity manager should be closed by application thread but was closed by TX Reaper thread",
TestEntityManager.getClosedByReaperThread());
}
}
| 5,337 | 41.031496 | 145 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/TestEntityManagerFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import jakarta.persistence.EntityManager;
/**
* TestEntityManagerFactory
*
* @author Scott Marlow
*/
public class TestEntityManagerFactory implements InvocationHandler {
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
if (method.getName().equals("createEntityManager")) {
return entityManager();
} else if(method.getName().equals("getProperties")) {
return new HashMap<String, Object>();
} else if(method.getName().equals("isOpen")) {
return true;
} else {
// System.out.println("TestEntityManagerFactory method=" + method.getName() + " is returning null");
}
return null;
}
private EntityManager entityManager() {
TestEntityManager testEntityManager =
new TestEntityManager();
Class[] targetInterfaces = EntityManager.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(EntityManager.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = EntityManager.class;
}
EntityManager proxyEntityManager = (EntityManager) Proxy.newProxyInstance(
testEntityManager.getClass().getClassLoader(),
proxyInterfaces,
testEntityManager
);
return proxyEntityManager;
}
}
| 3,454 | 37.820225 | 118 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/TestEntityManager.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.jboss.tm.TxUtils;
/**
* TestEntityManager
*
* @author Scott Marlow
*/
public class TestEntityManager implements InvocationHandler {
private static AtomicBoolean closedByReaperThread = new AtomicBoolean(false);
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
if (method.getName().equals("persist")) {
return persist();
}
if (method.getName().equals("close")) {
return close();
}
if (method.getName().equals("toString")) {
return "EntityManager";
}
return null;
}
private Object persist() {
DataSource dataSource = null;
InitialContext context = null;
try {
context = new InitialContext();
} catch (NamingException e) {
e.printStackTrace();
throw new RuntimeException("naming error creating initial context");
}
try {
dataSource = (DataSource) context.lookup("java:jboss/datasources/ExampleDS");
} catch (NamingException e) {
e.printStackTrace();
throw new RuntimeException("naming error creating initial context", e);
}
try {
dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("datasource error getting connection", e);
}
return null;
}
public static boolean getClosedByReaperThread() {
return closedByReaperThread.get();
}
private Object close() {
boolean isBackgroundReaperThread =
TxUtils.isTransactionManagerTimeoutThread();
if (isBackgroundReaperThread) {
closedByReaperThread.set(true);
} else {
closedByReaperThread.set(false);
}
return null;
}
public static void clearState() {
closedByReaperThread.set(false);
}
}
| 3,571 | 30.610619 | 106 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/txtimeout/SFSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.txtimeout;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateful;
import jakarta.persistence.EntityManager;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.ejb3.annotation.TransactionTimeout;
import org.jboss.logging.Logger;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
public class SFSB1 {
private static final Logger LOGGER = Logger.getLogger(SFSB1.class);
@PersistenceContext
EntityManager entityManager;
@Resource
TransactionSynchronizationRegistry transactionSynchronizationRegistry;
public void createEmployee(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
entityManager.persist(emp);
}
@TransactionTimeout(value = 1, unit = TimeUnit.SECONDS)
public void createEmployeeWaitForTxTimeout(String name, String address, int id) {
LOGGER.trace("org.jboss.as.test.integration.jpa.mockprovider.txtimeout.createEmployeeWaitForTxTimeout " +
"entered, will wait for tx time out to occur");
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
entityManager.persist(emp);
boolean done = false;
while (!done) {
try {
Thread.sleep(250);
entityManager.find(Employee.class, id);
int status = transactionSynchronizationRegistry.getTransactionStatus();
switch (status) {
case Status.STATUS_COMMITTED:
throw new RuntimeException("transaction was committed.");
case Status.STATUS_ROLLEDBACK:
LOGGER.trace("tx timed out and rolled back as expected, success case reached.");
done = true;
break;
case Status.STATUS_ACTIVE:
LOGGER.trace("tx is still active, sleep for 250ms and check tx status again.");
break;
default:
LOGGER.trace("tx status = " + status + ", sleep for 250ms and check tx status again.");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
LOGGER.trace("org.jboss.as.test.integration.jpa.mockprovider.txtimeout.createEmployeeWaitForTxTimeout waiting for tx to timeout");
}
}
public Employee getEmployeeNoTX(int id) {
return entityManager.find(Employee.class, id, LockModeType.NONE);
}
}
| 3,964 | 37.495146 | 142 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* Employee entity class
*
* @author Scott Marlow
*/
@Entity
public class Employee {
@Id
private int id;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,734 | 24.514706 | 72 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/TestPersistenceProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.ProviderUtil;
/**
* TestPersistenceProvider
*
* @author Scott Marlow
*/
public class TestPersistenceProvider implements PersistenceProvider {
// key = pu name
private static Map<String, PersistenceUnitInfo> persistenceUnitInfo = new HashMap<String, PersistenceUnitInfo>();
public static PersistenceUnitInfo getPersistenceUnitInfo(String name) {
return persistenceUnitInfo.get(name);
}
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, Map map) {
return null;
}
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
persistenceUnitInfo.put(info.getPersistenceUnitName(), info);
TestClassTransformer testClassTransformer = new TestClassTransformer();
info.addTransformer(testClassTransformer);
TestEntityManagerFactory testEntityManagerFactory =
new TestEntityManagerFactory();
Class[] targetInterfaces = jakarta.persistence.EntityManagerFactory.class.getInterfaces();
Class[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(jakarta.persistence.EntityManagerFactory.class)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = jakarta.persistence.EntityManagerFactory.class;
}
EntityManagerFactory proxyEntityManagerFactory = (EntityManagerFactory) Proxy.newProxyInstance(
testEntityManagerFactory.getClass().getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
testEntityManagerFactory
);
return proxyEntityManagerFactory;
}
@Override
public void generateSchema(PersistenceUnitInfo persistenceUnitInfo, Map map) {
}
@Override
public boolean generateSchema(String s, Map map) {
return false;
}
@Override
public ProviderUtil getProviderUtil() {
return null;
}
public static void clearLastPersistenceUnitInfo() {
persistenceUnitInfo.clear();
}
}
| 4,034 | 37.798077 | 130 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/TestEntityManagerFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* TestEntityManagerFactory
*
* @author Scott Marlow
*/
public class TestEntityManagerFactory implements InvocationHandler {
private static final List<String> invocations = Collections.synchronizedList(new ArrayList<String>());
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
invocations.add(method.getName());
if (method.getName().equals("isOpen")) {
return false;
}
return null;
}
}
| 1,759 | 33.509804 | 106 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/ClassFileTransformerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import javax.naming.InitialContext;
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.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Hibernate "hibernate.ejb.use_class_enhancer" test that causes hibernate to add a
* jakarta.persistence.spi.ClassTransformer to the pu.
*
* @author Scott Marlow
*/
@RunWith(Arquillian.class)
public class ClassFileTransformerTestCase {
private static final String ARCHIVE_NAME = "jpa_classTransformerTestWithMockProvider";
@Deployment
public static Archive<?> deploy() {
JavaArchive persistenceProvider = ShrinkWrap.create(JavaArchive.class, "testpersistenceprovider.jar");
persistenceProvider.addClasses(
TestClassTransformer.class,
TestEntityManagerFactory.class,
TestPersistenceProvider.class,
TestAdapter.class
);
// META-INF/services/jakarta.persistence.spi.PersistenceProvider
persistenceProvider.addAsResource(new StringAsset("org.jboss.as.test.integration.jpa.mockprovider.classtransformer.TestPersistenceProvider"),
"META-INF/services/jakarta.persistence.spi.PersistenceProvider");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear");
JavaArchive ejbjar = ShrinkWrap.create(JavaArchive.class, "ejbjar.jar");
ejbjar.addAsManifestResource(emptyEjbJar(), "ejb-jar.xml");
ejbjar.addClasses(ClassFileTransformerTestCase.class,
SFSB1.class
);
ejbjar.addAsManifestResource(ClassFileTransformerTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
ear.addAsModule(ejbjar); // add ejbjar to root of ear
JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar");
lib.addClasses(Employee.class, ClassFileTransformerTestCase.class);
ear.addAsLibraries(lib, persistenceProvider);
return ear;
}
private static StringAsset emptyEjbJar() {
return new StringAsset(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" \n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n" +
" version=\"3.0\">\n" +
" \n" +
"</ejb-jar>");
}
@ArquillianResource
private InitialContext iniCtx;
@Test
public void test_use_class_enhancer() throws Exception {
try {
assertTrue("entity classes are enhanced", TestClassTransformer.getTransformedClasses().size() > 0);
} finally {
TestClassTransformer.clearTransformedClasses();
}
}
@Test
public void test_persistenceUnitInfoURLS() throws Exception {
if(WildFlySecurityManager.isChecking()) { // avoid Permission check failed (permission "("org.jboss.vfs.VirtualFilePermission"
try {
assertTrue("testing that PersistenceUnitInfo.getPersistenceUnitRootUrl() url is vfs based, failed because getPersistenceUnitRootUrl is " +
TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().getProtocol(),
"vfs".equals(TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().getProtocol()));
} finally {
TestPersistenceProvider.clearLastPersistenceUnitInfo();
}
}
else {
try {
assertTrue("testing that PersistenceUnitInfo.getPersistenceUnitRootUrl() url is vfs based, failed because getPersistenceUnitRootUrl is " +
TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().getProtocol(),
"vfs".equals(TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().getProtocol()));
InputStream inputStream = TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().openStream();
assertNotNull("getPersistenceUnitRootUrl().openStream() returned non-null value", inputStream);
assertTrue("getPersistenceUnitRootUrl returned a JarInputStream", inputStream instanceof JarInputStream);
JarInputStream jarInputStream = (JarInputStream) inputStream;
ZipEntry entry = jarInputStream.getNextEntry();
assertNotNull("got zip entry from getPersistenceUnitRootUrl", entry);
while (entry != null && !entry.getName().contains("persistence.xml")) {
entry = jarInputStream.getNextEntry();
}
assertNotNull("didn't find persistence.xml in getPersistenceUnitRootUrl, details=" +
urlOpenStreamDetails(TestPersistenceProvider.getPersistenceUnitInfo("mypc").getPersistenceUnitRootUrl().openStream()),
entry);
} finally {
TestPersistenceProvider.clearLastPersistenceUnitInfo();
}
}
}
@Test
public void test_persistenceProviderAdapterInitialized() {
try {
assertTrue("persistence unit adapter was initialized", TestAdapter.wasInitialized());
} finally {
TestAdapter.clearInitialized();
}
}
private String urlOpenStreamDetails(InputStream urlStream) {
String result = null;
try {
JarInputStream jarInputStream = (JarInputStream) urlStream;
ZipEntry entry = jarInputStream.getNextEntry();
while (entry != null) {
result += entry.getName() + ", ";
entry = jarInputStream.getNextEntry();
}
} catch (IOException e) {
return "couldn't get content, caught error " + e.getMessage();
}
return result;
}
}
| 7,866 | 43.954286 | 154 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/TestClassTransformer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.spi.ClassTransformer;
/**
* TestClassTransformer
*
* @author Scott Marlow
*/
public class TestClassTransformer implements ClassTransformer {
// track class names that would of been transformed of this class was capable of doing so.
private static final List<String> transformedClasses = Collections.synchronizedList(new ArrayList<String>());
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
transformedClasses.add(className);
return classfileBuffer;
}
public static Collection getTransformedClasses() {
return transformedClasses;
}
public static void clearTransformedClasses() {
transformedClasses.clear();
}
}
| 2,076 | 36.089286 | 156 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/SFSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import jakarta.ejb.Stateful;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceUnit;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
public class SFSB1 {
@PersistenceUnit
EntityManagerFactory emf;
public void createEmployee(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
emf.createEntityManager().persist(emp);
}
public Employee getEmployeeNoTX(int id) {
return emf.createEntityManager().find(Employee.class, id, LockModeType.NONE);
}
}
| 1,793 | 32.849057 | 85 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/mockprovider/classtransformer/TestAdapter.java
|
package org.jboss.as.test.integration.jpa.mockprovider.classtransformer;
import java.util.Map;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jipijapa.plugin.spi.JtaManager;
import org.jipijapa.plugin.spi.ManagementAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.Platform;
/**
* persistence provider adaptor test class
*
* @author Scott Marlow
*/
public class TestAdapter implements PersistenceProviderAdaptor {
private static volatile boolean initialized = false;
@Override
public void injectJtaManager(JtaManager jtaManager) {
}
@Override
public void injectPlatform(Platform platform) {
}
@Override
public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
}
@Override
public void addProviderDependencies(PersistenceUnitMetadata pu) {
}
@Override
public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
initialized = true;
}
@Override
public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
}
@Override
public ManagementAdaptor getManagementAdaptor() {
return null;
}
@Override
public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) {
return false;
}
@Override
public void cleanup(PersistenceUnitMetadata pu) {
}
@Override
public Object beanManagerLifeCycle(BeanManager beanManager) {
return null;
}
@Override
public void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle) {
}
public static boolean wasInitialized() {
return initialized;
}
public static void clearInitialized() {
initialized = false;
}
}
| 1,889 | 21.235294 | 101 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/SFSBXPC.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContextType;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
/**
* stateful session bean with an extended persistence context
*
* @author Scott Marlow
*/
@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class SFSBXPC {
@PersistenceContext(unitName = "mypc", type = PersistenceContextType.EXTENDED)
EntityManager extendedEm;
@Resource
UserTransaction tx;
public void createEmployeeNoTx(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
extendedEm.persist(emp);
}
/**
* UT part of test for JPA 7.9.1 Container Responsibilities for XPC
* <p>
* "When a business method of the stateful session bean is invoked, if the stateful session bean
* uses bean managed transaction demarcation and a UserTransaction is begun within the method,
* the container associates the persistence context with the Jakarta Transactions transaction and calls
* EntityManager.joinTransaction.
* "
*/
public void savePendingChanges() {
try {
tx.begin();
tx.commit();
} catch (Exception e) {
throw new RuntimeException("could not commit pending extended persistence changes", e);
}
}
public void forceRollbackAndLosePendingChanges(int id, boolean shouldOfSavedAlready) {
Employee employee = extendedEm.find(Employee.class, id);
if (employee == null) { // employee should be found
throw new RuntimeException("pending database changes were not saved previously, could not find Employee id = " + id);
}
try {
tx.begin();
tx.rollback();
} catch (NotSupportedException ignore) {
} catch (SystemException ignore) {
}
employee = extendedEm.find(Employee.class, id);
if (shouldOfSavedAlready && employee == null) {
throw new RuntimeException("unexpectedly in forceRollbackAndLosePendingChanges(), rollback lost Employee id = " + id + ", which should of been previously saved");
} else if (!shouldOfSavedAlready && employee != null) {
throw new RuntimeException("unexpectedly in forceRollbackAndLosePendingChanges(), database changes shouldn't of been saved yet for Employee id = " + id);
}
}
public Employee lookup(int empid) {
return extendedEm.find(Employee.class, empid);
}
}
| 3,969 | 35.759259 | 174 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* Employee entity class
*
* @author Scott Marlow
*/
@Entity
public class Employee {
@Id
private int id;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,724 | 24.746269 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/SFSBCMT.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SFSBCMT {
@PersistenceContext(unitName = "mypc")
EntityManager em;
@Resource
SessionContext sessionContext;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Employee queryEmployeeNameRequireNewTX(int id) {
Query q = em.createQuery("SELECT e FROM Employee e where id=?");
q.setParameter(1, new Integer(id));
return (Employee) q.getSingleResult();
}
}
| 2,055 | 33.847458 | 72 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/DataSourceDefinitionJPATestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.persistence.TransactionRequiredException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Transaction tests
*
* @author Scott Marlow and Zbynek Roubalik
*/
@RunWith(Arquillian.class)
public class DataSourceDefinitionJPATestCase {
private static final String ARCHIVE_NAME = "jpa_datasourcedefinition";
@Deployment
public static Archive<?> deploy() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar");
jar.addPackage(DataSourceDefinitionJPATestCase.class.getPackage());
jar.addAsManifestResource(DataSourceDefinitionJPATestCase.class.getPackage(), "persistence.xml", "persistence.xml");
jar.addAsManifestResource(new StringAsset("Dependencies: com.h2database.h2\n"), "MANIFEST.MF");
return jar;
}
@ArquillianResource
private static InitialContext iniCtx;
protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName()));
}
protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup(name));
}
@Test
@InSequence(1)
public void testMultipleNonTXTransactionalEntityManagerInvocations() throws Exception {
SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class);
sfsb1.getEmployeeNoTX(1); // For each call in, we will use a transactional entity manager
// that isn't running in a transaction. So, a new underlying
// entity manager will be obtained. The is to ensure that we don't blow up.
sfsb1.getEmployeeNoTX(1);
sfsb1.getEmployeeNoTX(1);
}
@Test
@InSequence(2)
public void testQueryNonTXTransactionalEntityManagerInvocations() throws Exception {
SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class);
String name = sfsb1.queryEmployeeNameNoTX(1);
assertEquals("Query should of thrown NoResultException, which we indicate by returning 'success'", "success", name);
}
// Test that the queried Employee is detached as required by JPA 2.0 section 3.8.6
// For a transaction scoped persistence context non jta-tx invocation, entities returned from Query
// must be detached.
@Test
@InSequence(3)
public void testQueryNonTXTransactionalDetach() throws Exception {
SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class);
sfsb1.createEmployee("Jill", "54 Country Lane", 2);
Employee employee = sfsb1.queryEmployeeNoTX(2);
assertNotNull(employee);
boolean detached = sfsb1.isQueryEmployeeDetached(2);
assertTrue("JPA 2.0 section 3.8.6 violated, query returned entity in non-tx that wasn't detached ", detached);
}
/**
* Ensure that calling entityManager.flush outside of a transaction, throws a TransactionRequiredException
*
* @throws Exception
*/
@Test
@InSequence(4)
public void testTransactionRequiredException() throws Exception {
Throwable error = null;
try {
SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class);
sfsb1.createEmployeeNoTx("Sally", "1 home street", 1);
} catch (TransactionRequiredException e) {
error = e;
} catch (Exception failed) {
error = failed;
}
// jakarta.ejb.EJBException: jakarta.persistence.TransactionRequiredException: no transaction is in progress
while (error != null && !(error instanceof TransactionRequiredException) && error.getCause() != null) {
error = error.getCause();
}
assertTrue(
"attempting to persist entity with transactional entity manager and no transaction, should fail with a TransactionRequiredException"
+ " but we instead got a " + error, error instanceof TransactionRequiredException);
}
/**
* Tests Jakarta Transactions involving an EJB 3 SLSB which makes two DAO calls in transaction.
* Scenarios:
* 1) The transaction fails during the first DAO call and the Jakarta Transactions transaction is rolled back and no database changes should occur.
* 2) The transaction fails during the second DAO call and the Jakarta Transactions transaction is rolled back and no database changes should occur.
* 3) The transaction fails after the DAO calls and the Jakarta Transactions transaction is rolled back and no database changes should occur.
*/
@Test
@InSequence(5)
public void testFailInDAOCalls() throws Exception {
SLSB1 slsb1 = lookup("SLSB1", SLSB1.class);
slsb1.addEmployee();
String message = slsb1.failInFirstCall();
assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message);
message = slsb1.failInSecondCall();
assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message);
message = slsb1.failAfterCalls();
assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message);
}
@Test
@InSequence(6)
public void testUserTxRollbackDiscardsChanges() throws Exception {
SFSBXPC sfsbxpc = lookup("SFSBXPC", SFSBXPC.class);
sfsbxpc.createEmployeeNoTx("Amory Lorch", "Lannister House", 10); // create the employee but leave in xpc
Employee employee = sfsbxpc.lookup(10);
assertNotNull("could read employee record from extended persistence context (not yet saved to db)", employee);
// rollback any changes that haven't been saved yet
sfsbxpc.forceRollbackAndLosePendingChanges(10, false);
employee = sfsbxpc.lookup(10);
assertNull("employee record should not be found in db after rollback", employee);
}
@Test
@InSequence(7)
public void testEnlistXPCInUserTx() throws Exception {
SFSBXPC sfsbxpc = lookup("SFSBXPC", SFSBXPC.class);
sfsbxpc.createEmployeeNoTx("Amory Lorch", "Lannister House", 20); // create the employee but leave in xpc
Employee employee = sfsbxpc.lookup(20);
assertNotNull("could read employee record from extended persistence context (not yet saved to db)", employee);
// start/end a user transaction without invoking the (extended) entity manager, which should cause the
// pending changes to be saved to db
sfsbxpc.savePendingChanges();
sfsbxpc.forceRollbackAndLosePendingChanges(20, true);
employee = sfsbxpc.lookup(20);
assertNotNull("could read employee record from extended persistence context (wasn't saved to db during savePendingChanges())", employee);
}
}
| 8,521 | 42.479592 | 152 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/SFSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
import jakarta.transaction.UserTransaction;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class SFSB1 {
@PersistenceContext(unitName = "mypc")
EntityManager em;
@Resource
SessionContext sessionContext;
// always throws a TransactionRequiredException
public void createEmployeeNoTx(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
UserTransaction tx1 = sessionContext.getUserTransaction();
try {
tx1.begin();
em.joinTransaction();
em.persist(emp);
tx1.commit();
} catch (Exception e) {
throw new RuntimeException("couldn't start tx", e);
}
em.flush(); // should throw TransactionRequiredException
}
public void createEmployee(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
UserTransaction tx1 = sessionContext.getUserTransaction();
try {
tx1.begin();
em.joinTransaction();
em.persist(emp);
tx1.commit();
} catch (Exception e) {
throw new RuntimeException("couldn't start tx", e);
}
}
public Employee getEmployeeNoTX(int id) {
return em.find(Employee.class, id);
}
public String queryEmployeeNameNoTX(int id) {
Query q = em.createQuery("SELECT e.name FROM Employee e where e.id=:id");
q.setParameter("id", new Integer(id));
try {
String name = (String) q.getSingleResult();
return name;
} catch (NoResultException expected) {
return "success";
} catch (Exception unexpected) {
return unexpected.getMessage();
}
}
public Employee queryEmployeeNoTX(int id) {
TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e where e.id=:id", Employee.class);
q.setParameter("id", new Integer(id));
return q.getSingleResult();
}
// return true if the queried Employee is detached as required by JPA 2.0 section 3.8.6
// For a transaction scoped persistence context non jta-tx invocation, entities returned from Query
// must be detached.
public boolean isQueryEmployeeDetached(int id) {
TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e where e.id=:id", Employee.class);
q.setParameter("id", new Integer(id));
Employee employee = q.getSingleResult();
return em.contains(employee) != true;
}
}
| 4,259 | 32.28125 | 107 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/datasourcedefinition/SLSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.datasourcedefinition;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Arrays;
import jakarta.annotation.Resource;
import jakarta.annotation.sql.DataSourceDefinition;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import javax.naming.Context;
import javax.naming.InitialContext;
import jakarta.persistence.EntityExistsException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import javax.sql.DataSource;
import jakarta.transaction.UserTransaction;
/**
* @author Zbynek Roubalik
*/
@DataSourceDefinition(
name = "java:app/DataSource",
user = "sa",
password = "sa",
className = "org.h2.jdbcx.JdbcDataSource",
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"
)
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class SLSB1 {
@PersistenceContext(unitName = "mypc")
EntityManager em;
@Resource
UserTransaction tx;
public Employee createEmployee(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
return emp;
}
/**
* Makes two DAO calls, the transaction fails during the first DAO call. The
* Jakarta Transactions transaction is rolled back and no database changes should occur.
*/
public String failInFirstCall() throws Exception {
int[] initialList = getEmployeeIDsNoEM();
try {
tx.begin();
performFailCall();
em.persist(createEmployee("Tony", "Butcher", 101));
tx.commit();
return "Transaction was performed, but shouldn't";
} catch (EntityExistsException e) {
tx.rollback();
int[] newList = getEmployeeIDsNoEM();
if (Arrays.equals(initialList, newList)) {
return "success";
} else {
return "Database changed.";
}
}
}
/**
* Makes two DAO calls, the transaction fails during the second DAO call.
* The Jakarta Transactions transaction is rolled back and no database changes should occur.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String failInSecondCall() throws Exception {
int[] initialList = getEmployeeIDsNoEM();
try {
tx.begin();
em.persist(createEmployee("Jane", "Butcher", 102));
performFailCall();
tx.commit();
return "Transaction was performed, but shouldn't";
} catch (EntityExistsException e) {
tx.rollback();
int[] newList = getEmployeeIDsNoEM();
if (Arrays.equals(initialList, newList)) {
return "success";
} else {
return "Database changed.";
}
} catch (Exception unexpected) {
return unexpected.getMessage();
}
}
/**
* Makes two DAO calls, the transaction fails after the DAO calls. The Jakarta Transactions
* transaction is rolled back and no database changes should occur.
*/
public String failAfterCalls() throws Exception {
int[] initialList = getEmployeeIDsNoEM();
try {
tx.begin();
em.persist(createEmployee("Peter", "Butcher", 103));
em.persist(createEmployee("John", "Butcher", 104));
int n = 100 / 0; // this should throw exception: division by zero
n = n + 20;
tx.commit();
return "Transaction was performed, but shouldn't";
} catch (Exception e) {
tx.rollback();
int[] newList = getEmployeeIDsNoEM();
if (Arrays.equals(initialList, newList)) {
return "success";
} else {
return "Database changed.";
}
}
}
/**
* Persisting existing entity, should throws EntityExistsException
*/
public void performFailCall() {
Employee emp = em.find(Employee.class, 1212);
if (emp == null) {
emp = createEmployee("Mr. Problem", "Brno ", 1212);
em.persist(emp);
em.flush();
}
em.persist(createEmployee(emp.getName(), emp.getAddress(), emp.getId()));
}
/**
* Returns array of Employee IDs in DB using raw connection to the
* DataSource
*/
public int[] getEmployeeIDsNoEM() throws Exception {
int[] idList = null;
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx
.lookup("java:jboss/datasources/ExampleDS");
Connection conn = ds.getConnection();
try {
ResultSet rs = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY).executeQuery(
"SELECT e.id FROM Employee e ORDER BY e.id");
rs.last();
int rowCount = rs.getRow();
idList = new int[rowCount];
rs.first();
int i = 0;
while (rs.next()) {
idList[i] = rs.getInt(1);
i++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
return idList;
}
/**
* Adds new Employee
*/
public void addEmployee() throws Exception {
try {
tx.begin();
em.persist(createEmployee("John", "Wayne", 100));
tx.commit();
} catch (Exception e) {
throw new Exception("Couldn't add an Employee.");
}
}
}
| 6,965 | 29.687225 | 96 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/deploymentsubsystemoperations/JPADeploymentSubsystemOperationsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.deploymentsubsystemoperations;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
/**
* Regression tests for WFLY-11173
* Tests proper operations behavior in /deployment/subsystem=jpa case
*
* @author <a href="mailto:[email protected]">Petr Beran
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JPADeploymentSubsystemOperationsTestCase {
private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient();
private static final PathAddress DEPLOYMENT_PATH = PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT, JPADeploymentSubsystemOperationsTestCase.class.getSimpleName() + ".war"));
private static final PathAddress SUBSYSTEM_PATH = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, "jpa"));
// Hardcoded to avoid adding the JPA module as a dependency
// Same goes for the "jpa" in SUBSYSTEM_PATH
private static final String DEFAULT_DATASOURCE = "default-datasource";
private static final String DEFAULT_EXTENDED_PERSISTENCE_INHERITANCE = "default-extended-persistence-inheritance";
@Deployment
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, JPADeploymentSubsystemOperationsTestCase.class.getSimpleName() + ".war");
war.addAsWebInfResource(JPADeploymentSubsystemOperationsTestCase.class.getPackage(), "persistence.xml", "classes/META-INF/persistence.xml");
return war;
}
/**
* Tests the proper behavior for the {@code read-resource} operation on the JPA subsystem in a deployment.
* The {@code read-resource} should return the main subsystem values instead of the deployment's subsystem ones.
*
* @throws IOException if an error occurs during the {@code ModelNode} execution.
*/
@Test
public void testReadResourceOperation() throws IOException {
// We need to change the subsystem's attribute from a default one. Otherwise we would be checking a default value
// against a default value and the test would pass every time.
// The default value for default-extended-persistence-inheritance is DEEP, so we're changing it to SHALLOW, see JPADefinition class
ModelNode writeAttributeModelNode = Util.getWriteAttributeOperation(SUBSYSTEM_PATH, DEFAULT_EXTENDED_PERSISTENCE_INHERITANCE, "SHALLOW");
controllerClient.execute(writeAttributeModelNode);
ModelNode subsystemModelNode = Util.getReadResourceOperation(SUBSYSTEM_PATH);
ModelNode subsystemResult = controllerClient.execute(subsystemModelNode);
ModelNode deploymentModelNode = Util.getReadResourceOperation(DEPLOYMENT_PATH.append(SUBSYSTEM_PATH));
ModelNode deploymentResult = controllerClient.execute(deploymentModelNode);
Assert.assertEquals("The attribute in the subsystem and in the deployment is not the same",
subsystemResult.get(RESULT).get(DEFAULT_EXTENDED_PERSISTENCE_INHERITANCE),
deploymentResult.get(RESULT).get(DEFAULT_EXTENDED_PERSISTENCE_INHERITANCE));
Assert.assertEquals("The attribute in the subsystem and in the deployment is not the same",
subsystemResult.get(RESULT).get(DEFAULT_DATASOURCE),
deploymentResult.get(RESULT).get(DEFAULT_DATASOURCE));
}
/**
* Tests the proper behavior for the {@code add} and {@code remove} operations on the JPA subsystem in a deployment.
* These operations should fail since they are unsupported in a deployment's subsystem.
*
* @throws IOException if an error occurs during the {@code ModelNode} execution.
*/
@Test
public void testAddRemoveResource() throws IOException {
ModelNode removeModelNode = Util.createRemoveOperation(DEPLOYMENT_PATH.append(SUBSYSTEM_PATH));
ModelNode removeResult = controllerClient.execute(removeModelNode);
checkForFailure(removeResult, REMOVE.toUpperCase(), "WFLYCTL0031");
ModelNode addModelNode = Util.createAddOperation(DEPLOYMENT_PATH.append(SUBSYSTEM_PATH));
ModelNode addResult = controllerClient.execute(addModelNode);
checkForFailure(addResult, ADD.toUpperCase(), "WFLYCTL0031");
}
/**
* Tests the proper behavior for the {@code write-attribute} operation on the JPA subsystem in a deployment.
* The operation should fail since it is unsupported in a deployment's subsystem.
*
* @throws IOException if an error occurs during the {@code ModelNode} execution.
*/
@Test
public void testWriteAttribute() throws IOException {
ModelNode writeAttributeModelNode = Util.getWriteAttributeOperation(DEPLOYMENT_PATH.append(SUBSYSTEM_PATH), DEFAULT_DATASOURCE, "Foobar");
ModelNode writeAttributeResult = controllerClient.execute(writeAttributeModelNode);
checkForFailure(writeAttributeResult, WRITE_ATTRIBUTE_OPERATION.toUpperCase(), "WFLYCTL0048");
}
/**
* Helper method for checking whether the operation failed as expected.
*
* @param modelNode The result of the operation in form of {@code ModelNode}
* @param method The {@code String} representing the operation's name. Used only for the error message purposes.
* @param errorCode The {@code String} representing expected error code in the operation's result.
*/
private void checkForFailure(ModelNode modelNode, String method, String errorCode) {
Assert.assertTrue("The operation '" + method + "' should have failed for the JPA subsystem in a deployment",
modelNode.get(OUTCOME).asString().equals(FAILED));
Assert.assertTrue("The operation '" + method + "' failed due to an unexpected reason",
modelNode.get(FAILURE_DESCRIPTION).asString().contains(errorCode));
}
}
| 8,297 | 53.235294 | 189 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resultstream/ResultStreamTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.resultstream;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Hibernate test using Jakarta Persistence 2.2 API jakarta.persistence.Query#getResultStream
* using {@link ResultStreamTest} bean.
* <p>
* Note that this test uses an extended persistence context, so that the Hibernate session will stay open long enough
* to complete each test. A transaction scoped entity manager would be closed after each Jakarta Transactions transaction completes.
*
* @author Zbyněk Roubalík
* @author Gail Badner
*/
@RunWith(Arquillian.class)
public class ResultStreamTestCase {
private static final String ARCHIVE_NAME = "jpa_resultstreamtest";
@ArquillianResource
private InitialContext iniCtx;
protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName()));
}
protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup(name));
}
@Deployment
public static Archive<?> deploy() {
JavaArchive jar = ShrinkWrap.create( JavaArchive.class, ARCHIVE_NAME + ".jar" );
jar.addClasses(ResultStreamTestCase.class, Ticket.class, ResultStreamTest.class);
jar.addAsManifestResource( ResultStreamTestCase.class.getPackage(), "persistence.xml", "persistence.xml" );
return jar;
}
@Test
public void testCreateQueryRemove() throws Exception {
ResultStreamTest test = lookup( "ResultStreamTest", ResultStreamTest.class );
List<Ticket> tickets = new ArrayList<Ticket>(4);
tickets.add( test.createTicket() );
tickets.add( test.createTicket() );
tickets.add( test.createTicket() );
tickets.add( test.createTicket() );
Stream<Ticket> stream = (Stream<Ticket>) test.getTicketStreamOrderedById();
Iterator<Ticket> ticketIterator = tickets.iterator();
stream.forEach( t -> assertEquals( t.getId(), ticketIterator.next().getId() ) );
test.deleteTickets();
}
}
| 3,748 | 36.868687 | 133 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resultstream/Ticket.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.resultstream;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/**
* Ticket entity class
*
* @author Zbyněk Roubalík
*/
@Entity
public class Ticket {
Long id;
String number;
public Ticket() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long long1) {
id = long1;
}
public String getNumber() {
return number;
}
public void setNumber(String string) {
number = string;
}
}
| 1,706 | 26.095238 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resultstream/ResultStreamTest.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.resultstream;
import java.util.stream.Stream;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.EntityManager;
/**
* Stateful session bean for testing Jakarta Persistence 2.2 API
* jakarta.persistence.Query#getResultStream
*
* @author Gail Badner
*/
@Stateful
public class ResultStreamTest {
@PersistenceContext(unitName = "mypc")
EntityManager em;
public Ticket createTicket() throws Exception {
Ticket t = new Ticket();
t.setNumber("111");
em.persist(t);
return t;
}
@TransactionAttribute(TransactionAttributeType.NEVER)
public Stream getTicketStreamOrderedById() {
return em.createQuery( "select t from Ticket t order by t.id" ).getResultStream();
}
public void deleteTickets() {
em.createQuery( "delete from Ticket" ).executeUpdate();
}
}
| 2,047 | 31 | 90 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/SFSB3LC.java
|
package org.jboss.as.test.integration.jpa.secondlevelcache;
import jakarta.ejb.EJB;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
@Stateless
public class SFSB3LC {
@EJB
private SFSB4LC sfsb4lc;
/**
* Create employee in provided EntityManager
*/
public void createEmployee(String name, String address, int id) {
sfsb4lc.createEmployee(name, address, id);
}
/**
* Performs 2 query calls, first call put entity in the cache and second should hit the cache
*
* @param id Employee's id in the query
*/
public String entityCacheCheck(int id) {
return sfsb4lc.entityCacheCheck(id);
}
/**
* Update employee simulating an intermediate exception in a nested transaction:
* <ul>
* <li>Transaction A, calls transaction B which modifies entity X</li>
* <li>Transaction B gets an application exception with rollback=true, so the transaction rolls back</li>
* <li>Transaction A catches this exception, and calls the same EJB (now Transaction C since it REQUIRES_NEW)</li>
* <li>Transaction C modifies the same record but this time doesn't throw the application exception</li>
* </ul>
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public String testL2CacheWithRollbackAndRetry(int id, String address) {
try {
sfsb4lc.updateEmployeeAddress(id, address, true);
} catch (RollbackException ex) {
try {
sfsb4lc.updateEmployeeAddress(id, address, false);
} catch (Exception e) {
return e.getMessage();
}
}
return "OK";
}
}
| 1,741 | 31.867925 | 118 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import jakarta.persistence.Cacheable;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
/**
* Cachable Employee entity class
*
* @author Scott Marlow
*/
@Entity
@Cacheable(true)
public class Employee {
@Id
private int id;
@ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Company company;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 2,108 | 24.409639 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/JPA2LCTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.management.util.CLIOpResult;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Jakarta Persistence Second level cache tests
*
* @author Scott Marlow and Zbynek Roubalik and Tommaso Borgato
*/
@RunWith(Arquillian.class)
public class JPA2LCTestCase {
private static final String ARCHIVE_NAME = "jpa_SecondLevelCacheTestCase";
private static final String CACHE_REGION_NAME = JPA2LCTestCase.class.getPackage().getName() + '.';;
@Deployment
public static Archive<?> deploy() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar");
jar.addClasses(JPA2LCTestCase.class,
Employee.class,
Company.class,
SFSB1.class,
SFSB2LC.class,
SFSB3LC.class,
SFSB4LC.class,
RollbackException.class
);
jar.addAsManifestResource(JPA2LCTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
return jar;
}
@ArquillianResource
private InitialContext iniCtx;
protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName()));
}
protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup(name));
}
@Test
@InSequence(1)
public void testMultipleNonTXTransactionalEntityManagerInvocations() throws Exception {
SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class);
sfsb1.createEmployee("Kelly Smith", "Watford, England", 1000);
sfsb1.createEmployee("Alex Scott", "London, England", 2000);
sfsb1.getEmployeeNoTX(1000);
sfsb1.getEmployeeNoTX(2000);
DataSource ds = rawLookup("java:jboss/datasources/ExampleDS", DataSource.class);
Connection conn = ds.getConnection();
try {
int deleted = conn.prepareStatement("delete from Employee").executeUpdate();
// verify that delete worked (or test is invalid)
assertTrue("was able to delete added rows. delete count=" + deleted, deleted > 1);
} finally {
conn.close();
}
// read deleted data from second level cache
Employee emp = sfsb1.getEmployeeNoTX(1000);
assertTrue("was able to read deleted database row from second level cache", emp != null);
}
// When caching is disabled, no extra action is done or exception happens
// even if the code marks an entity and/or a query as cacheable
@Test
@InSequence(2)
public void testDisabledCache() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String message = sfsb.disabled2LCCheck();
if (!message.equals("OK")) {
fail(message);
}
}
// When entity caching is enabled, loading all entities at once
// will put all entities in the cache. During the SAME session,
// when looking up for the ID of an entity which was returned by
// the original query, no SQL queries should be executed.
//
// Hibernate ORM 5.3 internally changed from 5.1.
// Infinispan caches are now non-transactional, meaning that the Hibernate first level cache is
// relied on inside of transactions for caching.
// Note from Radim:
// "
// With (5.1) transactional caches, Infinispan was storing the fact that you've
// stored some entities in transactional context and when you attempted to
// read it from cache, it transparently provided the updated data. With
// non-transactional caches the *Infinispan layer* (as opposed to *2LC
// layer*) does not do that. Instead the 2LC provider registers Jakarta Persistence
// synchronization to execute the update if the Jakarta Persistence transaction commits.
// "
//
// In response to this change, the current sameSessionCheck doesn't make sense anymore,
// as the "sameSession" refers to the same persistence context being used for the entire test.
// The same persistence context being used, means that the persistence context first level cache (1lc),
// is used, instead of the 2lc, which leads to emp2LCStats.getElementCountInMemory() being zero, which would
// cause this test to fail.
// Since this test, as currently written, doesn't really test the 2lc, we will ignore it.
@Ignore
@Test
@InSequence(3)
public void testEntityCacheSameSession() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String message = sfsb.sameSessionCheck(CACHE_REGION_NAME);
if (!message.equals("OK")) {
fail(message);
}
}
// When entity caching is enabled, loading all entities at once
// will put all entities in the cache. During the SECOND session,
// when looking up for the ID of an entity which was returned by
// the original query, no SQL queries should be executed.
@Ignore // see comment for testEntityCacheSameSession, ignored for same reason.
@Test
@InSequence(4)
public void testEntityCacheSecondSession() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String message = sfsb.secondSessionCheck(CACHE_REGION_NAME);
if (!message.equals("OK")) {
fail(message);
}
}
// Check if evicting entity second level cache is working as expected
@Ignore // see comment for testEntityCacheSameSession, ignored for same reason.
@Test
@InSequence(5)
public void testEvictEntityCache() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String message = sfsb.addEntitiesAndEvictAll(CACHE_REGION_NAME);
if (!message.equals("OK")) {
fail(message);
}
message = sfsb.evictedEntityCacheCheck(CACHE_REGION_NAME);
if (!message.equals("OK")) {
fail(message);
}
}
// When query caching is enabled, running the same query twice
// without any operations between them will perform SQL queries only once.
@Test
@InSequence(6)
public void testSameQueryTwice() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String id = "1";
String message = sfsb.queryCacheCheck(id);
if (!message.equals("OK")) {
fail(message);
}
}
//When query caching is enabled, running a query to return all entities of a class
// and then adding one entity of such class would invalidate the cache
@Test
@InSequence(7)
public void testInvalidateQuery() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String id = "2";
String message = sfsb.queryCacheCheck(id);
if (!message.equals("OK")) {
fail(message);
}
// invalidate the cache
sfsb.createEmployee("Newman", "Paul", 400);
message = sfsb.queryCacheCheck(id);
if (!message.equals("OK")) {
fail(message);
}
}
// Check if evicting query cache is working as expected
@Test
@InSequence(8)
public void testEvictQueryCache() throws Exception {
SFSB2LC sfsb = lookup("SFSB2LC", SFSB2LC.class);
String id = "3";
String message = sfsb.queryCacheCheck(id);
if (!message.equals("OK")) {
fail(message);
}
// evict query cache
sfsb.evictQueryCache();
message = sfsb.queryCacheCheckIfEmpty(id);
if (!message.equals("OK")) {
fail(message);
}
}
/**
<p>
Check that, when L2 cache is enabled, it does not prevent recovery in separate transactions;
</p>
<p>
Note that all EJB calls are marked with <code>TransactionAttributeType.REQUIRES_NEW</code>;
</p>
<p>
Test sequence:
<ul>
<li>{@link SFSB3LC} calls {@link SFSB4LC}</li>
<li>{@link SFSB4LC} throws and exception</li>
<li>{@link SFSB3LC} intercepts the exception and calls again {@link SFSB4LC} (hence creating a new transaction)</li>
<li>this time {@link SFSB4LC} succeeds and {@link SFSB3LC} should succeed as well</li>
</ul>
</p>
*/
@Test
@InSequence(9)
public void testTransaction() throws Exception {
SFSB3LC sfsb = lookup("SFSB3LC", SFSB3LC.class);
int id = 10_000;
// create entity
sfsb.createEmployee("Gisele Bundchen", "Milan, ITALY", id);
String message = sfsb.entityCacheCheck(id);
if (!message.equals("OK")) {
fail(message);
}
// update entity
message = sfsb.testL2CacheWithRollbackAndRetry(id, "Brookline, Massachusetts (MA), US");
assertEquals("Expected message is OK", "OK", message);
}
/**
* Verify that we can read Cache Region Statistics via cli
*/
@Test
@InSequence(10)
@RunAsClient
public void testStatistics() throws Exception {
CLIWrapper cli = new CLIWrapper(true);
cli.sendLine(String.format("/deployment=%s.jar:read-resource(include-runtime=true,recursive=true)", ARCHIVE_NAME));
CLIOpResult opResult = cli.readAllAsOpResult();
Assert.assertTrue(opResult.isIsOutcomeSuccess());
}
}
| 11,307 | 34.448276 | 129 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/JpaStatisticsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Jakarta Persistence statistics test
*
* @author Scott Marlow
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JpaStatisticsTestCase extends ContainerResourceMgmtTestBase {
private static final String ARCHIVE_NAME = "JpaStatisticsTestCase";
@Deployment
public static Archive<?> deploy() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar");
jar.addClasses(JpaStatisticsTestCase.class,
Employee.class,
Company.class,
SFSB1.class,
SFSB2LC.class
);
jar.addAsManifestResource(JpaStatisticsTestCase.class.getPackage(), "persistence.xml", "persistence.xml");
return jar;
}
@ArquillianResource
private InitialContext iniCtx;
protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName()));
}
protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException {
return interfaceType.cast(iniCtx.lookup(name));
}
@Test
public void testJpaStatistics() throws Exception {
ModelNode op = Util.createOperation(READ_RESOURCE_OPERATION,
PathAddress.pathAddress(DEPLOYMENT, ARCHIVE_NAME + ".jar")
.append(SUBSYSTEM, "jpa")
.append("hibernate-persistence-unit", ARCHIVE_NAME + ".jar#mypc")
);
op.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true);
op.get(ModelDescriptionConstants.RECURSIVE).set(true);
// ensure that the WFLY-10964 regression doesn't occur,
// "org.hibernate.MappingException: Unknown entity: entity-update-count" was being thrown due to
// a bug in the (WildFly) Hibernate integration code. This causes Jakarta Persistence statistics to not be shown
// in WildFly management console.
ModelNode result = executeOperation(op);
Assert.assertFalse("Subsystem is empty (result=" + result+")", result.keys().size() == 0);
}
}
| 4,332 | 39.12037 | 129 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/SFSB4LC.java
|
package org.jboss.as.test.integration.jpa.secondlevelcache;
import org.hibernate.Session;
import org.hibernate.stat.QueryStatistics;
import org.hibernate.stat.Statistics;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.Query;
import static org.junit.Assert.assertEquals;
@Stateless
public class SFSB4LC {
@PersistenceUnit(unitName = "mypc")
EntityManagerFactory emf;
/**
* Create employee in provided EntityManager
*/
public void createEmployee(String name, String address, int id) {
EntityManager em = emf.createEntityManager();
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
try {
em.persist(emp);
em.flush();
} catch (Exception e) {
throw new RuntimeException("transactional failure while persisting employee entity", e);
}
}
/**
* Performs 2 query calls, first call put entity in the cache and second should hit the cache
*
* @param id Employee's id in the query
*/
public String entityCacheCheck(int id) {
// the nextTimestamp from infinispan is "return System.currentTimeMillis()"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return e.getMessage();
}
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
try {
String queryString = "select e from Employee e where e.id = " + id;
QueryStatistics queryStats = stats.getQueryStatistics(queryString);
Query query = em.createQuery(queryString);
query.setHint("org.hibernate.cacheable", true);
// query - this call should fill the cache
query.getResultList();
assertEquals("Expected 1 miss in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheMissCount());
assertEquals("Expected 1 put in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCachePutCount());
assertEquals("Expected no hits in cache" + generateQueryCacheStats(queryStats), 0, queryStats.getCacheHitCount());
// query - second call should hit cache
query.getResultList();
assertEquals("Expected 1 hit in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheHitCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Update Employee's address
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateEmployeeAddress(int id, String address, boolean fail) {
EntityManager em = emf.createEntityManager();
Employee emp = em.find(Employee.class, id);
emp.setAddress(address);
em.merge(emp);
em.flush();
if (fail) {
// Asked to fail...throwing exception for rollback
throw new RollbackException();
}
}
/**
* Generate query cache statistics for put, hit and miss count as one String
*/
public String generateQueryCacheStats(QueryStatistics stats) {
String result = "(hitCount=" + stats.getCacheHitCount()
+ ", missCount=" + stats.getCacheMissCount()
+ ", putCount=" + stats.getCachePutCount() + ").";
return result;
}
}
| 3,804 | 32.672566 | 126 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/SFSB1.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import jakarta.ejb.Stateful;
import jakarta.persistence.EntityManager;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceContext;
/**
* stateful session bean
*
* @author Scott Marlow
*/
@Stateful
public class SFSB1 {
@PersistenceContext(unitName = "mypc2")
EntityManager em;
public void createEmployee(String name, String address, int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
em.persist(emp);
}
public Employee getEmployeeNoTX(int id) {
return em.find(Employee.class, id, LockModeType.NONE);
}
}
| 1,745 | 31.943396 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/SFSB2LC.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.Query;
import org.hibernate.Session;
import org.hibernate.stat.CacheRegionStatistics;
import org.hibernate.stat.QueryStatistics;
import org.hibernate.stat.Statistics;
/**
* SFSB for Second level cache tests
*
* @author Zbynek Roubalik
*/
@Stateful
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SFSB2LC {
@PersistenceUnit(unitName = "mypc")
EntityManagerFactory emf;
@PersistenceUnit(unitName = "mypc_no_2lc")
EntityManagerFactory emfNo2LC;
/**
* Check if disabling 2LC works as expected
*/
public String disabled2LCCheck() {
EntityManager em = emfNo2LC.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
try {
// check if entities are NOT cached in 2LC
String[] names = stats.getSecondLevelCacheRegionNames();
assertEquals("There aren't any 2LC regions.", 0, names.length);
createEmployee(em, "Martin", "Prague 132", 1);
assertEquals("There aren't any puts in the 2LC.", 0, stats.getSecondLevelCachePutCount());
// check if queries are NOT cached in 2LC
Employee emp = getEmployeeQuery(em, 1);
assertNotNull("Employee returned", emp);
assertEquals("There aren't any query puts in the 2LC.", 0, stats.getQueryCachePutCount());
// cleanup
em.remove(emp);
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Checking entity 2LC in one EntityManager session
* TODO: rewrite to separate transaction used to createEmployee, and either load entities outside tx or
* start new tx for loading entities. Maybe simplest to have calling code, handle creating the Employees first.
* TODO: need conclusion to discussion about whether createEmployee should cause 2lc PutCount to be incremented,
* as no data is loaded into the cache.
*/
public String sameSessionCheck(String CACHE_REGION_NAME) {
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics emp2LCStats = stats.getDomainDataRegionStatistics(CACHE_REGION_NAME + "Employee");
try {
// add new entities and check if they are put in 2LC
createEmployee(em, "Peter", "Ostrava", 2);
createEmployee(em, "Tom", "Brno", 3);
assertEquals("There are 2 puts in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getPutCount());
// loading all Employee entities should put in 2LC all Employee
List<?> empList = getAllEmployeesQuery(em);
assertEquals("There are 2 entities.", empList.size(), 2);
assertEquals("There are 2 entities in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getElementCountInMemory());
// clear session
em.clear();
// entity should be loaded from 2L cache, we'are expecting hit in 2L cache
Employee emp = getEmployee(em, 2);
assertNotNull("Employee returned", emp);
assertEquals("Expected 1 hit in cache" + generateEntityCacheStats(emp2LCStats), 1, emp2LCStats.getHitCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Checking entity 2LC in a different EntityManager session
*/
public String secondSessionCheck(String CACHE_REGION_NAME) {
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics emp2LCStats = stats.getDomainDataRegionStatistics(CACHE_REGION_NAME + "Employee");
try {
// add new entity
createEmployee(em, "David", "Praha", 10);
assertEquals("There is 1 put in the 2LC" + generateEntityCacheStats(emp2LCStats), 1, emp2LCStats.getPutCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
EntityManager em2 = emf.createEntityManager();
try {
// loading entity stored in previous session, we'are expecting hit in cache
Employee emp = getEmployee(em2, 10);
assertNotNull("Employee returned", emp);
assertEquals("Expected 1 hit in 2LC" + generateEntityCacheStats(emp2LCStats), 1, emp2LCStats.getHitCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em2.close();
}
return "OK";
}
/**
* Insert 2 entities and put them into the 2LC and then evicts entity cache.
*/
public String addEntitiesAndEvictAll(String CACHE_REGION_NAME) {
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics emp2LCStats = stats.getDomainDataRegionStatistics(CACHE_REGION_NAME + "Employee");
try {
createEmployee(em, "Jan", "Ostrava", 20);
createEmployee(em, "Martin", "Brno", 30);
assertEquals("There are 2 puts in the 2LC" + generateEntityCacheStats(emp2LCStats), 2, emp2LCStats.getPutCount());
assertTrue("Expected entities stored in the cache" + generateEntityCacheStats(emp2LCStats), emp2LCStats.getElementCountInMemory() > 0);
// evict entity 2lc
emf.getCache().evictAll();
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Checks if entity 2LC is empty.
*/
public String evictedEntityCacheCheck(String CACHE_REGION_NAME) {
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
CacheRegionStatistics emp2LCStats = stats.getDomainDataRegionStatistics(CACHE_REGION_NAME + "Employee");
try {
assertEquals("Expected no entities stored in the cache" + emp2LCStats, 0, emp2LCStats.getElementCountInMemory());
// loading entity stored in previous session, we are expecting miss in 2lc
Employee emp = getEmployee(em, 20);
assertNotNull("Employee returned", emp);
assertEquals("Expected 1 miss in 2LC" + generateEntityCacheStats(emp2LCStats), 1, emp2LCStats.getMissCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Performs 2 query calls, first call put query in the cache and second should hit the cache
*
* @param id Employee's id in the query
*/
public String queryCacheCheck(String id) {
// the nextTimestamp from infinispan is "return System.currentTimeMillis()"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return e.getMessage();
}
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
try {
String queryString = "select e from Employee e where e.id > " + id;
QueryStatistics queryStats = stats.getQueryStatistics(queryString);
Query query = em.createQuery(queryString);
query.setHint("org.hibernate.cacheable", true);
// query - this call should fill the cache
query.getResultList();
assertEquals("Expected 1 miss in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheMissCount());
assertEquals("Expected 1 put in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCachePutCount());
assertEquals("Expected no hits in cache" + generateQueryCacheStats(queryStats), 0, queryStats.getCacheHitCount());
// query - second call should hit cache
query.getResultList();
assertEquals("Expected 1 hit in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheHitCount());
} catch (AssertionError e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Evicts all query cache regions
*/
public void evictQueryCache() {
EntityManager em = emf.createEntityManager();
try {
// this should evict query cache
em.unwrap(Session.class).getSessionFactory().getCache().evictDefaultQueryRegion();
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
/**
* Checking if query cache is empty
*
* @param id Employee's id in the query
*/
public String queryCacheCheckIfEmpty(String id) {
EntityManager em = emf.createEntityManager();
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
try {
// the nextTimestamp from infinispan is "return System.currentTimeMillis() / 100;"
Thread.sleep(1000);
String queryString = "select e from Employee e where e.id > " + id;
QueryStatistics queryStats = stats.getQueryStatistics(queryString);
Query query = em.createQuery(queryString);
query.setHint("org.hibernate.cacheable", true);
// query - this call shouldn't hit the cache -> query cache is empty
query.getResultList();
assertEquals("Expected 1 miss in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCacheMissCount());
assertEquals("Expected 1 put in cache" + generateQueryCacheStats(queryStats), 1, queryStats.getCachePutCount());
assertEquals("Expected no hits in cache" + generateQueryCacheStats(queryStats), 0, queryStats.getCacheHitCount());
} catch (AssertionError e) {
return e.getMessage();
} catch (InterruptedException e) {
return e.getMessage();
} finally {
em.close();
}
return "OK";
}
/**
* Generate query cache statistics for put, hit and miss count as one String
*/
public String generateQueryCacheStats(QueryStatistics stats) {
String result = "(hitCount=" + stats.getCacheHitCount()
+ ", missCount=" + stats.getCacheMissCount()
+ ", putCount=" + stats.getCachePutCount() + ").";
return result;
}
/**
* Generate entity cache statistics for put, hit and miss count as one String
*/
public String generateEntityCacheStats(CacheRegionStatistics stats) {
String result = "(hitCount=" + stats.getHitCount()
+ ", missCount=" + stats.getMissCount()
+ ", putCount=" + stats.getPutCount() + ").";
return result;
}
public String getCacheRegionName() {
return (String) emf.getProperties().get("hibernate.cache.region_prefix");
}
/**
* Create employee in provided EntityManager
*/
public void createEmployee(EntityManager em, String name, String address,
int id) {
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
try {
em.persist(emp);
em.flush();
} catch (Exception e) {
throw new RuntimeException("transactional failure while persisting employee entity", e);
}
}
/**
* Create employee in provided EntityManager
*/
public void createEmployee(String name, String address,
int id) {
EntityManager em = emf.createEntityManager();
Employee emp = new Employee();
emp.setId(id);
emp.setAddress(address);
emp.setName(name);
try {
em.persist(emp);
} catch (Exception e) {
throw new RuntimeException("transactional failure while persisting employee entity", e);
} finally {
em.close();
}
}
/**
* Load employee from provided EntityManager
*/
public Employee getEmployee(EntityManager em, int id) {
Employee emp = em.find(Employee.class, id);
return emp;
}
/**
* Load employee using Query from provided EntityManager
*/
public Employee getEmployeeQuery(EntityManager em, int id) {
Query query;
query = em.createQuery("select e from Employee e where e.id=:id");
query.setParameter("id", id);
query.setHint("org.hibernate.cacheable", true);
return (Employee) query.getSingleResult();
}
/**
* Load all employees using Query from provided EntityManager
*/
@SuppressWarnings("unchecked")
public List<Employee> getAllEmployeesQuery(EntityManager em) {
Query query;
query = em.createQuery("select e from Employee e");
query.setHint("org.hibernate.cacheable", true);
return query.getResultList();
}
}
| 15,168 | 33.475 | 147 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/RollbackException.java
|
package org.jboss.as.test.integration.jpa.secondlevelcache;
import jakarta.ejb.ApplicationException;
@ApplicationException(rollback = true)
public class RollbackException extends RuntimeException {
private static final long serialVersionUID = 2967914874533141967L;
}
| 275 | 24.090909 | 70 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/secondlevelcache/Company.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.secondlevelcache;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.Cacheable;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
/**
* Company
*
* @author Scott Marlow
*/
@Entity
@Cacheable(true)
public class Company {
@Id
@GeneratedValue
public Integer id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<Employee> employees = new HashSet<>();
public Integer getId() {
return id;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
| 1,912 | 29.365079 | 71 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/sibling/Employee.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jpa.sibling;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* Employee entity class
*
* @author Scott Marlow
*/
@Entity
public class Employee {
@Id
private int id;
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 1,711 | 24.552239 | 70 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.