Interceptor not being called on Payara 5.184 - java

I am running a simple Maven Java EE web project on Payara
I am trying demonstrate the working of Interceptor but it isn't getting called. I have even defined it in a beans.xml file
Payara Version: 5.184
Edition: Full
JDK Version: 1.8, Java EE 7
Operating System: Mac
Database: Oracle
Bean class
package com.maven.web;
import com.interceptors.LogNameInterceptor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.interceptor.Interceptors;
#ManagedBean
#Stateless
public class UserBean implements User {
private String firstName;
private String lastName;
public static final Logger LOGGER = Logger.getLogger(UserBean.class.getName());
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
#Interceptors(LogNameInterceptor.class)
public String show(String fn, String ln) {
LOGGER.log(Level.INFO, "Inside method");
return "result";
}
}
User.java
package com.maven.web;
import javax.ejb.Remote;
#Remote
public interface User {
public String show(String a, String b);
}
Interceptor class
package com.interceptors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
#Interceptor
public class LogNameInterceptor {
public static final Logger LOGGER = Logger.getLogger(LogNameInterceptor.class.getName());
#AroundInvoke
public Object aroundInvoke(InvocationContext ctx) throws Exception {
LOGGER.log(Level.INFO, "Inside Interceptor");
System.out.println(ctx.getMethod());
return ctx.proceed();
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans 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/beans_1_0.xsd">
<interceptors>
<class>com.interceptors.LogNameInterceptor</class>
</interceptors>
</beans>
Only 'Inside method' is printed in the log, meaning it doesn't reach the aroundInvoke method
Thanks a lot!

Related

Java Spring Boot problem LoggiFailureAnalysisReporter

I am new to Boot-Spring apparently, I mostly copy some code from youtube on this case. However, after modification, in the end, I got a message like this;
APPLICATION FAILED TO START
Description:
Field postService in com.example.demo.BlogController required a bean of type 'Server.PostService' that could not be found.
Action:
Consider defining a bean of type 'Server.PostService' in your configuration.
.....Any idea how to deal with this situation. Thank you for the support.
1stclass-BlogApplciation-----com.example.demo(package)
2nd-Blog Controller--------same package as BlogApplication
3rdclass-Post---entities
4rthclass-PostRepositories---Repositories
**package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}**
**package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import Server.PostService;
import entities.Post;
import java.util.Date;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value="/")
public String index() {
return "index";
}
#GetMapping(value="/posts")
public List<Post>posts(){
return postService.getAllPosts();
}
#PostMapping(value="/post")
public void publishPost(#RequestBody Post post) {
if(post.getDatecreation() == null)
post.setDatecreation(new Date());
postService.insert(post);
}
}**
**package entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String body;
private Date Datecreation;
public Post() {
}
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 String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Date getDatecreation() {
return Datecreation;
}
public void setDatecreation(Date datecreation) {
this.Datecreation = datecreation;
}
}**
**package Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import entities.Post;
#Repository
public interface PostRepository extends JpaRepository<Post,Long>{
}**
Your BlogApplication Class, which is the class annotated with #SpringBootApplication is in the package com.example.demo. That means that, by default, Spring is going to launch a Component Scan starting from that package.
The problem is that your class PostService and your interface PostRepository are not in the same package as (or in a sub-package of) com.example.demo, so Spring can't find them and won't automatically create these beans for you.
To correct this issue, move the packages you created inside your root package (com.example.demo).
You can find more information about the use of #SpringBootApplication here.
EDIT:
You are missing PostService class or you have imported incorrect class as Server.PostService.
try to create a service like this one:
#Component
public class PostService {
public List<Post> getAllPosts(){
//your code
}
}

mongoTemplate bean could not be found

