"No resource methods" when using JAX-RS on TomEE+ - java

Using stock TomEE+, I cannot get a simple JAX-RS resource to work. I constantly get an error of:
Jun 30, 2012 5:09:59 PM org.apache.cxf.jaxrs.utils.ResourceUtils checkMethodDispatcher
WARNING: No resource methods have been found for resource class com.tensorwrench.test.BaseResource
Jun 30, 2012 5:09:59 PM org.apache.cxf.jaxrs.utils.ResourceUtils checkMethodDispatcher
WARNING: No resource methods have been found for resource class com.tensorwrench.test.BaseResource
Jun 30, 2012 5:09:59 PM org.apache.cxf.jaxrs.utils.ResourceUtils checkMethodDispatcher
WARNING: No resource methods have been found for resource class com.tensorwrench.test.BaseResource
Jun 30, 2012 5:09:59 PM org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean checkResources
SEVERE: No resource classes found
Jun 30, 2012 5:09:59 PM org.apache.catalina.startup.HostConfig deployWAR
SEVERE: Error deploying web application archive D:\workspace\api\src\main\catalina_base\webapps\testapi-1.0.war
org.apache.cxf.service.factory.ServiceConstructionException
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:194)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.deploy(CxfRsHttpListener.java:126)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.deployPojo(CxfRsHttpListener.java:97)
at org.apache.openejb.server.rest.RESTService.deployPojo(RESTService.java:270)
at org.apache.openejb.server.rest.RESTService.afterApplicationCreated(RESTService.java:173)
at org.apache.tomee.webservices.TomeeJaxRsService.afterApplicationCreated(TomeeJaxRsService.java:55)
at org.apache.tomee.catalina.WebDeploymentListeners.afterApplicationCreated(WebDeploymentListeners.java:38)
at org.apache.tomee.catalina.TomcatWebAppBuilder.afterStart(TomcatWebAppBuilder.java:818)
at org.apache.tomee.catalina.GlobalListenerSupport.lifecycleEvent(GlobalListenerSupport.java:103)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:401)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:168)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:962)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1603)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.ws.rs.WebApplicationException
at org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean.checkResources(AbstractJAXRSFactoryBean.java:312)
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:144)
... 23 more
Resource class:
package com.tensorwrench.test;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
#Path("/test")
public class BaseResource {
#GET #Produces("text/plain") #Path("test") Response helloWorld() {
return Response.ok("Hello world","plain/text").build();
}
#GET #Produces("text/plain") String helloWorld2() {
return "Hello world without path!";
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="api" version="3.0"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd">
<display-name>Service</display-name>
build.gradle:
apply plugin: 'java'
apply plugin: 'war'
repositories { mavenCentral() }
dependencies {
providedCompile 'org.apache.openejb:javaee-api:6.0-4'
}
version = '1.0'
jar {
manifest {
attributes 'Title': 'Services',
'Version': version
}
}
</web-app>
I've tried a number of permutations, adding beans.xml, removing, changing order of the annotations, using different compile dependencies for the Java EE classes. I consistently get this error.

It looks like your resource methods are not public in scope. Try this:
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
#Path("/test")
public class BaseResource {
#GET #Produces("text/plain") #Path("test") public Response helloWorld() {
return Response.ok("Hello world","plain/text").build();
}
#GET #Produces("text/plain") public String helloWorld2() {
return "Hello world without path!";
}
}

Related

spring mvc with angular 2 not working on eclipse, data is not getting loaded

