I need some help with JAX-RS and Jersey in my multi module Java EE App.
I will start with describing my environment:
Java 8 (Java EE 7)
Maven 3.3.3
GlassFish 4.1.
After properly deploying on GlassFish there are such errors in logs:
[2016-02-08T14:06:10.302+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770302] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.RestConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.RestConfig]]
[2016-02-08T14:06:10.304+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770304] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.GraphConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.GraphConfig]]
[2016-02-08T14:06:10.304+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770304] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.GraphConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.GraphConfig]]
[2016-02-08T14:06:10.304+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770304] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.GraphConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.GraphConfig]]
[2016-02-08T14:06:10.305+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770305] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.GraphConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.GraphConfig]]
[2016-02-08T14:06:10.305+0100] [glassfish 4.1] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=44 _ThreadName=admin-listener(2)] [timeMillis: 1454936770305] [levelValue: 900] [[
Unable to load class pl.com.softnet.rest.RestConfig, reason: java.lang.ClassNotFoundException: pl.com.softnet.rest.RestConfig]]
Here is my poms dependency of Web Service module:
<!-- JAVAEE API 7-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- SERVLET-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<exclusions>
<exclusion>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.22</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.22</version>
<scope>provided</scope>
</dependency>
<!-- RICHAFACES -->
<dependency>
<groupId>org.richfaces</groupId>
<artifactId>richfaces</artifactId>
<version>4.5.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.1.2-b04</version>
<scope>provided</scope>
</dependency>
<!-- JSF -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.0</version>
<scope>provided</scope>
</dependency>
This is the resource class:
package pl.com.softnet.rest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pl.com.softnet.ejb3.localBeans.FSMAdministratorBean;
import pl.com.softnet.ejb3.localBeans.ModulBezpieczenstwaBean;
import pl.com.softnet.entity.ProcesyDef;
import pl.com.softnet.entity.Uzytkownik;
import pl.com.softnet.filters.TestFilter;
import pl.com.softnet.util.ServiceLocator;
import pl.com.softnet.util.XmlUtils;
import pl.com.softnet.wyjatki.ModyfikacjaProcesuException;
import javax.naming.NamingException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.util.UUID;
#Path("config")
public class GraphConfig {
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_XML)
public Response getMethod {
}
#POST
#Path("{id}")
#Consumes(MediaType.APPLICATION_XML)
public Response postMethod() {
}
}
There is a Web Service class:
package pl.com.softnet.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
#ApplicationPath("/rest/*")
public class RestConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> myResources = new HashSet<Class<?>>();
myResources.add(GraphConfig.class);
return myResources;
}
}
My web.xml file:
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>pl.com.softnet.rest.RestConfigr</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
In your web.xml you just need this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
Note that is important the web-app version of web.xml
In your pom.xml
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.12</version>
</dependency>
And, you need a class that implements Application, but you don't need any Implementation. Just Like this is enough:
#ApplicationPath("/rest")
public class RestConfig extends Application {
#Context
private UriInfo context;
/**
* Creates a new instance of SimetPersistence
*/
public RestConfig() {
}
}
and, your application:
#Path("config")
public class GraphConfig {
public GraphConfig() {}
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_XML)
public Response getMethod {
...
It, must work. =)
Enviroment :
Java version: 1.7.0_79, vendor: Oracle Corporation
Apache Maven 3.0.3
Glassfish 4.1 (build 13)
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>br.ceptro.measure</groupId>
<artifactId>restfullexample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>restfullexample</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Class that extends Application
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ceptro.measure.restfullexample;
import java.util.Set;
import javax.ws.rs.core.Application;
/**
*
* #author polianareis
*/
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(br.ceptro.measure.restfullexample.OlaBrasilResource.class);
}
}
Your REST WEb Services
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ceptro.measure.restfullexample;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* REST Web Service
*
* #author polianareis
*/
#Path("ola-brasil")
public class OlaBrasilResource {
#Context
private UriInfo context;
/**
* Creates a new instance of OlaBrasilResource
*/
public OlaBrasilResource() {
}
/**
* Retrieves representation of an instance of br.ceptro.measure.restfullexample.OlaBrasilResource
* #return an instance of java.lang.String
*/
#POST
#Produces("application/json")
public String postJson(String content) throws JSONException {
JSONObject jSONObject = new JSONObject(content);
String value = jSONObject.getString("value");
return "Your web service works so well !!! ValueIs="+ value;
}
/**
* PUT method for updating or creating an instance of OlaBrasilResource
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/json")
public String putJson(String content) {
return "Example PUT";
}
}
You just need, clean and build. and deploy the war artifact in Glassfish 4.1
For test, you could use a REST Client in your navigator.
This is complete example and its works . See the image below:
Testing your rest application
Assuming you are using servlet 3.0 or higher
From https://jersey.java.net/nonav/documentation/2.0/deployment.html
There are multiple deployment options for the class that implements
Application interface in the Servlet 3.0 container. For simple
deployments, no web.xml is needed at all. Instead, an #ApplicationPath
annotation can be used to annotate the user defined application class
and specify the the base resource URI of all application resources
First remove all related Jersey configuration from web.xml
Update your RestConfig to be :
#ApplicationPath("rest")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("pl.com.softnet.rest");// This will scan for rest resources
}
}
The other approach is to use web.xml in that case remove MyApplication class
and update your web.xml to be like the following:
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>pl.com.softnet.rest</param-value>
</init-param>
</servlet>
...
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
I hope that can work ! :)
Related
I'm working on an Java EE app using wildfly 8.2 ,I try to make an unit test for my dao layer, but running classTest as JUnit Test it doesn't work with this error: ?
java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor
This the error log :
java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:160)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:111)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:97)
at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:52)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:93)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:156)
... 10 more
Caused by: org.jboss.arquillian.container.impl.ContainerCreationException: Could not create Container jboss
at org.jboss.arquillian.container.impl.LocalContainerRegistry.create(LocalContainerRegistry.java:85)
at org.jboss.arquillian.container.impl.client.container.ContainerRegistryCreator.createRegistry(ContainerRegistryCreator.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.ManagerImpl.bindAndFire(ManagerImpl.java:236)
at org.jboss.arquillian.core.impl.InstanceImpl.set(InstanceImpl.java:74)
at org.jboss.arquillian.config.impl.extension.ConfigurationRegistrar.loadConfiguration(ConfigurationRegistrar.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.ManagerImpl.start(ManagerImpl.java:261)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.<init>(EventTestRunnerAdaptor.java:56)
... 15 more
Caused by: java.lang.IllegalArgumentException: DeployableContainer must be specified
at org.jboss.arquillian.core.spi.Validate.notNull(Validate.java:44)
at org.jboss.arquillian.container.impl.ContainerImpl.<init>(ContainerImpl.java:71)
at org.jboss.arquillian.container.impl.LocalContainerRegistry.create(LocalContainerRegistry.java:76)
... 39 more
This my Dao Code
#Singleton
#TransactionManagement(TransactionManagementType.CONTAINER)
public class CategoryDao implements ICategoryDao {
//===================================
//= Attributes =
//===================================
#Inject
private EntityManager em;
#Inject
private Logger log = Logger.getLogger(CategoryDao.class);
//===================================
//= Constructors =
//===================================
public CategoryDao() {
super();
}
//===================================
//= CRUD Database Operations =
//===================================
public Category addCategory(Category category) {
em.persist(category);
log.info("CategoryDao : Object persisted.");
return category;
}
#Override
public void deleteCategory(Long codeCategory) {
Category category = em.find(Category.class, codeCategory);
if(category!=null)
{
em.remove(category);
log.info("CategoryDao : Object was removed.");
}
}
#Override
public List<Category> getAllCategories() {
if(em==null)
{
System.out.println("dao em is null");
}
else
{
System.out.println("dao em is not null");
}
Query query = em.createNamedQuery("Find_All_Categories");
List<Category> categories = query.getResultList();
return categories;
}
#Override
public Category updateCategory(Category category) {
// TODO Auto-generated method stub
return null;
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
This is my resource file :
public class Resources {
private final String UNIT_NAME="BooksStore";
#PersistenceContext(unitName = UNIT_NAME, type = PersistenceContextType.TRANSACTION)
#Produces
private EntityManager em;
#Produces
private Logger log = Logger.getLogger(CategoryDao.class);
}
This my arquillian.xml
<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 WildFly 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">/path/to/wildfly</property> -->
<!--</configuration> -->
</container>
</arquillian>
And this my TestDao class :
#RunWith(Arquillian.class)
public class CategoryDaoTest {
#Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(Category.class, CategoryDao.class, Resources.class)
.addAsResource("META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
#Inject
private CategoryDao dao;
#Test
public void testRegister() throws Exception {
System.out.println("unit test start");
}
}
And this my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.glsid.bookstore</groupId>
<artifactId>bookstore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>WildFly Quickstarts: bookstore</name>
<description>A starter Java EE 7 webapp project for use on JBoss WildFly / WildFly, generated from the jboss-javaee6-webapp archetype</description>
<url>http://wildfly.org</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<distribution>repo</distribution>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license>
</licenses>
<properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- JBoss dependency versions -->
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
<!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. -->
<version.jboss.bom>8.2.1.Final</version.jboss.bom>
<!-- other plugin versions -->
<version.compiler.plugin>3.1</version.compiler.plugin>
<version.surefire.plugin>2.16</version.surefire.plugin>
<version.war.plugin>2.5</version.war.plugin>
<!-- maven-compiler-plugin -->
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
</properties>
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
of artifacts. We use this here so that we always get the correct versions
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
from the Hibernate family of projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.wildfly.arquillian</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>1.1.0.Final</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- First declare the APIs we depend on and need for compilation. All
of them are provided by JBoss WildFly -->
<!-- Import the CDI API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the Common Annotations API (JSR-250), we use provided scope
as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JAX-RS API, we use provided scope as the API is included
in JBoss WildFly -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the EJB API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSR-303 (Bean Validation) Implementation -->
<!-- Provides portable constraints such as #Email -->
<!-- Hibernate Validator is shipped in JBoss WildFly -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Import the JSF API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Now we declare any tools needed -->
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for
typesafe criteria queries -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope>
</dependency>
<!-- Annotation processor that raising compilation errors whenever constraint
annotations are incorrectly used. -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<scope>provided</scope>
</dependency>
<!-- Needed for running tests (you may also use TestNG) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.3.3.Final</version>
</dependency>
</dependencies>
<build>
<!-- Maven will append the version to the finalName (which is the name
given to the generated war, and hence the context root) -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- The WildFly plugin deploys your war to a local WildFly container -->
<!-- To use, run: mvn package wildfly:deploy -->
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run
just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in your WildFly instance -->
<!-- This profile will start a new WildFly instance, and execute the
test, shutting it down when done -->
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in a remote WildFly instance -->
<!-- Run with: mvn clean test -Parq-wildfly-remote -->
<id>arq-wildfly-remote</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- When built in OpenShift the 'openshift' profile will be used when
invoking mvn. -->
<!-- Use this profile for any OpenShift specific customization your app
will need. -->
<!-- By default that is to put the resulting archive into the 'deployments'
folder. -->
<!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
<id>openshift</id>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<outputDirectory>deployments</outputDirectory>
<warName>ROOT</warName>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<!-- aquairm -->
</profiles>
</project>
Does it work when you run mvn build with any of the wildfly profiles?
My guess is that in Eclipse there is no container adapter in the classpath - you should activate a profile in your IDE first, otherwise the JAR is missing.
It would be easier to understand the problem if you could paste the stacktrace rather than attaching part of it as a screenshot :)
I am learning REST services and face the problem: RestEasy cannot find my resources, even though I've tried various ways to demonstrate them.
Exception:
Failed to execute: javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://localhost:8080/RestfullService/services/hello
where RestfullService is the name of my project, /service - applicationPath, hello - resource. None of the errors (404 etc.) are shown on this pages.
My web.xml
(by the way, I've met controversial approaches regarding the content of web.xml while using web app server 3.0. According to official manuals, it is not required, but lots of people argue for it. What is the best practice?)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>RestEasy sample Web Application</display-name>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.store.model.WebConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/</param-value>
</context-param>
</web-app>
My pom.xml (Although I've added all dependencies manually, the problem wasn't eliminated)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>RestfullService</groupId>
<artifactId>RestfullService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>webapp\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- <executions> <execution> <phase>package</phase> <configuration> <webXml>\webapp\WEB-INF\web.xml</webXml>
</configuration> </execution> </executions> -->
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<version>2.7</version>
<configuration>
<modules>
<ejbModule>
<!-- property configurations goes here -->
</ejbModule>
</modules>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.4.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.4.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.4.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>3.0.4.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0-EDR1</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.0_spec</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
</dependencies>
</project>
ServiceInitialisation.java (both options with and without the body of this class didn't help):
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/services")
public class ServiceInitialisation extends Application{
// private Set<Object> singletons = new HashSet<Object>();
// private Set<Class<?>> classes = new HashSet<Class<?>>();
//
// public ServiceInitialisation() {
// singletons.add(new GoodsWebServiceImpl());
// }
//
// #Override
// public Set<Object> getSingletons() {
// return singletons;
// }
//
// #Override
// public Set<Class<?>> getClasses() {
// return classes;
// }
}
And finally services:
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.store.entity.Item;
#Path("/")
public interface GoodsWebService {
#GET
#Path("/hello")
#Produces("application/json")
public Response greet();
// id: \\d+ - regex for cheching if it is int #GET #Path("{id:
\\d+}")
#Produces("application/json")
public Response
getInfoById(#PathParam("id") int id);
#GET
#Path("/all")
#Produces("application/json")
public List<Item> getAllItems();
}
package com.store.restService;
import java.util.ArrayList;
import java.util.List;
//import org.json.JSONException;
//import org.json.JSONObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.json.JSONObject;
import com.store.entity.Item;
import com.store.entity.Shop;
#Path("/")
public class GoodsWebServiceImpl implements GoodsWebService
{
private static List<Item>data;
private static List<Shop>shops1;
private static List<Shop>shops2;
private static List<Shop>shops3;
private static Shop shop1;
private static Shop shop2;
private static Shop shop3;
static {
shop1 = new Shop(1,4.55, 1);
shop2 = new Shop(2,9.99, 2);
shop3 = new Shop(3,6,0);
shops1.add(shop1); shops1.add(shop2);
shops2.add(shop3); shops2.add(shop1);
shops3.add(shop2); shops3.add(shop3);
data = new ArrayList<>();
data.add(new Item(1, "hand", shops1));
data.add(new Item(2, "pen", shops2));
data.add(new Item(3, "ball", shops2));
}
public static Item getItemById(int id){
for(Item e: data){
if(e.getId()==id) return e;
}
throw new RuntimeException("Can't find Item with id -" + id);
}
public static List<Item> getAll(){
return data;
}
#Override
public Response greet(){
String result = "Hello!";
return Response.status(200).entity(result).build();
}
#Override
public Response getInfoById(int id){
JSONObject jsonObject = new JSONObject();
Item item = getItemById(id);
jsonObject.put("Id ", item.getId());
jsonObject.put("Mpn ", item.getMpn());
jsonObject.put("Shop ", item.getShops());
String result = "Output:\n" + jsonObject;
return Response.status(200).entity(result).build();
}
#Override
public List<Item> getAllItems(){
// JSONObject jsonObject = new JSONObject();
// List<Item> items = getAll();
// jsonObject.put("List", items);
// JSONArray jArray = jsonObject.getJSONArray("List");
// for(int i=0; i<jArray.length(); i++){
// System.out.println(jArray.getJSONObject(i).getString("id"));
// System.out.println(jArray.getJSONObject(i).getString("mpn"));
// System.out.println(jArray.getJSONObject(i).getString("shop"));
// }
return getAll();
}
}
I would be gratefull for any comments, since all the available solutions in the web were already been unsuccessfully tried.
Thanks in advanced
Update:
Due to the fact that only a few manuals were succesfully deployed on my machine, I suppose I choose incorrect setting during the process of creation of the project.
I create the project for REST in this way: create Dynamic web project -> convert it to Maven -> add dependencies etc. -> trying to deploy
Screenshot of them:
The image is here
Update2
Moreover, I've noticed that every time I start WildFly I meet the same error. I have tried to create a few project with various dependencies, but the result is the same. How to deal with it?
22:45:09,109 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."RestService.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."RestService.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "RestService.war"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:163)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer from [Module "deployment.RestService.war:main" from Service Module Loader]
at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:292)
at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.scanWebDeployment(JaxrsScanningProcessor.java:153)
at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.deploy(JaxrsScanningProcessor.java:104)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:156)
... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer from [Module "deployment.RestService.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:290)
... 8 more
22:45:09,114 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"RestService.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"RestService.war\".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment \"RestService.war\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer from [Module \"deployment.RestService.war:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer from [Module \"deployment.RestService.war:main\" from Service Module Loader]"}}
You don't need web.xml, the resteasy-servlet, or any explicit RESTEasy dependencies in your POM.
You'd better start with a simple working example, e.g. https://github.com/wildfly/quickstart/tree/10.x/jaxrs-client.
Despite its name, this sample not only includes a JAX-RS client, but also a JAX-RS service.
I would like to convert the Spring Integration based web services to Spring Boot Application.
My application is developed using spring integration web services.
I want to convert that existed application into spring boot.I have tried to find many demos. No demo is available in online.
While converting I was facing this issue.
My Soap meesage response after submitting the request is as follows:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">No adapter for endpoint [countryGateway]: Is your endpoint annotated with #Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Startup of the application is given below
Application.Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.integration.config.EnableIntegration;
#SpringBootApplication
#EnableIntegration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring configuration is as below
Sample-context.xml
<bean id="payloadMapping"
class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="mappings">
<props>
<prop
key="{http://spring.io/guides/gs-producing-web-service}getCountryRequest">countryGateway</prop>
</props>
</property>
</bean>
<int:channel id="countryRequestChannel"></int:channel>
<int:channel id="countryResponseChannel"></int:channel>
<int:channel id="countryErrorChannel"></int:channel>
<int-ws:inbound-gateway id="countryGateway"
error-channel="countryErrorChannel" request-channel="countryRequestChannel"
reply-channel="countryResponseChannel" />
<int:service-activator input-channel="countryRequestChannel" output-channel="countryResponseChannel" method="hello" ref="sampleActivator"></int:service-activator>
<bean id="sampleActivator" class="com.sample.country.SampleValidate"></bean>
Maven configuration is as below
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>com.sample.country</groupId>
<artifactId>springbootsample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<!-- Adding the dependencies -->
<dependencies>
<!-- To support web services -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ws</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ws</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-xml</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>org.apache.ws.xmlschema</groupId>
<artifactId>xmlschema-core</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
</project>
Web service configuration that i used is as given below
WebServiceConfig.java
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}
I don't see you referencing the Sample-context.xml anywhere.
Try adding
#ImportResource("Sample-context.ml")
to the Application class.
EDIT
#EnableWs doesn't add a MessageEndpointAdapter, just a MethodEndpointAdapter.
This works...
#EnableWs
#Configuration
#ImportResource("Sample-context.xml")
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(MessageDispatcherServlet servlet) {
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean
public MessageDispatcherServlet servlet() {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setTransformWsdlLocations(true);
return servlet;
}
#Bean
public MessageEndpointAdapter adapter() {
return new MessageEndpointAdapter();
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}
I try to integrate the arquillian solution into my maven EJB project which contains juste the EJBs which I uses in other separate projects.
I use Jboss EAP6.
So i have make it as the following :
I made the arquillian.xml into ejbModule/src/test/resources/:
<container qualifier="jboss" default="true">
<configuration>
<property name="jbossHome">D:\jbdevstudio\jboss-eap-6.2</property>
</configuration>
</container>
in the pom of my project i added the following dependencies:
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-jbossas-embedded-6</artifactId>
<version>1.0.0.Alpha5</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-junit</artifactId>
<version>1.0.0.Alpha5</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
<profiles>
<profile>
<id>jbossas-embedded-6</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>arq-jbossas-managed</id>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-containermanaged</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>arq-jbossas-remote</id>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-containerremote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
The Test Class :
import javax.inject.Inject;
import org.jboss.arquillian.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.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.oap.subscription.AbstractSubscription;
#RunWith(Arquillian.class)
public class SubscriptionFactoryTest {
#Inject
private SubscriptionFactory subscriptionFactory;
#Deployment
public static JavaArchive getDeployement() {
System.out.println("### testSayHelloEJB");
return ShrinkWrap.create(JavaArchive.class, "subscriptionFactory.jar")
.addClasses(AbstractSubscription.class,SubscriptionFactory.class);
}
#Test
public void getSubscriptionByIdTest() {
System.out.println("### testSayHelloEJB");
}
}
The EJB Class:
#Remote(ISubscriptionFactoryRemote.class)
#Local(ISubscriptionFactoryLocal.class)
#Stateless
public class SubscriptionFactory extends AbstractSubscription implements ISubscriptionFactoryRemote {
#Override
public AbstractSubscription getSubscriptionById(final Integer id) {
AbstractSubscription ret = null;
if (id != null) {
// create query
final StringBuilder queryString = new StringBuilder("select c from AbstractSubscription c ");
try {
queryString.append("where c.id = :id");
// create query
Query query = this.getEntityManager().createQuery(queryString.toString());
// set parameter
query = query.setParameter("id", id);
// recovers refCountry
ret = (AbstractSubscription) query.getSingleResult();
} catch (final Exception exc) {
}
}
return ret;
}
}
When i run the class test as Junit test , it gives me the errors :
janv. 20, 2015 12:15:34 PM org.jboss.arquillian.impl.client.container.ContainerRegistryCreator getActivatedConfiguration
Infos: Could not read active container configuration: null
the Faillure Trace:
java.lang.NoClassDefFoundError: Lorg/jboss/embedded/api/server/JBossASEmbeddedServer;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2397)
at java.lang.Class.getDeclaredFields(Class.java:1806)
at org.jboss.arquillian.impl.core.Reflections.getFieldInjectionPoints(Reflections.java:74)
... 79 more
Any idea.
You're using a very old version of Arquillian, I'd use at least version 1.1.0.Final. I also don't think you need a few of the Arquillian dependencies you have defined.
Remove the arquillian-jbossas-embedded-6 and arquillian-junit depdendencies.
There are plenty of quickstart examples of how to use Arquillian with JBoss EAP. Have a look at some of the pom's there as it might help.
I'm trying to enable the compression in restlet + jetty embedded but in my test application the compression works only with requests handled directly by servlets and not for those handled by restlet.
My test code:
package restlettest;
import java.io.IOException;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlets.GzipFilter;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.ext.servlet.ServerServlet;
import org.restlet.routing.Router;
public class RestletTestServerJettyEmbedded {
public static class RestletTestApplication extends Application {
#Override
public synchronized Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/sayHello", HelloWorldResource.class);
return router;
}
}
#SuppressWarnings("serial")
public static class JettyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().println("Hello from jetty!");
};
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
final ServletContextHandler serveltContext = new ServletContextHandler(
ServletContextHandler.SESSIONS);
serveltContext.setContextPath("/");
serveltContext.setInitParameter("org.restlet.application",
RestletTestApplication.class.getName());
serveltContext.addFilter(GzipFilter.class, "/*",
EnumSet.of(DispatcherType.REQUEST));
serveltContext.addServlet(ServerServlet.class, "/restlet/*");
serveltContext.addServlet(JettyServlet.class, "/jetty/*");
server.setHandler(serveltContext);
server.start();
server.join();
}
}
The project POM:
<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>com.devmao.restlettest</groupId>
<artifactId>restlettest</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>8.1.7.v20120910</jetty.version>
<restlet.version>2.1.0</restlet.version>
</properties>
<dependencies>
<!-- Jetty -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<!-- /Jetty -->
<!-- Restlet -->
<dependency>
<groupId>org.restlet.jee</groupId>
<artifactId>org.restlet.ext.servlet</artifactId>
<version>${restlet.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.restlet.jee</groupId>
<artifactId>org.restlet.ext.httpclient</artifactId>
<version>${restlet.version}</version>
<scope>compile</scope>
</dependency>
<!-- /Restlet -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<!-- Restlet Repositories -->
<repository>
<id>maven-restlet</id>
<name>Public online Restlet repository</name>
<url>http://maven.restlet.org</url>
</repository>
<!-- /Restlet Repositories -->
</repositories>
</project>
Testing servlet request:
$ curl -i -H 'Accept-Encoding: gzip,deflate' http://localhost:8080/jetty
HTTP/1.1 200 OK
Vary: Accept-Encoding
Content-Encoding: gzip
Transfer-Encoding: chunked
Server: Jetty(8.1.7.v20120910)
Testing restlet request:
$ curl -i -H 'Accept-Encoding: gzip,deflate' http://localhost:8080/restlet/sayHello
HTTP/1.1 200 OK
Vary: Accept-Encoding
Content-Type: text/plain;charset=UTF-8
Date: Tue, 06 Nov 2012 09:24:01 GMT
Accept-Ranges: bytes
Server: Restlet-Framework/2.1.0
Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
Content-Length: 12