Arquillian testing on remote server - java

I want to test my war file on remote server but it is not working and giving me error:
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream cannot be cast to com.itextpdf.text.pdf.codec.Base64$InputStream
I dont know what i am doing wrong.I am new to arquillian and have checked almost all the links available but still not got any solution over this..
Here is my arquillian.xml
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<!-- Uncomment to have test archives exported to the file system for inspection -->
<!-- <engine> -->
<!-- <property name="deploymentExportPath">target/</property> -->
<!-- </engine> -->
<!-- Force the use of the Servlet 3.0 protocol with all containers, as it
is the most mature -->
<defaultProtocol type="Servlet 3.0" />
<!-- Example configuration for a remote JBoss EAP 6 instance -->
<container qualifier="jboss" default="true">
<!-- By default, arquillian will use the JBOSS_HOME environment variable.
Alternatively, the configuration below can be uncommented. -->
<configuration>
<!-- <property name="jbossHome">/opt/jboss7</property> --> <!-- <property name="managementAddress">197.242.148.253</property> <property
name="managementPort">22000</property> <property name="username"></property>
<property name="password"></property> -->
<property name="managementAddress">197.242.148.253</property>
<property name="managementPort">22000</property>
<property name="username">abc</property>
<property name="password">aabc123</property>
</configuration>
</container>
</arquillian>
This is my test class
public class ArqTest extends Arquillian{
//creates war and deploys it
#Deployment(testable = true)
public static WebArchive createNotTestableDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "USSD.war")
.addClasses(ShowConversations.class)
.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
System.out.println("deployed");
System.out.println(war.getName());
return war;
}
#RunAsClient
#Test(dataProvider = Arquillian.ARQUILLIAN_DATA_PROVIDER)
public void Test() throws IOException {
URL url = new URL("http://197.242.148.253");
InputStream is = (InputStream) url.openStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(is));
String result = br.readLine();
System.out.println(result+"hello");
br.close();
}
}
Can any body provide me some help over this

Try to add at the configuration node the next property:
<property name="allowConnectingToRunningServer">true</property>
Dunno if this will solve your error but I think you need it because, if not, arquillian tries to create a new jBoss instance instead of using the remote running one.

Related

No Persistence provider for EntityManager named- when try to deploy from weblogic console

I'm struggling for a few days about this error.
When I try to deploy from ide(IntelliJ-eclipse), it works correct.
But when I try to deploy from WebLogic console, I got these errors;
Error Unable to access the selected application.
Error Unable to invoke Annotation processoror.
Error Unable to invoke Annotation processoror.
For more information, I checked logs and errors from stack trace.
It looks like the main error is: javax.persistence.PersistenceException: No Persistence provider for EntityManager named.
In debug, throwing from this code; Persistence.createEntityManagerFactory("persistanceUnitName");
Persistence classes are coming from javaee-web-abi-7.0.jar.
Everything looks fine in persistence.xml.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistanceUnitName"
transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>dataSource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.logging.parameters" value="true" />
<property name="eclipselink.logging.logger" value="DefaultLogger" />
<property name="eclipselink.logging.level" value="WARNING" />
<property name="eclipselink.refresh" value="true" />
<property name="eclipselink.query-results-cache" value="false" />
<!-- <property name="eclipselink.ddl-generation" value="create-or-extend-tables" />-->
</properties>
</persistence-unit>
</persistence>
persistance.xml located in /WEB-INF/classes/META-INF
We got a case like that: we have a test and prep environment. In test, it works, in prep doesn't work, in local doesn't work (from WebLogic console). Unfortunately, I can't see test server configs. But I expect the same options with prep. Anyway forget other environments, firstly I need to deploy successful from local.
Could you pls help me, I really don't know what I miss. Read every topic, tried everything
It looks like a classpath issue. Check your weblogic classpath.
If you are using eclipselink library must be loaded first when you are deploying.
Check this.
Add eclipselink into your project with scope provided:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
<scope>provided<scope>
</dependency>
add same dependency into your weblogic classpath:
$WEBLOGIC_HOME/user_projects/domains/base_domain/lib
Then, add below to your weblogic.xml to use eclipselink library.
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>org.eclipse.persistence.*</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>

how to integrate cache2k with hibernate