I am tying to test a simple spring mvc with angular 2 project running on eclipse.
The html page is getting displayed, but it is not loading any data from spring backend, any idea why this is happening?
console output:
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:AngularjsSpringRestExample' did not find a matching property.
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Sep 29 2017 13:46:41 UTC
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.47.0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jdk1.8.0_111\jre
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_111-b14
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47\endorsed
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_111\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\Program Files (x86)\GnuWin32\bin\;C:\Program Files (x86)\RBTools\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\IBM\RationalSDLC\common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\bin;C:\Program Files (x86)\IBM\gsk8\lib;C:\Program Files (x86)\IBM\gsk8\bin;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\RemoteClient\cteapis;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Users\dzhao\Java_Softwares\eclipse;;.
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1209 ms
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:25 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springrest'
Oct 06, 2017 11:31:25 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization started
Oct 06, 2017 11:31:25 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:25 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springrest-servlet.xml]
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[GET],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.getCountryById(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[POST],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.addCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[PUT],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.updateCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[DELETE],produces=[application/json]}" onto public void org.arpit.java2blog.controller.CountryController.deleteCountry(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[GET],produces=[application/json]}" onto public java.util.List org.arpit.java2blog.controller.CountryController.getCountries()
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.handler.SimpleUrlHandlerMapping registerHandler
INFO: Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization completed in 2531 ms
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:27 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5321 ms
This is my 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.arpit.java2blog</groupId>
<artifactId>AngularjsSpringRestExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>AngularjsSpringRestExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>AngularjsSpringRestExample</finalName>
</build>
</project>
servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
<mvc:default-servlet-handler/>
</beans>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
controller class:
package org.arpit.java2blog.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
#RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
public Country addCountry(#RequestBody Country country) {
return countryService.addCountry(country);
}
#RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
public Country updateCountry(#RequestBody Country country) {
return countryService.updateCountry(country);
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteCountry(#PathVariable("id") int id) {
countryService.deleteCountry(id);
}
}
bean class:
package org.arpit.java2blog.bean;
public class Country{
int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
service class:
package org.arpit.java2blog.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.arpit.java2blog.bean.Country;
/*
* It is just a helper class which should be replaced by database implementation.
* It is not very well written class, it is just used for demonstration.
*/
public class CountryService {
static HashMap<Integer,Country> countryIdMap=getCountryIdMap();
public CountryService() {
super();
if(countryIdMap==null)
{
countryIdMap=new HashMap<Integer,Country>();
// Creating some objects of Country while initializing
Country indiaCountry=new Country(1, "India",10000);
Country chinaCountry=new Country(4, "China",20000);
Country nepalCountry=new Country(3, "Nepal",8000);
Country bhutanCountry=new Country(2, "Bhutan",7000);
countryIdMap.put(1,indiaCountry);
countryIdMap.put(4,chinaCountry);
countryIdMap.put(3,nepalCountry);
countryIdMap.put(2,bhutanCountry);
}
}
public List getAllCountries()
{
List countries = new ArrayList(countryIdMap.values());
return countries;
}
public Country getCountry(int id)
{
Country country= countryIdMap.get(id);
return country;
}
public Country addCountry(Country country)
{
country.setId(getMaxId()+1);
countryIdMap.put(country.getId(), country);
return country;
}
public Country updateCountry(Country country)
{
if(country.getId()<=0)
return null;
countryIdMap.put(country.getId(), country);
return country;
}
public void deleteCountry(int id)
{
countryIdMap.remove(id);
}
public static HashMap<Integer, Country> getCountryIdMap() {
return countryIdMap;
}
// Utility method to get max id
public static int getMaxId()
{ int max=0;
for (int id:countryIdMap.keySet()) {
if(max<=id)
max=id;
}
return max;
}
}
html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<title>AngularJS $http Rest example</title>
<script type="text/javascript">
var app = angular.module("CountryManagement", []);
//Controller Part
app.controller("CountryController", function($scope, $http) {
$scope.countries = [];
$scope.countryForm = {
id : -1,
countryName : "",
population : ""
};
//Now load the data from server
_refreshCountryData();
//HTTP POST/PUT methods for add/edit country
// with the help of id, we are going to find out whether it is put or post operation
$scope.submitCountry = function() {
var method = "";
var url = "";
if ($scope.countryForm.id == -1) {
//Id is absent in form data, it is create new country operation
method = "POST";
url = '/AngularjsSpringRestExample/countries';
} else {
//Id is present in form data, it is edit country operation
method = "PUT";
url = '/AngularjsSpringRestExample/countries';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.countryForm),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
};
//HTTP DELETE- delete country by Id
$scope.deleteCountry = function(country) {
$http({
method : 'DELETE',
url : '/AngularjsSpringRestExample/country/' + country.id
}).then(_success, _error);
};
// In case of edit, populate form fields and assign form.id with country id
$scope.editCountry = function(country) {
$scope.countryForm.countryName = country.countryName;
$scope.countryForm.population = country.population;
$scope.countryForm.id = country.id;
};
/* Private Methods */
//HTTP GET- get all countries collection
function _refreshCountryData() {
$http({
method : 'GET',
url : 'http://localhost:8080/AngularjsSpringRestExample/countries'
}).then(function successCallback(response) {
$scope.countries = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
function _success(response) {
_refreshCountryData();
_clearFormData()
}
function _error(response) {
console.log(response.statusText);
}
//Clear the form
function _clearFormData() {
$scope.countryForm.id = -1;
$scope.countryForm.countryName = "";
$scope.countryForm.population = "";
};
});
</script>
<style>
.blue-button{
background: #25A6E1;
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #1A87B9
}
.red-button{
background: #CD5C5C;
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #CD5C5C
}
table {
font-family: "Helvetica Neue", Helvetica, sans-serif;
width: 50%;
}
caption {
text-align: left;
color: silver;
font-weight: bold;
text-transform: uppercase;
padding: 5px;
}
th {
background: SteelBlue;
color: white;
}
tbody tr:nth-child(even) {
background: WhiteSmoke;
}
tbody tr td:nth-child(2) {
text-align:center;
}
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: center;
font-family: monospace;
}
tfoot {
background: SeaGreen;
color: white;
text-align: right;
}
tfoot tr th:last-child {
font-family: monospace;
}
td,th{
border: 1px solid gray;
width: 25%;
text-align: left;
padding: 5px 10px;
}
</style>
<head>
<body ng-app="CountryManagement" ng-controller="CountryController">
<h1>
AngularJS Restful web services example using $http
</h1>
<form ng-submit="submitCountry()">
<table>
<tr>
<th colspan="2">Add/Edit country</th>
</tr>
<tr>
<td>Country</td>
<td><input type="text" ng-model="countryForm.countryName" /></td>
</tr>
<tr>
<td>Population</td>
<td><input type="text" ng-model="countryForm.population" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
</tr>
</table>
</form>
<table>
<tr>
<th>CountryName</th>
<th>Population</th>
<th>Operations</th>
</tr>
<tr ng-repeat="country in countries">
<td> {{ country.countryName }}</td>
<td >{{ country.population }}</td>
<td><a ng-click="editCountry(country)" class="blue-button">Edit</a> | <a ng-click="deleteCountry(country)" class="red-button">Delete</a></td>
</tr>
</table>
</body>
</html>
If you want to return anything from a rest controller then you must use #ResponseBody annotation just before function declaration.
Like this in your case:
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
.
.
.
}
And in case you are having a rest call which doesn't return anything then make sure to write #ResponseStatus(HttpStatus.NO_CONTENT)
Example:
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void setCountryById(#PathVariable int id) {
countryService.setCountry(id);
}

Spring Boot - Failed to initialize ServletRegistrationBean in WebLogic 12c

We're running GraphQL sample Java application in WebLogic 12c, but encountered some errors with servlet during startup.
The servlet was configured and register our servlets using a ServletRegistrationBean as below:
#Configuration
#ConditionalOnWebApplication
#ConditionalOnClass(DispatcherServlet.class)
#ConditionalOnBean({GraphQLSchema.class, GraphQLSchemaProvider.class})
#ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, SpringGraphQLCommonAutoConfiguration.class})
#EnableConfigurationProperties(GraphQLServletProperties.class)
public class GraphQLWebAutoConfiguration {
...
#Bean
#ConditionalOnMissingBean
public GraphQLServlet graphQLServlet(GraphQLSchemaProvider schemaProvider, ExecutionStrategyProvider executionStrategyProvider) {
return new SimpleGraphQLServlet(schemaProvider, executionStrategyProvider, listeners, instrumentation, errorHandler, contextBuilder);
}
#Bean
ServletRegistrationBean graphQLServletRegistrationBean(GraphQLServlet servlet) {
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, graphQLServletProperties.getServletMapping());
bean.setLoadOnStartup(1);
return bean;
}
}
In the weblogic server log, it prints out errors:
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101125> <[ServletContext#933807824[app:CPRES module:CPRES path:null spec-version:3.1]] Error occurred while instantiating servlet: "simpleGraphQLServlet".
java.lang.InstantiationException: graphql.servlet.SimpleGraphQLServlet
at java.lang.Class.newInstance(Class.java:427)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.newServletInstanceIfNecessary(StubSecurityHelper.java:365)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoSuchMethodException: graphql.servlet.SimpleGraphQLServlet.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101216> <Servlet: "simpleGraphQLServlet" failed to preload on startup in Web application: "CPRES".
javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:326)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:29 PM SGT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "19094957742917053" for task "130" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated"
weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
It looks that the weblogic is trying to create a new servlet instance instead of the ServletBean SimpleGraphQLServlet created and managed by Spring context.
Any advance? Thanks.
A walkaround solution is to write a Servlet wrapper class like this:
public class DelegateGraphQLServlet extends HttpServlet {
protected GraphQLServlet graphQLServlet;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ApplicationContext ac = (ApplicationContext) servletConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.graphQLServlet = (GraphQLServlet)ac.getBean("graphQLServlet");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
graphQLServlet.service(req, res);
}
}

