I'm new to using Hibernate with Java. I'm getting the following exception. The stuff that I found online regarding this error didn't seem to help. Any ideas? The Exception:
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException:
ApplPerfStats is not mapped [select count(c) from ApplPerfStats c]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:601)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)
at com.icesoft.icefaces.samples.datatable.jpa.CustomerDAO.findTotalNumberCustomers(CustomerDAO.java:89)
at com.icesoft.icefaces.samples.datatable.ui.SessionBean.getDataPage(SessionBean.java:189)
at com.icesoft.icefaces.samples.datatable.ui.SessionBean.access$0(SessionBean.java:185)
at com.icesoft.icefaces.samples.datatable.ui.SessionBean$LocalDataModel.fetchPage(SessionBean.java:245)
at com.icesoft.icefaces.samples.datatable.ui.PagedListDataModel.getPage(PagedListDataModel.java:121)
at com.icesoft.icefaces.samples.datatable.ui.PagedListDataModel.getRowCount(PagedListDataModel.java:100)
at com.icesoft.faces.component.datapaginator.DataPaginator.isModelResultSet(DataPaginator.java:1091)
at com.icesoft.faces.component.datapaginator.DataPaginatorRenderer.encodeBegin(DataPaginatorRenderer.java:201)
The place where this is called:
#SuppressWarnings("unchecked")
public Long findTotalNumberCustomers() {
EntityManagerHelper.log("finding number of Customer instances", Level.INFO, null);
try {
String queryString = "select count(c) from ApplPerfStats c";
return (Long) getEntityManager().createQuery(queryString).getSingleResult();
} catch (RuntimeException re) {
EntityManagerHelper.log("find number of Appl_perf_stats failed",
Level.SEVERE, re);
throw re;
}
}
The class that maps to the database table:
package com.icesoft.icefaces.samples.datatable.jpa;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Appl_perf_stats", uniqueConstraints = {})
public class ApplPerfStats implements java.io.Serializable {
.....
Thanks,
Tam
Try adding a class element under persistence-unit, in your persistence.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="unit">
<class>com.icesoft.icefaces.samples.datatable.jpa.ApplPerfStats</class>
...
</persistence-unit>
<persistence>
I haven't done much more than that with JPA/EntityManager, so I don't know if there's a way to add an entire package. AFAIK, when using hibernate.cfg.xml, each persistent class has to be specified directly.
It happened to me until I started to use the full class name, e.g.:
String queryString = "select count(c) from com.my.classes.package.ApplPerfStats c";
But I don't like this approach, because it's refactoring-unfirendly. A more tractable one would be:
String queryString = "select count(c) from " + ApplPerfStats.class.getName() + c";
javashlook's solution seems to be a shortcut for that - but it adds more XML configuration, which I try to avoid. If only there was an annotation-based way to specify that...
I was having the same problem and I solved by adding aspectj entries to my pom.xml see below. I guess it makes sense if you are using annotations. Otherwise you need to specify the mappings in the XML file. I had this problem from a project that was using a jar with JPA annotations.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.2</version> <!-- NB: do use 1.3 or 1.3.x due to MASPECTJ-90 - wait for 1.4 -->
<dependencies>
<!-- NB: You must use Maven 2.0.9 or above or these are ignored (see MNG-2972) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<configuration>
<weaveDependencies>
<weaveDependency> <groupId>your.project</groupId> <artifactId>your.artifact</artifactId> </weaveDependency>
</weaveDependencies>
</configuration>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
You should specify a column to do the count on
select count(c.someColumn) from ApplPerfStats c
Or try a count(*)
select count(*) from ApplPerfStats c
I faced this issue but in my case the problem was due to gradle version.
When I changed my system from linux to mac then I had to switch from gradle-1.0-milestone-3 to gradle-1.0-milestone-4 as milestone-3 does not work in OSX. And in gradle-1.0-milestone-4 I faced the same issue then I had to degrade my gradle version to gradle-1.0-milestone-1. Now it is working fine
I was also face this problem fixed by this ...
You haven't declared your entity classes in persistence.xml config file:
<property name="hibernate.archive.autodetection" value="class, hbm"/>
I know it has been a long time on this matter, but none of the above answers solved my problem.
I had already declared the entity in the persistence.xml file.
At the end the whole problem was simply that the name of the entity is case sensitive on my system.
This jpql was wrong
SELECT u FROM user u WHERE userId = 1?
But this one works fine
SELECT u FROM User u WHERE userId = 1?
Related
My project builds successfully with groovy-eclipse-compiler, but fails without groovy-eclipse-compiler (using just javac). The build fails with an error message as given below (reported in a test class, while mocking an invocation)
java: reference to getFileResource is ambiguous
In order to debug the issue, I created a project with minimal files (given below). Though in project we have groovy source also, but I have not included them here to keep the code minimal.
The code is also pushed to git and is available at https://github.com/kaushalkumar/project-debug
My Doubt: The reported issue looks to be legitimate and I feel that groovy-eclipse-compiler must also fail, but it seems that the error is ignored. I am trying to understand what make groovy compiler to ignore it. Is it an issue in groovy compiler?
src/main/java/pkg1/IStrategy.java
package pkg1;
import java.util.Map;
public interface IStrategy {
Map<String, Object> getEnvMap();
}
src/main/java/pkg1/SharedResourceHelper.java
package pkg1;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class SharedResourceHelper {
public static File getFileResource(final String resourceName, final IStrategy strategy) throws IOException {
return getFileResource(resourceName, strategy.getEnvMap());
}
public static File getFileResource(final String resourceName, final Map<String, Object> envConfig) throws IOException {
return null;
}
}
src/test/java/pkg1/StrategyTest.java
package pkg1;
import pkg1.SharedResourceHelper;
import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.junit.Test;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.runner.RunWith;
import java.io.File;
#PrepareForTest({SharedResourceHelper.class})
#RunWith(PowerMockRunner.class)
public class StrategyTest {
#Test
#PrepareForTest({SharedResourceHelper.class})
public void testGetFileResource() throws Exception {
PowerMock.mockStatic(SharedResourceHelper.class);
EasyMock.expect(SharedResourceHelper.getFileResource(EasyMock.anyString(), EasyMock.anyObject())).andReturn(File.createTempFile("tmp", "s"));
// EasyMock.expect(SharedResourceHelper.getFileResource("test", null)).andReturn(File.createTempFile("tmp", "s"));
}
}
/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>project.debug</groupId>
<artifactId>project</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<source>1.8</source>
<target>1.8</target>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.9.2-01</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>2.4.3-01</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Java version - 1.8.0_231
Maven - 3.6.2
OS - Mac 10.15.6
groovy-eclipse-compiler - 2.9.2-01
groovy-eclipse-batch - 2.4.3-01
You reference "SharedResourceHelper.getFileResource(EasyMock.anyString(), EasyMock.anyObject())" is indeed ambiguous. If you add a typecast before "EasyMock.anyObject()" you could disambiguate. And EasyMock probably provides an "any" method that you can pass a type into as well.
groovy-eclipse-compiler is based upon ecj (eclipse compiler for java) and not javac, so there are bound to be differences. It may also be that ecj has a different default error/warning level for this particular case. If you feel this should be an error, you can file a JDT bug at bugs.eclipse.org.
eric-milles gave some direction to further explore this. His input is available at https://github.com/groovy/groovy-eclipse/issues/1157.
Based on his comment, we explored the history of https://github.com/groovy/groovy-eclipse/blob/master/extras/groovy-eclipse-batch-builder/build.properties and found that the compilation issue was between 2.4.12-01 (compilation works) and 2.4.12-02 (compilation breaks- as expected), which was part of release 2.9.2.
The change happened on Aug 10, 2017 (13c1c2a#diff-c8c111c3afb6080ae6b32148caaf6a0a), with comment as "Remove codehaus references". The jdt.patch.target was targeted for e44 which is Luna. This was same for both the files.
I invested some time in exploring https://github.com/eclipse/eclipse.jdt.core, to figure out how compiler behaviour could have altered, but could not get much. Though I am not very sure, but I feel that change in groovy-eclipse-batch (between 2.4.12-01 and 2.4.12-02) might be the cause of this.
Having invested this much time, I feel that it is not worth to further debug on this to figure out the root cause as the issue is already fixed in next version(s) [2.4.12-02 and beyond].
I have a Maven jar project that creates a SOAP client using cxf-codegen-plugin.
In an another Maven project using that client it is simply needed to persist instance of a data class (some soap response) - generated by cxf-codegen-plugin - with JPA (currently using OpenJPA).
It might be possible with some configuration stuff - for example - after each client source code generation to add #Entity annotation to data class before compiling/enhancing and installing the client jar but I'd like to get rid of this phase while still keeping the client as generic as possible. Projects using client should just be able to safely assume that the class is persistence capable.
Best way to handle this might be some tricks in client project settings (currently using openjpa-maven-plugin for enhancing data classes) to detect desired classes and somehow make them persistence capable plus enhance those.
I'd rather skip stuff like maintaining beans.xml and stick to the annotations if possible but it is an option too.
In case someone needs the same i describe the method i currently use. It is based on adding annotations, fields like id and imports using com.google.code.maven-replacer-plugin.
Shortly: i have added following stuff in my pom.xml
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- dir where cxf-codegen-plugin has generated model classes -->
<basedir>src/generated/java/org/example/service</basedir>
<includes>
<include>NamedEntity.java</include>
</includes>
<regex>false</regex>
<replacements>
<replacement>
<token>package org.example.service.service;</token>
<value>package org.example.service.service;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.GeneratedValue;
import javax.persistence.InheritanceType;
</value>
</replacement>
<replacement>
<token>public class</token>
<value>#Entity
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class</value>
</replacement>
<replacement>
<token>protected String name;
</token>
<value>protected String name;
#Id
#GeneratedValue
#Getter
private Long id;
</value>
</replacement>
</replacements>
</configuration>
</plugin>
To keep the code nicely formatted all indents and line feeds are required in <replacement>s. Using regexps this might be done more stylish but this is good enough for me.
I m new to Spock, tried to write a simple Spock but it failed:
Error:Groovyc: Could not instantiate global transform class org.spockframework.compiler.SpockTransform specified at jar:file:.../.m2/repository/org/spockframework/spock-core/1.0-groovy-2.4/spock-core-1.0-groovy-2.4.jar!/META-INF/services/org.codehaus.groovy.transform.ASTTransformation because of exception java.lang.NullPointerException
here is my Spec:
#Unroll
class UserFilterSpec extends Specification {
private static final String USER_ID_1 = "someUserId1";
private static final String USER_ID_2 = "someUserId2";
private static final String USER_ID_3 = "someUserId3";
def filter = new UserFilter()
def User user1 = setupTestUser(USER_ID_1)
def User user2 = setupTestUser(USER_ID_2)
def User user3 = setupTestUser(USER_ID_3)
def "given a list of users and list of user ids, should return list of user with those users removed"() {
expect:
filter.filterUserDataByIds(userList, userIdList) == filterList
where:
userList | userIdList || filterList
Lists.newArrayList(user1, user2, user3) | Lists.newArrayList(USER_ID_1) || Lists.newArrayList(user2, user3)
}
}
and here is my pom.xml:
<!-- Mandatory plugins for using Spock -->
<plugin>
<!-- The gmavenplus plugin is used to compile Groovy code. To learn more about this plugin,
visit https://github.com/groovy/GMavenPlus/wiki -->
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Optional plugins for using Spock -->
<!-- Only required if names of spec classes don't match default Surefire patterns (`*Test` etc.) -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.6</version>
<configuration>
<useFile>false</useFile>
<includes>
<include>**/*Spec.java</include>
<include>**/*Test.java</include> <!-- Just in case of having also "normal" JUnit tests -->
</includes>
</configuration>
</plugin>
...
<!-- Mandatory dependencies for using Spock -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.0-groovy-2.4</version>
<scope>test</scope>
</dependency>
<!-- Optional dependencies for using Spock -->
<dependency> <!-- use a specific Groovy version rather than the one specified by spock-core -->
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.1</version>
</dependency>
<dependency> <!-- enables mocking of classes (in addition to interfaces) -->
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency> <!-- enables mocking of classes without default constructor (together with CGLIB) -->
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
what is wrong my Spec or pom setting? do i have to install Groovy to make it work?
Here is your test, re-written in more idiomatic Spock/Groovy:
#Unroll
class UserFilterSpec extends Specification {
static final String USER_ID_1 = "someUserId1"
static final String USER_ID_2 = "someUserId2"
static final String USER_ID_3 = "someUserId3"
#Shared user1 = setupTestUser(USER_ID_1)
#Shared user2 = setupTestUser(USER_ID_2)
#Shared user3 = setupTestUser(USER_ID_3)
#Shared filter = new UserFilter()
def "given a list of users and list of user ids, should return list of user with those users removed"() {
expect:
filter.filterUserDataByIds(userList, userIdList) == filterList
where:
userList | userIdList || filterList
[user1, user2, user3] | [USER_ID_1] || [user2, user3]
}
}
A couple of notes:
Groovy (in which Spock tests are written) has native support for declaring collections. Thus [user1, user3] instead of Lists.newArrayList.
#Shared or static is required for class-level variables that are used in tests. This will solve your compilation problem.
I highly recommend reading the Groovy user guide, it's a great read and will help you immensely getting started with Spock. The style guide is here: http://www.groovy-lang.org/style-guide.html, and from there you can explore the Documentation page for other interesting tidbits.
The Spock documentation is also excellent, and can easily be read in one sitting: http://docs.spockframework.org.
Add static or #Shared for non-method variables - 'filter', 'user 1-3'.
You can`t access non static class properties from inside the 'where' section.
In my case I solved the groovy error by upgrading from spring boot 2.3.4 to 2.5.3
https://issueexplorer.com/issue/spockframework/spock-example/44
Also, try upgrading from 1.3-groovy-2.5 to 2.0-groovy-3.0
Here is flyway maven plugin configuration:
<plugins>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<sqlMigrationSuffix>.oracle.sql</sqlMigrationSuffix>
<placeholderReplacement>true</placeholderReplacement>
<placeholderPrefix>#[</placeholderPrefix>
<placeholderSuffix>]</placeholderSuffix>
<encoding>UTF-8</encoding>
<table>T00M001</table>
<locations>
<location>classpath:/META-INF/flyway/oracle</location>
<location>classpath:/com/chorke/dbms/jdbcmi/oracle</location>
</locations>
<resolvers>
<resolver>com.chorke.dbms.flyway.resolvers.FlywayResolverImpl</resolver>
</resolvers>
<callbacks>
<callback>com.chorke.dbms.flyway.callbacks.AfterEachMigrate</callback>
<callback>com.chorke.dbms.flyway.callbacks.BeforeEachMigrate</callback>
</callbacks>
<serverId>chorke.flyway.oracle</serverId>
<url>jdbc:oracle:thin:#127.0.0.1:1521:xe</url>
</configuration>
<dependencies>
<dependency>
<groupId>com.chorke.dbms</groupId>
<artifactId>chorke-dbms-flyway</artifactId>
<version>1.0.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.chorke.dbms</groupId>
<artifactId>chorke-dbms-oracle</artifactId>
<version>1.0.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.chorke.dbms</groupId>
<artifactId>chorke-dbms-jdbcmi</artifactId>
<version>1.0.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
Here is flyway.properties
flyway.encoding: UTF-8
flyway.placeholders.key: value
flyway.placeholders.name: nome
flyway.placeholders.prop: value
Here is the snippet of migration script:
-- DDL OF T01I001
-- -----------------------------------------------------------------------------
CREATE TABLE t01i001
(
t_msg_code VARCHAR2(5 BYTE) NOT NULL
, t_lang1_msg VARCHAR2(80 BYTE)
, t_lang2_msg VARCHAR2(80 BYTE)
, t_entry_user VARCHAR2(4 BYTE)
, t_entry_date DATE
, t_upd_user VARCHAR2(4 BYTE)
, t_upd_date DATE
);
-- DML OF T01I001
-- -----------------------------------------------------------------------------
INSERT INTO t01i001 (t_msg_code,t_lang1_msg,t_lang2_msg,t_entry_user
,t_entry_date,t_upd_user,t_upd_date) VALUES ('00','يوجد سجل أخر لليوم والوقت المحدد'
,'Record already exists for the specified Date and Time.','2'
,to_date('13-10-2005','DD-MM-YYYY'),'C',to_date('27-11-2005','DD-MM-YYYY'));
INSERT INTO t01i001 (t_msg_code,t_lang1_msg,t_lang2_msg,t_entry_user
,t_entry_date,t_upd_user,t_upd_date) VALUES ('01'
,'البيانات قد أدخلت من قبل لرقم الزيارة هذا'
,'Data has already been entered for this Visit Number.','2'
,to_date('13-10-2005','DD-MM-YYYY'),'C',to_date('27-11-2005','DD-MM-YYYY'));
Here is the registry for charset of oracle 11g XE R2:
NLS_LANG =AMERICAN_AMERICA.UTF8
Here is the maven goals:
mvn clean install flyway:migrate flyway:info
There is two type of problem occurred:
t_lang1_msg size exceed
imported character changed
While we increased t_lang1_msg size than migration work fine. but it is automatically converted يوجد سجل أخر لليوم والوقت المحدد to يوجد سجل أخر لليوم والوقت المØدد. Which one unreadable to us.
Any solution regarding to the issue? We appreciate your answer to resolving this issue.
Actually there was no doubt about the configuration of flyway-maven-plugin, flyway.properties as well as sql script and it's encoding. But there was an problem inside ant script target. Where there was an task to concat sql files in specific order for per sprint basis. that's as following:
<concat destfile="${file.flyway.sql.concat}" outputencoding="UTF-8"append="true">
<sort xmlns:rcmp="antlib:org.apache.tools.ant.types.resources.comparators">
<fileset refid="dir.set.flyway.db.version.build"/>
<rcmp:name />
</sort>
</concat>
After adding encoding="UTF-8" attribute to concat task it is working fine.
<concat destfile="${file.flyway.sql.concat}"
outputencoding="UTF-8" encoding="UTF-8" append="true">
<sort xmlns:rcmp="antlib:org.apache.tools.ant.types.resources.comparators">
<fileset refid="dir.set.flyway.db.version.build"/>
<rcmp:name />
</sort>
</concat>
That's resolve this issue.
I'm new to Java, but I have to use it to do a small WebSocket related project.
So, I installed JDK 1.8.0 and NetBeans 8.1 on my CentOS 7 in a VirtualBox.
I added the tyrus-standalone-client-jdk 1.12 plug-in in the pom.xml to make the standalone Websocket client, and it built fine. However, I ran into the error below:
[root#cet7 ~]# java -jar "/root/NetBeansProjects/Switchclient/target/Switchclient-1.0-SNAPSHOT.jar"
Exception in thread "main" java.lang.NoClassDefFoundError: javax/websocket/ContainerProvider
at org.sample.switchclient.Switchclient.main(Switchclient.java:21)
Caused by: java.lang.ClassNotFoundException: javax.websocket.ContainerProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
[root#cet7 ~]# java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)
I did a bit more searching and found that the "fully qualified classname of the container implementation of ContainerProvider must be listed in the META-INF/services/javax.websocket.ContainerProvider file in the implementation JAR file" for the ServiceLoader API according to Oracle documentation. So, I added the serviceloader-maven-plugin to the pom.xml. The result was that it did generate the META-INF/services/javax.websocket.ContainerProvider file, but without any content, and the runtime error continued to persist. I tried to modify the contents bellow manually and re-pack it into a JAR but it did not worked:
org.glassfish.tyrus.container.inmemory.InMemoryContainerProvider
org.glassfish.tyrus.client.ClientManager
I've attached the Java file and the pom.xml. I've worked for hours and haven't a clue what the issue is, so any response to this thread will be appreciated.
Thank you very much.
===========LIST1: pom.xml===========
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sample</groupId>
<artifactId>Switchclient</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>org.sample.switchclient.Switchclient</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>eu.somatik.serviceloader-maven-plugin</groupId>
<artifactId>serviceloader-maven-plugin</artifactId>
<version>1.0.6</version>
<configuration>
<services>
<param>javax.websocket.ContainerProvider</param>
</services>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client-jdk</artifactId>
<version>1.12</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
===========LIST2: Switchclient.java===========
package org.sample.switchclient;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
#ClientEndpoint
public class Switchclient {
#OnMessage
public void onRemoteMessage (String message) {
System.out.println("Received msg: "+message);
}
public static void main(String[] args) {
WebSocketContainer container = null;
Session session = null;
try{
container = ContainerProvider.getWebSocketContainer();
session = container.connectToServer (Switchclient.class, URI.create("ws://localhost:8080/Switchserver/"));
}catch (Exception e) {
e.printStackTrace();
}
}
}
Basically, Tyrus requires Java EE. It's the reason you have to list a lot of dependencies in pom.xml. If you use Java SE and want to keep your project small, use another different WebSocket client library that depends on only Java SE. For example, nv-websocket-client (mine).
Just add the following dependency to pom.xml,
<dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-websocket-client</artifactId>
<version>1.13</version>
</dependency>
then try:
import com.neovisionaries.ws.client.*;
public class Switchclient
{
public static void main(String[] args) throws Exception
{
WebSocket websocket = new WebSocketFactory()
.createSocket("ws://localhost:8080/Switchserver/")
.addListener(new WebSocketAdapter() {
#Override
public void onTextMessage(WebSocket ws, String message) {
System.out.println("Received msg: " + message);
}
})
.connect();
// Don't forget to call disconnect() after use.
// websocket.disconnect();
}
}
I'm not sure what exactly caused the problem since I kept trying and problems kept jumping out during the past day. But finally here is it:
Client dependencies:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-client-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>1.12</version>
</dependency>
at a first glance it seems javax.websocket-client-api should be enough but finally cyber said that ContainerProvider is not impediment.
Then, all built OK. (with different java codes from my original post, I tried a lot on including the source codes, but codes themselves don't matter that match here while the environment setup matters. They mostly based on the examples of Tyrus 1.9 user guide however.)
And the run from the NetBeans by maven was OK, but when I went to use "java -jar Switchclient.jar", same/similar problem jumped out saying problem with "Endpoint".
Finally (as a last try) I copied all those tar files included in the classpath (witch was generated by maven-jar-plugin by specifying "<addClasspath>true<addClasspath>" into one directory, and also copied the generated jar file in, then it worked:
[root#cet7 neededjars]# ls
grizzly-framework-2.3.22.jar tyrus-client-1.12.jar
grizzly-http-2.3.22.jar tyrus-container-grizzly-client-1.12.jar
grizzly-http-server-2.3.22.jar tyrus-core-1.12.jar
javax.websocket-api-1.1.jar tyrus-spi-1.12.jar
javax.websocket-client-api-1.1.jar tyrus-standalone-client-1.12.jar
Switchclient-1.1-SNAPSHOT.jar
[root#cet7 neededjars]# java -jar Switchclient-1.1-SNAPSHOT.jar
Received message: Hello world
That's it, dirty and but worked. and I'm at a new start. Again, I'm really new to java (one of those non-hard-tech guys, just pick it up in case of need); and it showed me the complicity of the community based development, especially in the case the technology is relatively new. dependencies and pitfall everywhere. That's is one part of the nature I guess...