How i can integrate cache2k like hibernate cache provider?
I mean in current project we use ehcache and
enable cache in next configuration hibernate.cfg.xml :
<hibernate-configuration>
<session-factory>
<!-- Cache Configurations -->
<!-- Using net.sf.ehcache.hibernate.SingletonEhCacheProvider instead of
net.sf.ehcache.hibernate.EhCacheProvider ensures the same instance
of CacheManager is referred to by both Hibernate and our JMX Agent
simpleJpaHibernateApp.agents.jmxAgent. -->
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>
<!-- <property name="hibernate.cache.provider_configuration">/ehcache.cfg.xml</property> -->
<property name="hibernate.cache.use_minimal_puts">false</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_structured_entries">true</property>
</session-factory>
As well we use Cache manager class:
public class AppCacheManager {
private static final Logger log = LoggerFactory.getLogger(AppCacheManager.class);
private static CacheManager manager;
#SuppressWarnings("unused")
private static AppCacheManager INSTANCE = new AppCacheManager();
private AppCacheManager() {
manager = CacheManager.getInstance();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);
if (log.isInfoEnabled()) {
log.info("Cache Manager was initialized.");
log.info("Cache Regions Detected:");
String[] cacheNames = manager.getCacheNames();
for (String cacheName : cacheNames) {
log.info(" " + cacheName);
}
log.info("Cache disk store path: " + manager.getDiskStorePath());
}
}
Can i replace in hibernate-configuration net.sf.ehcache.hibernate.SingletonEhCacheProvider with some cache2k impl?
And how i should adopt AppCacheManager base on cache2k ?
Thank you!
You can use cache2k with hibernate without any additional code.
You need to add the following dependencies in your project:
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-all</artifactId>
<version>${cache2k-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-jcache</artifactId>
<version>${cache2k-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.0</version>
</dependency>
The hibernate configuration needs to contain:
<hibernate-configuration>
<session-factory>
<property name="cache.region.factory_class">org.hibernate.cache.jcache.JCacheRegionFactory</property>
<property name="hibernate.javax.cache.provider">org.cache2k.jcache.provider.JCacheProvider</property>
<property name="hibernate.javax.cache.uri">hibernate</property>
<!-- .... rest of configuration .... -->
</session-factory>
</hibernate-configuration>
You can then add a file cache2k-hibernate.xml to the classpath which allows further configuration of the caches, for example:
<cache2k>
<version>1.0</version>
<!-- if enabled cache2k does not refuse operation in case there is
no configuration for a requested cache name -->
<ignoreMissingCacheConfiguration>true</ignoreMissingCacheConfiguration>
<defaults>
<!-- default settings for every cache -->
<cache>
<entryCapacity>100_000</entryCapacity>
</cache>
</defaults>
<caches>
<!-- reduced size for the query cache -->
<cache>
<name>org.hibernate.cache.internal.StandardQueryCache</name>
<entryCapacity>100</entryCapacity>
</cache>
</caches>
</cache2k>

Arquillian and wildfly 10 - Cannot undeploy: 144976d2-382b-438f-8b8a-2007db7b53c2.war

I'm running integration tests from MVN with Wildfly 10 and Arquilliain. I get the following error:
WARN ArchiveDeployer - Cannot undeploy:
144976d2-382b-438f-8b8a-2007db7b53c2.war
org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper$ServerDeploymentException:
java.lang.Exception: "WFLYCTL0216: Management resource
'[(\"deployment\" => \"144976d2-382b-438f-8b8a-2007db7b53c2.war\")]'
not found" at
org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper.undeploy(ServerDeploymentHelper.java:114)
at
org.jboss.as.arquillian.container.ArchiveDeployer.undeploy(ArchiveDeployer.java:55)
at
org.jboss.as.arquillian.container.CommonDeployableContainer.undeploy(CommonDeployableContainer.java:152)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController$4.call(ContainerDeployController.java:205)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController$4.call(ContainerDeployController.java:185)
at
org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
Here's my Arquillian (identical to another project that works, so I don't think this is the issue, all the ports are right):
<?xml version="1.0" ?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://jboss.org/schema/arquillian"
xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<engine>
<property name="deploymentExportPath">target</property>
</engine>
<!--
<container qualifier="wildfly-managed" default="true">
<configuration>
<!– <property name="serverConfig">standalone.xml</property> Does not work, use -DjbossHome=.....–>
<property name="outputToConsole">true</property>
<property name="javaVmArguments">-Djboss.socket.binding.port-offset=100</property>
<property name="managementPort">10090</property>
</configuration>
</container>
-->
<container qualifier="wildfly-remote" default="true">
<protocol type="Servlet 3.0">
<property name="host">192.168.3.70</property>
<property name="port">8180</property>
</protocol>
<configuration>
<property name="managementPort">10090</property>
<property name="username">mike</property>
<property name="password">mike</property>
<property name="managementAddress">192.168.3.70</property>
</configuration>
</container>
<extension qualifier="transaction">
<property name="manager">java:jboss/UserTransaction</property>
</extension>
</arquillian>
My deployment is built like so:
#Deployment
public static WebArchive createDeployment() {
WebArchive wa = ShrinkWrap.create(WebArchive.class).addPackage(Baby.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsManifestResource("jboss-deployment-structure.xml", "jboss-deployment-structure.xml")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsResource("arquillian.xml", "arquillian.xml").addAsResource("log4j.xml", "log4j.xml")
.addAsLibrary(Maven.resolver().loadPomFromFile("pom.xml").resolve("joda-time:joda-time:2.9.3")
.withTransitivity().asSingleFile())
.addAsLibraries((Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:2.7.4").withTransitivity()
.asFile()));
The app works fine, and if I launch it as a managed container on a local WF installation it works. For some reason, the remote container is failing.
Any ideas?
EDIT:
I also added this to web.xml and it did not change the issue:
<context-param>
<param-name>antiJARLocking</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>antiResourceLocking</param-name>
<param-value>true</param-value>
</context-param>

Inject EntityManagerFactory using #PersistenceUnit on Jersey with Wildfly

I'm trying to inject EntityManagerFactory using #PersistenceUnit, but it's always null.
I think my persistence.xml is OK, since I can get the EntityManager with this code:
EntityManager em = Persistence.createEntityManagerFactory("myPersistenceUnit").createEntityManager();
So, I would like to know if I'm doing something wrong, or if this is not possible when using Jersey (2.23) and Wildfly 10 (JBoss EAP 7).
Here is what I've done so far:
Created a jersey-quickstart-webapp maven project on eclipse;
Added the following dependencies to my pom.xml:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>oracle-driver-ojdbc6</artifactId>
<version>12.1.0.1</version>
</dependency>
Created the persistence.xml:
<persistence-unit name="myPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- All persistence classes must be listed -->
<class>com.mps.classes.TermosPesquisados</class>
<properties>
<!-- Provider-specific connection properties -->
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="JDBC_URL" />
<property name="javax.persistence.jdbc.user" value="USER" />
<property name="javax.persistence.jdbc.password" value="PASSWORD" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.connection.release_mode" value="after_transaction" />
<property name="hibernate.connection.isolation" value="2" />
</properties>
</persistence-unit>
Modified the MyResource.java:
#ManagedBean
#Path("myresource")
public class MyResource {
#PersistenceUnit(unitName= "myPersistenceUnit")
private EntityManagerFactory emf;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
if(emf == null)
return "emf is null";
return "emf is not null";
}
}
Added an empty beans.xml (not sure if it's necessary);
It seems that Jersey conflicts with Resteasy. This way, I had 2 options:
Turn-off Resteasy on JBoss/Wildfly (I know that's possible, but I don't know how);
Remove Jersey and use Resteasy instead;
I ended up choosing the 2nd option because it was easier and I have no reasons to use specifically Jersey.
This way, I had to change my web.xml, replacing this:
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
...
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
For this:
<servlet-name>javax.ws.rs.core.Application</servlet-name>
...
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
*Another option was to create a class extending Application class.
*beans.xml was not necessary.
Then, I annotated my resource class with #Stateless and I was able to inject EntityManager properly:
#Path("myresource")
#Stateless
public class MyResource {
#PersistenceContext(unitName="myPersistenceUnit")
private EntityManager em;
...
At this point, EntityManager was OK, but somehow it was using JBoss h2 in-memmory database (ExampleDS).
So, I configured an oracle datasource on JBoss (OracleDS) and updated my persistence.xml to use OracleDS and JTA instead of "RESOURCE_LOCAL":
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:jboss/datasources/OracleDS</jta-data-source>
...
With those steps I was able to inject EntityManager and make my CRUD operations successfully.
There is no point for a #ManagedBean annotation here, this is a JSF annotation and I according to your code you're trying to expose a REST layer.
Just remove it and all will be fine (also ensure that you have a beans.xml in your classpath to enable CDI, otherwise annotate your class with #Stateless)
I think Entity manager should be enough :
#PersistenceUnit(unitName= "myPersistenceUnit")
private EntityManager em;

No autodetection of JPA Entities in maven-verify

If I put the persistence.xml in the src/test/META-INF folder, autodetection the Entities does not work with maven-verify. When the persistence.xml is located in the src/main/META-INF folder it works.
Running the tests in eclipse works in both cases.
Is there a way to get autodetection to work for maven-verify when the persistence.xml is located in the src/test Folder?
persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="Unit" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- Scan for annotated classes and Hibernate mapping XML files -->
<property name="hibernate.archive.autodetection" value="class" />
</properties>
</persistence-unit>
</persistence>
By default autodetection works for entities in the same classpath item as persistence.xml. It can be configured by <jar-file> elements.
To enable correct autodetection when persistence.xml is in src/test/resources/META-INF I use the following trick:
persistence.xml:
<persistence ...>
<persistence-unit ...>
<jar-file>${project.build.outputDirectory}</jar-file>
...
</persistence-unit>
</persistence>
pom.xml - enable resource filtering for src/test/resources:
<project ...>
...
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
</project>
Though I'm not sure how to use it if your persistence.xml is actually in src/test/META-INF.
If you use Spring Framework you can do the following with a PersistenceUnitPostProcessor
CustomPersistenceUnitPostProcessor:
package com.yourpackage.utils.jpa.CustomPersistenceUnitPostProcessor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import net.sourceforge.stripes.util.ResolverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;
/**
* This PersistenceUnitPostProcessor is used to search given package list for JPA
* entities and add them as managed entities. By default the JPA engine searches
* for persistent classes only in the same class-path of the location of the
* persistence.xml file. When running unit tests the entities end up in test-classes
* folder which does not get scanned. To avoid specifying each entity in the persistence.xml
* file to scan, this post processor automatically adds the entities for you.
*
*/
public class CustomPersistenceUnitPostProcessor implements PersistenceUnitPostProcessor, InitializingBean {
private static final Logger log = LoggerFactory.getLogger(CustomPersistenceUnitPostProcessor.class);
/** the path of packages to search for persistent classes (e.g. org.springframework). Subpackages will be visited, too */
private List<String> packages;
/** the calculated list of additional persistent classes */
private Set<Class<? extends Object>> persistentClasses;
/**
* Looks for any persistent class in the class-path under the specified packages
*/
#Override
public void afterPropertiesSet() throws Exception {
if (packages == null || packages.isEmpty())
throw new IllegalArgumentException("packages property must be set");
log.debug("Looking for #Entity in " + packages);
persistentClasses = new HashSet<Class<? extends Object>>();
for (String p : packages) {
ResolverUtil<Object> resolver = new ResolverUtil<Object>();
ClassLoader cl = this.getClass().getClassLoader();
log.debug("Using classloader: " + cl);
resolver.setClassLoader(cl);
resolver.findAnnotated(Entity.class, p);
Set<Class<? extends Object>> classes = resolver.getClasses();
log.debug("Annotated classes: " + classes);
persistentClasses.addAll(classes);
}
if (persistentClasses.isEmpty())
throw new IllegalArgumentException("No class annotated with #Entity found in: " + packages);
}
/**
* Add all the persistent classes found to the PersistentUnit
*/
#Override
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo persistenceUnitInfo) {
for (Class<? extends Object> c : persistentClasses)
persistenceUnitInfo.addManagedClassName(c.getName());
}
public void setPackages(List<String> packages) {
this.packages = packages;
}
}
Spring Config:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="thePersistenceUnitName" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<!-- reference to the XA datasource -->
<property name="dataSource" ref="theDataSource" />
<property name="persistenceUnitPostProcessors">
<list>
<!-- custom implementation to avoid xml entity class declarations -->
<bean class="com.yourpackage.utils.jpa.CustomPersistenceUnitPostProcessor">
<property name="packages">
<list value-type="java.lang.String">
<value>com.yourpackage.model</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?> <persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="thePersistenceUnitName" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.use_sql_comments" value="false" />
<property name="hibernate.generate_ddl" value="false" />
<property name="hibernate.database_platform" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
</persistence-unit>
</persistence>

Categories

Resources