I am building a very simple Spring boot app with mvc + mongodb. I used Spring initializer to create the proj with web, thymeleaf and mongo dependencies. I have one controller, one model and a view but I keep on getting an error when trying to execute the app:
Description:
Field repo in com.example.CustomerController required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
CustomerController:
import model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Hello on 25/04/2017.
*/
#Controller
#RequestMapping("/home")
public class CustomerController {
#Autowired
CustomerMongoRepo repo;
#RequestMapping(value = "/home", method= RequestMethod.GET)
public String viewingHome(Model model){
//initDB();
model.addAttribute("key", "THIS IS FROM THE MODEL");
return "homepage";
}
}
CustomerMongoRepo:
import org.springframework.data.repository.CrudRepository;
import model.Customer;
public interface CustomerMongoRepo extends CrudRepository {}
MainApp:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class DemoApplication extends WebMvcAutoConfiguration {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Customer Model:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by Hello on 25/04/2017.
*/
#Document(collection = "customerCollection")
public class Customer {
#Id
private int id;
private String fName;
private String sName;
public Customer(){}
public Customer(int id, String fName, String sName){
setfName(fName);
setsName(sName);
setId(id);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
}
My Application Properties:
spring.data.mongodb.database=customer
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true
You are excluding Mongo Configuration.
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
Then how will spring create mongoTemplate for you. Remove this exclusion or create MongoTemplate manually and register it with application context(using #Bean)
I recently ran into this same problem and my solution was to remove spring-data-mongodb:
<!--<dependency>-->
<!-- <groupId>org.springframework.data</groupId>-->
<!-- <artifactId>spring-data-mongodb</artifactId>-->
<!-- <version>3.2.1</version>-->
<!--</dependency>-->
and I kept spring-boot-starter-data-mongodb:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
It is seen that either the two together gave conflict or I need to add 'something' that I did not know.
Happy code !!! And I hope to be of help to you
Update
Later I found something related to what could be described by the problem although I would never finish checking it:
https://stackoverflow.com/a/12389842/7911776

Spring Boot MVC mapping

I have problem with my Spring project. I just started with Spring Boot and i try to make ez controller which redirect me to another web.
When i started my application and go to browser on
localhost:8080/person
there is problem with mapping idk why
enter image description here
This is my structure
enter image description here
PersonController
package Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import Model.Person;
public class PersonController {
#RequestMapping("/person")
public String person(Model model)
{
Person p = new Person();
p.setFirstName("John");
p.setLastName("BonJovi");
p.setAge(23);
model.addAttribute("person", p);
return "personview";
}
}
Person Class
package Model;
public class Person {
String firstName;
String lastName;
int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And "Main"
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#EnableAutoConfiguration
#ComponentScan({"demo","controller"})
public class EducationProjectApplication {
public static void main(String[] args) {
SpringApplication.run(EducationProjectApplication.class, args);
}
}
Add a #Controller to the top of your PersonController
Also - just check, your #ComponentScan({"demo","controller"})
"controller" is not capitalized, but your package is declared "Controller"
You must annotated your PersonController class as #RestController.
Like Rafael said you need to put annotations above PersonController class. #RestController if you want to build a REST controller, #Controller if you want to build normal website. Make sure you already configure your view resolver so it will return a jsp files.

What location to put spring bean configuration file

I am implementing a simple application to do CRUD operations, using Spring framework.
Source code:
User.java is the model class.
package com.vipin.model;
public class User {
private int ssn;
private String firstName;
private String lastName;
private String emailId;
public int getSsn() {
return ssn;
}
public void setSsn(int ssn) {
this.ssn = ssn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Dao layer:
package com.vipin.dao;
import com.vipin.model.User;
public interface DBOpsDao {
boolean add(User user);
boolean find(int ssnId);
}
The class which implements (skelton) implementation is:
package com.vipin.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.vipin.model.User;
public class DefaultDBOpsDaoImpl implements DBOpsDao {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
#Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
System.out.println("Datasource value is " + dataSource);
}
public boolean add(User user) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
return false;
}
public boolean find(int ssnId) {
// TODO Auto-generated method stub
return false;
}
}
Sample Main class:
package com.vipin.app;
import com.vipin.dao.DBOpsDao;
import com.vipin.dao.DefaultDBOpsDaoImpl;
import com.vipin.model.User;
public class MainApp {
public static void main(String[] args) {
System.out.println("Inside main...");
DBOpsDao dao = new DefaultDBOpsDaoImpl();
User user = new User();
user.setFirstName("xxx");
user.setLastName("yyy");
user.setSsn(1);
user.setEmailId("xxx.yyy#example.com");
dao.add(user);
}
}
I am using maven to build this, so the java source code is in:
src/main/java (top level package com.vipin)
When i run this program it is throwing exception complaining that spring.xml doesn't exist. I
used ApplicationContext, one of implementation ClassPathXmlApplicationContext.
In which location do i need to put spring.xml file?
Any inputs would be helpful.
You will need to add spring.xml file at the location - src/main/resources folder. You can have your directory structure inside this directory as - src/main/resources/com/vipin/dao.
src/main/java directory is preferred for java classes.
If you are debugging from eclipse, make sure that you are adding your folder in the project's classpath.
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
If you create your maven project using maven archetype and you import into eclipse, you need to edit your .classpath file.
You have to initilalize application context properly in your main method. You can check this link for example.
Place the xml file at the root of your classpath
For maven that is src/main/resources/ if the directory doesn't exist yet, create it.
src/main/resources/applicationContext.xml
Also src/main/resources/spring/ works as well.

Entity Beans inside EJB Project class mapping

I am using Eclipse and Derby database (with Embeeded Driver). As a starting point I am running the asadmin (from glassfish) to start-database from there. The database within eclipse can be pinged, as well as connected to just fine. Having started my EJB project which combines the session beans and entity beans I have ran into the following exception - java.lang.IllegalArgumentException: Unknown entity bean class: class model.Userbay, please verify that this class has been marked with the #Entity annotation.
Just few lines below this error i get pointed to this line of code - Userbay user = emgr.find(model.Userbay.class, username);
Although my feeling is that it could be a problem with the persistence.xml that causes it in the first place.
I would really appreciate any hints/help given towards fixing this annoying problem me and my friend are facing for quite a time now..
The following are the java/xml files;
Persistence.xml (which is stored under ejbModule/META-INF)
<?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="EJBAuctionv2">
<class>model.Userbay</class>
<class>model.Item</class>
<class>model.Category</class>
</persistence-unit>
</persistence>
I've also tried adding the following properties tag - however it grants another error org.apache.derby.client.am.SqlException: Schema 'ADRIAN' does not exist
<properties>
<property name="javax.persistence.jdbc.password" value="test" />
<property name="javax.persistence.jdbc.user" value="adrian" />
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeededDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:C:/Users/Adrian/MyDB;create=true" />
</properties>
userRegistrationSB.java (Session Bean)
package auction;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Singleton;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.Userbay;
/**
* Session Bean implementation class userRegistrationSB
*/
#Remote #Stateless
public class userRegistrationSB implements userRegistrationSBRemote {
//#EJB private Userbay user;
#PersistenceContext private EntityManager emgr;
/**
* Default constructor.
*/
public userRegistrationSB() {
// TODO Auto-generated constructor stub
System.out.println("TEST2");
}
#Override
public boolean registerUser(String username, String password, String email,
String firstname, String lastname) {
boolean registered = false;
System.out.println("Registering an user");
Userbay user = emgr.find(model.Userbay.class, username);
if (user != null) {
System.out.println("Username doesn't exist.");
registered = true;
} else {
registered = false;
System.out.println("Username already exists.");
}
return registered;
}
#Override
public boolean userExists(String username) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean userMatchesPassword(String username, String password) {
// TODO Auto-generated method stub
return false;
}
}
Userbay.java (Entity Bean)
package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity #Table (name = "Userbay")
/*#NamedQuery(name="Userbay.findAll", query="SELECT u FROM Userbay u")*/
public class Userbay implements Serializable {
private static final long serialVersionUID = 1L;
#Id #Column(name="USER_NAME")
private String userName;
private String email;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="PASSWORD")
private String password;
//bi-directional many-to-one association to Item
#OneToMany(mappedBy="userbay")
private List<Item> items;
public Userbay() {
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Item> getItems() {
return this.items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Item addItem(Item item) {
getItems().add(item);
item.setUserbay(this);
return item;
}
public Item removeItem(Item item) {
getItems().remove(item);
item.setUserbay(null);
return item;
}
}
I've also tried adding the following properties tag - however it
grants another error org.apache.derby.client.am.SqlException: Schema
'ADRIAN' does not exist
Have you checked if your database schema was actually created? If it did not, adding the following lines in your persistence.xml might help.
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
You may also want to undeploy your application manually or if it is your developer machine and this is the only application deployed merely delete content of the applications directory in your domain.

Categories