EJB added to JNDI, but can't inject with #EJB

I've been trying to get a hang of Java EE and EJB over the last week.
I've been able to create the entities, DAOs, persistance units and such, but I'm still running into some issues.
In my project, I have an Author and a Book class. These, in turn, have their respective DAOs. (Listed below)
The issue is, my EJBs are being created and added to the JNDI tree correctly, only I can't seem to be able to inject them into my AuthorAPI REST provider... When I call the AuthorAPI.getAllAuthors method, the server responds with a 500 error pointing to the AuthorDAO object being null.
Any help would be greatly appreciated!
TomEE log
INFO: PersistenceUnit(name=libraryPU, provider=org.hibernate.ejb.HibernatePersistence) - provider time 969ms
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=BookDAOLocalBean) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/BookDAO!org.ucll.rest.dao.BookDAO) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/BookDAO) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=AuthorDAOLocalBean) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/AuthorDAO!org.ucll.rest.dao.AuthorDAO) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/AuthorDAO) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=AuthorLocalBean) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Author!org.ucll.rest.model.Author) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Author) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=BookLocalBean) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Book!org.ucll.rest.model.Book) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Book) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.CdiBuilder initSingleton
INFO: Existing thread singleton service in SystemInstance(): org.apache.openejb.cdi.ThreadSingletonServiceImpl#80169cf
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
INFO: OpenWebBeans Container is starting...
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
INFO: OpenWebBeans Container has started, it took 19 ms.
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=AuthorDAO, ejb-name=AuthorDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=Book, ejb-name=Book, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=Author, ejb-name=Author, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=BookDAO, ejb-name=BookDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=AuthorDAO, ejb-name=AuthorDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=Book, ejb-name=Book, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=Author, ejb-name=Author, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=BookDAO, ejb-name=BookDAO, container=Default Stateless Container)
HTTP Status 500 stacktrace
javax.servlet.ServletException: java.lang.NullPointerException
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:487)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
org.ucll.rest.web.api.AuthorAPI.getAllAuthors(AuthorAPI.java:25)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Author.java
package org.ucll.rest.model;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* #author larsv
*/
#Entity
#Table(name = "author", schema = "library")
#Stateless
public class Author implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "name", length = 100, nullable = false)
private String name;
#OneToMany(mappedBy = "author")
private List<Book> books;
public Author() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
Book.java
package org.ucll.rest.model;
import java.io.Serializable;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* #author larsv
*/
#Entity
#Table(name = "book", schema = "library")
#Stateless
public class Book implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "title", length = 100, nullable = false)
private String title;
#ManyToOne
#JoinColumn(name = "name")
private Author author;
public Book() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
AuthorDAO.java
package org.ucll.rest.dao;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ucll.rest.model.Author;
/**
*
* #author larsv
*/
#Stateless
public class AuthorDAO extends AbstractDAO<Author> {
#PersistenceContext(unitName = "libraryPU")
private EntityManager em;
public AuthorDAO() {
super(Author.class);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
BookDAO.java
package org.ucll.rest.dao;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ucll.rest.model.Book;
/**
*
* #author larsv
*/
#Stateless
public class BookDAO extends AbstractDAO<Book> {
#PersistenceContext(unitName = "libraryPU")
private EntityManager em;
public BookDAO() {
super(Book.class);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
AuthorAPI.java
package org.ucll.rest.web.api;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.ucll.rest.dao.AuthorDAO;
import org.ucll.rest.web.helper.JSONConverter;
/**
*
* #author larsv
*/
#Path("/author")
public class AuthorAPI {
#EJB
private AuthorDAO authorDAO;
#GET
#Path("/all")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllAuthors() {
String json_response = JSONConverter.covertAuthorList(authorDAO.readAll());
return Response.status(200).entity(json_response).build();
}
}
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="libraryPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/library</jta-data-source>
<class>org.ucll.rest.model.Author</class>
<class>org.ucll.rest.model.Book</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
The reason your #EJB is not being resolved is that you are not in the EE container context.
The easiest solution for this is to make your webservice an EJB.
This can be done by adding the stateless annotation:
#Path("/author")
#Stateless
public class AuthorAPI {
After this change your dao should get injected into it.
On a side note some tips for your code that might help prevent future problems :
You should provide a getter/setter method for
private AuthorDAO authorDAO;
Otherwise the container cant inject the implementation at runtime.
On a related note: I dont know what version of EJB you are using but in 3.0 it was necessairy to create an interface for your EJB's. Since 3.1 it is not needed anymore but I still consider it to be best practice to code vs an interface instead of vs an implementation class.

Spring mvc Java based Configuration not working. Console display no error but my jsp page is not showing

Hello i am converting my simple demo project from bean configuration to pure java based configuration. Bean configuration works fine creating tables and all. But my java configuration is not displaying any pages. I solved many errors bur now console shows no error specifying the problem. here's my code please find whats wrong, or have i missed anything in the configuration. I am new to spring and fairly new to java based configuration. These are the sites from which i took code.
http://codehustler.org/blog/spring-security-tutorial-form-login-java-config/
for hibernate i use used this tutorial
http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annotations/
My classes
1. AppConfiguration
package com.kharoud.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#ComponentScan({"com.kharoud"})
#Import({MvcConfiguraion.class, RepositoryConfiguration.class})
public class AppConfiguration {
}
2.MvcConfigurtion
package com.kharoud.configuration;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#Configuration
public class MvcConfiguraion extends WebMvcConfigurerAdapter{
#Override
public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer ){
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views");
resolver.setSuffix(".jsp");
return resolver;
}
}
3.RepositoryConfiguration
package com.kharoud.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] {"com.kharoud.model"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
4.SpringConfigurationInitializer
package com.kharoud.configuration.initilizer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.kharoud.configuration.AppConfiguration;
public class SpringConfigurationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
only added these new classes. I deleted my web.xml.
Later on i will add Spring Security configuration class
this is my console output
Feb 25, 2015 2:32:13 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_25\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Window s;C:/Program Files/Java/jre1.8.0_25/bin/server;C:/Program Files/Java/jre1.8.0_25/bin;C:/Program Files/Java/jre1.8.0_25/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\ system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShe ll\v1.0\;C:\Program Files\Java\jdk1.8.0_25\bin;;C:\ECLIPSE\eclipse;;.
Feb 25, 2015 2:32:14 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ProjectDemo' did not find a matching property.
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:14 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1063 ms
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Feb 25, 2015 2:32:15 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [217] milliseconds.
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [com.kharoud.configuration.initilizer.SpringConfigurationInitializer#389ae113]
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
Feb 25, 2015 2:32:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:26 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11876 ms
MyHomeController
package com.kharoud;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String welcome(Model model){
return "index";
}
}
Myindex.jsp file is in WEB-INF/views folder under webapp folder
The views were properly resolved with bean configuration.
Thank you for your answers. I found the problem. When i wrote #ComponentScan on top of my MvcConfiguration class it worked and pages are displaying.

Running Jersey with built in HTTP server

I'm trying to run a simple Jersey app from the command line using the built in HTTP server.
Following various tutorials, I've set my app up like this:
src/main/java/net/wjlafrance/jerseyfun/App.java:
package net.wjlafrance.jerseyfun;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
/**
* Hello world!
*
*/
#Path("/hello")
public class App {
public static void main(String[] args) {
System.out.println("Starting HTTP server..");
try {
HttpServerFactory.create("http://localhost:9998/").start();
} catch (IOException ex) {
System.err.println(ex);
}
}
#GET
public Response getMessage() {
String output = "It works!";
return Response.status(200).entity(output).build();
}
}
src/main/webapp/WEB-INF/web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>net.wjlafrance.jerseyfun</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
When I run mvn clean package exec:java -Dexec.mainClass=net.wjlafrance.jerseyfun.App, I see this output:
Starting HTTP server..
Apr 29, 2013 9:12:11 AM com.sun.jersey.api.core.ClasspathResourceConfig init
INFO: Scanning for root resource and provider classes in the paths:
C:\cygwin\home\wlafrance\bin\apache-maven-3.0.5/boot/plexus-classworlds-2.4.jar
Apr 29, 2013 9:12:11 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.17 01/17/2013 03:31 PM'
Apr 29, 2013 9:12:11 AM com.sun.jersey.server.impl.application.RootResourceUriRules <init>
SEVERE: The ResourceConfig instance does not contain any root resource classes.
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1331)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:172)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:264)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:246)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:117)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:92)
at net.wjlafrance.jerseyfun.App.main(App.java:22)
... 6 more
Clearly enough, my server is misconfigured. Can someone point me in the right direction?
With Jersey 1.x, the answer of #pakOverflow points to the right direction. Here the complete code with which I had success. Without any dependency on Grizlly1 or Grizzly2 etc.
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class WineryUsingHttpServer {
public static void main(String[] args) throws IOException {
ResourceConfig packagesResourceConfig = new DefaultResourceConfig();
Application app = new Application() {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> res = new HashSet<>();
res.add(org.example.MainResource.class);
return res;
}
};
packagesResourceConfig.add(app);
HttpServerFactory.create("http://localhost:8080/", packagesResourceConfig).start();
}
}
See this line "The ResourceConfig instance does not contain any root resource classes" in the error message?
You did not set any resource for the http server.
What I will do is use this method:
GrizzlyHttpServerFactory.createHttpServer("http://localhost:9998/", new Application());
The new Application() will create a new ResourceConfig class for the http server. You should check the jersey's documents for that, it`s just a simple class which contains a java package.
My ResourceConfig is likes below:
import org.glassfish.jersey.server.ResourceConfig;
public class Application extends ResourceConfig {
public Application() {
packages("ftp.recourse");
}
}
While the ftp.recourse package contains all the path and operations like GET, PUT, POST.
Check the jersey`s official documents for more detials. Hope this will help
You should do the following:
final com.sun.jersey.api.core.ResourceConfig packagesResourceConfig = new com.sun.jersey.api.core.ResourceConfig("net.wjlafrance.jerseyfun") ;
HttpServerFactory.create("http://localhost:9998/", packagesResourceConfig).start();

Categories

Resources