"NullPointerException: null" in play framework - java

I am new to play framework and I have project with java in play framework connected to the mongoDB via MorphiaPlay. My problem is that I cannot add data. This is some of my code
public class Sign extends Controller{
static Form<Group> groupForm = form(Group.class);
public static Result index() throws Exception {
// redirect to the "group Result
return redirect(routes.Sign.group());
}
public static Result group() {
return ok(views.html.sign.render(Group.all(), groupForm));
}
public static Result newGroup() {
Form<Group> filledForm = groupForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(views.html.sign.render(Group.all(), filledForm));
} else {
Group.create(filledForm.get());
return redirect(routes.Sign.group());
}
}
}
#Entity
public class Group {
#Id
public ObjectId id;
#Required
public String name;
public String email;
public String username;
public String password;
public static List<Group> all() {
if (MorphiaObject.datastore != null) {
return MorphiaObject.datastore.find(Group.class).asList();
} else {
return new ArrayList<Group>();
}
}
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
And the error is
Execution exception
[NullPointerException: null]
In C:\lo\app\models\Group.java at line 37.
public static void create(Group group) {
MorphiaObject.datastore.save(group);
}
My morphiaObject class
package controllers;
public class MorphiaObject extends GlobalSettings{
static public Mongo mongo;
static public Morphia morphia;
static public Datastore datastore;
#Override
public void onStart(play.Application arg0) {
super.beforeStart(arg0);
Logger.debug("** onStart **");
try {
MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "project");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
Logger.debug("** Morphia datastore: " + MorphiaObject.datastore.getDB());
}
}
Can you please help!

Related

How to implement proxy pattern?

I'm trying to understand how to make and use a proxy design pattern. I have no idea what am i doing wrong. Any suggestions would be appreciated:
Load method should simulate downloading configuration from remote server... and it kinda does. The 2 seconds delay should be launched just once, and then it should go smoothly.
public interface ConfigLoader {
String load();
}
RealObject
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.RandomStringUtils;
import pl.sdacademy.prog.streams.MyExepction;
#Getter
#Setter
public class ConfigLoaderImplementation implements ConfigLoader {
private String configuration;
private String serverUrl;
public ConfigLoaderImplementation(final String serverUrl) {
this.serverUrl = serverUrl;
}
#Override
public String load() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new MyException("Sleeping canceled!", e);
}
System.out.println("Configuration from " + getServerUrl() + " downloaded successfully");
String generatedConfiguration = RandomStringUtils.randomAlphabetic(10);
setConfiguration(generatedConfiguration);
return generatedConfiguration;
}
}
Proxy
import lombok.Data;
#Data
public class ConfigLoaderProxy implements ConfigLoader {
private ConfigLoader proxy;
public ConfigLoaderProxy(String url) {
this.proxy = proxy;
}
#Override
public String load() {
if (proxy == null) {
proxy = new ConfigLoaderImplementation("www.blablA.com");
return proxy.load();
} else {
return proxy.load();
}
//todo
}
}
Test class, with main
public class ConfigLoaderDemo {
public static void main(String[] args) {
ConfigLoader proxy = new ConfigLoaderProxy("sdasd");
proxy.load();
proxy.load();
proxy.load();
}
}
public class ConfigLoaderProxy implements ConfigLoader {
private final ConfigLoader configLoader;
private String configuration;
public ConfigLoaderProxy(final ConfigLoader configLoader) {
this.configLoader = configLoader;
}
#Override
public String load() {
if (configuration == null) {
configuration = configLoader.load();
}
return configuration;
}
}

A NullPointerException is caught when I try to add a new client in a CRUD Spring boot Application

I am doing a CRUD web application using Spring boot, spring mvc and Spring Data JPA. I wanted to test my code in the main class with adding a new client. It returns me a NullPointerException. I already check my code with a debug mode. Honestly I don't see where is exactly the issue, so, if it's possible to help it will be a pleasure.
Entity class :
#Entity
#Table(name="cliente")
public class Cliente implements Serializable{
#Id #GeneratedValue
private Integer idCliente;
private String iceCliente;
private String nombreCliente;
private String apellidoCliente;
private String direccionCliente;
private String telefonoCliente;
private String emailCliente;
private TipoCliente tipoCliente;
private String cuidadCliente;
public Cliente() {
super();
}
public Cliente(String iceCliente, String nombreCliente, String apellidoCliente, String direccionCliente,
String telefonoCliente, String emailCliente, TipoCliente tipoCliente, String cuidadCliente) {
super();
this.iceCliente = iceCliente;
this.nombreCliente = nombreCliente;
this.apellidoCliente = apellidoCliente;
this.direccionCliente = direccionCliente;
this.telefonoCliente = telefonoCliente;
this.emailCliente = emailCliente;
this.tipoCliente = tipoCliente;
this.cuidadCliente = cuidadCliente;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public String getIceCliente() {
return iceCliente;
}
public void setIceCliente(String iceCliente) {
this.iceCliente = iceCliente;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public String getApellidoCliente() {
return apellidoCliente;
}
public void setApellidoCliente(String apellidoCliente) {
this.apellidoCliente = apellidoCliente;
}
public String getDireccionCliente() {
return direccionCliente;
}
public void setDireccionCliente(String direccionCliente) {
this.direccionCliente = direccionCliente;
}
public String getTelefonoCliente() {
return telefonoCliente;
}
public void setTelefonoCliente(String telefonoCliente) {
this.telefonoCliente = telefonoCliente;
}
public String getEmailCliente() {
return emailCliente;
}
public void setEmailCliente(String emailCliente) {
this.emailCliente = emailCliente;
}
public TipoCliente getTipoCliente() {
return tipoCliente;
}
public void setTipoCliente(TipoCliente tipoCliente) {
this.tipoCliente = tipoCliente;
}
public String getCuidadCliente() {
return cuidadCliente;
}
public void setCuidadCliente(String cuidadCliente) {
this.cuidadCliente = cuidadCliente;
}
ClienteService :
#Service
#Transactional
public class ClienteServiceImpl implements ClienteService {
#Autowired
ClienteRepository clienteRepository;
#Override
public Cliente agregarCliente(Cliente cliente) {
return clienteRepository.save(cliente);
}
#Override
public Cliente editarCliente(Cliente cliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(cliente.getIdCliente());
if (clienteDB.isPresent()) {
Cliente clienteUpdate = clienteDB.get();
clienteUpdate.setIdCliente(cliente.getIdCliente());
clienteUpdate.setIceCliente(cliente.getIceCliente());
clienteUpdate.setNombreCliente(cliente.getNombreCliente());
clienteUpdate.setApellidoCliente(cliente.getApellidoCliente());
clienteUpdate.setDireccionCliente(cliente.getDireccionCliente());
clienteUpdate.setCuidadCliente(cliente.getCuidadCliente());
clienteUpdate.setTelefonoCliente(cliente.getTelefonoCliente());
clienteUpdate.setEmailCliente(cliente.getEmailCliente());
clienteRepository.save(clienteUpdate);
return clienteUpdate;
} else {
throw new RessourceNotFoundException(
"Cliente no encontrado con nombre de usuario : " + cliente.getIdCliente());
}
}
#Override
public List<Cliente> obtenerCliente() {
return this.clienteRepository.findAll();
}
#Override
public void removeCliente(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
this.clienteRepository.delete(clienteDB.get());
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
#Override
public Cliente obtenerClientePorId(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
return clienteDB.get();
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
ClienteRepository :
#Repository
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
}
ClienteController :
#RestController
//#RequestMapping("/index")
public class ClienteController {
#Autowired
private ClienteService clienteService;
#GetMapping("/clientes")
public ResponseEntity<List<Cliente>> obtenerCliente() {
return ResponseEntity.ok().body(clienteService.obtenerCliente());
}
#GetMapping("/clientes/{id}")
public ResponseEntity<Cliente> obtenerClientePorId(#PathVariable Integer idCliente) {
return ResponseEntity.ok().body(clienteService.obtenerClientePorId(idCliente));
}
#PostMapping("/clientes")
public ResponseEntity<Cliente> agregarCliente(#RequestBody Cliente cliente) {
return ResponseEntity.ok().body(this.clienteService.agregarCliente(cliente));
}
#PutMapping("/clientes/{id}")
public ResponseEntity<Cliente> editarCliente(#PathVariable Integer idCliente, #RequestBody Cliente cliente) {
cliente.setIdCliente(idCliente);
return ResponseEntity.ok().body(this.clienteService.editarCliente(cliente));
}
#DeleteMapping("/clientes/{id}")
public HttpStatus removeCliente(#PathVariable Integer idCliente) {
this.clienteService.removeCliente(idCliente);
return HttpStatus.OK;
}
Main class :
#SpringBootApplication
//#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class NestideasFacturasApplication {
#Autowired
public static ClienteService clienteService = new ClienteServiceImpl();
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537",
"hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
System.out.println(clienteService);
}
Stacktrace :
Stacktrace
First, for your test scenario, it's better to use ApplicationRunner.
NestideasFacturasApplication must implement ApplicationRunner, and override run method. Then you can write your test scenario in run.
Code :
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario ...
}
}
Second, Change injection of ClienteService like below
#Autowired
private ClienteService clienteService;
So we have (Entire code)
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
#Autowired
private ClienteService clienteService;
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537", "hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
}
}

All JPA queries fail to find any result(even tho data is present in the MySQL DB)

I'm trying to set up javax.Persistence in my project, and I've started to use the basic approach:
EntityManagerGenerator
package olsa.amex.dao;
import javax.persistence.*;
public class EntityManagerGenerator {
private EntityManager currentSession;
private EntityTransaction currentTransaction;
public EntityManager openCurrentSession() {
if ((currentSession == null)||(currentSession != null && !currentSession.isOpen()))
currentSession = getSessionFactory().createEntityManager();
return currentSession;
}
public EntityManager openCurrentSessionwithTransaction() {
if ((currentSession == null)||(currentSession != null && !currentSession.isOpen()))
currentSession = getSessionFactory().createEntityManager();
currentTransaction = currentSession.getTransaction();
currentTransaction.begin();
return currentSession;
}
public void closeCurrentSession() {
if (currentSession != null && currentSession.isOpen())
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
if (currentSession != null && currentSession.isOpen()) {
currentTransaction.commit();
currentSession.close();
}
}
private static EntityManagerFactory getSessionFactory() {
EntityManagerFactory entityManager = Persistence.createEntityManagerFactory("JPAAmex");
return entityManager;
}
public EntityManager getCurrentSession() {
return currentSession;
}
public void setCurrentSession(EntityManager currentSession) {
this.currentSession = currentSession;
}
public EntityTransaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(EntityTransaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
}
ViewAgentSsbDAO(for now I have only implemented findAll and findById)
package olsa.amex.dao;
import java.util.List;
import javax.persistence.TypedQuery;
import com.olsa.amex.entities.ViewAgentssb;
public class ViewAgentSsbDAO implements IGenericDAO<ViewAgentssb,Integer> {
private EntityManagerGenerator hibernateSessionGenerator;
public ViewAgentSsbDAO() {
this.hibernateSessionGenerator = new EntityManagerGenerator();
}
public EntityManagerGenerator getHibernateSessionGenerator() {
return hibernateSessionGenerator;
}
#Override
public void persist(ViewAgentssb entity) throws Exception{
throw new UnsupportedOperationException();
}
#Override
public void update(ViewAgentssb entity) throws Exception {
throw new UnsupportedOperationException();
}
#Override
public ViewAgentssb findById(Integer id) throws Exception{
TypedQuery<ViewAgentssb> query = hibernateSessionGenerator.getCurrentSession().createQuery("from com.olsa.amex.entities.ViewAgentssb as v where v.IDAgent = :id", ViewAgentssb.class);
query.setParameter("id", id);
ViewAgentssb view = query.getSingleResult();
return view;
}
#Override
public void delete(ViewAgentssb entity) throws Exception {
throw new UnsupportedOperationException();
}
#Override
public List<ViewAgentssb> findAll() throws Exception{
List<ViewAgentssb> views = hibernateSessionGenerator.getCurrentSession().createQuery("from com.olsa.amex.entities.ViewAgentssb", ViewAgentssb.class).getResultList();
return views;
}
#Override
public void deleteAll() throws Exception{
throw new UnsupportedOperationException();
}
}
The service class:
package olsa.amex.services;
import java.util.List;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.olsa.amex.entities.ViewAgentssb;
import olsa.amex.dao.ViewAgentSsbDAO;
public class ViewAgentSsbService implements IGenericService<ViewAgentssb,Integer> {
private ViewAgentSsbDAO viewAgentSsbDAO;
private Logger logger = LogManager.getLogger(ViewAgentSsbService.class);
public ViewAgentSsbService() {
this.viewAgentSsbDAO = new ViewAgentSsbDAO();
}
#Override
public void persist(ViewAgentssb entity) throws Exception{
throw new UnsupportedOperationException();
}
#Override
public void update(ViewAgentssb entity) throws Exception{
throw new UnsupportedOperationException();
}
#Override
public ViewAgentssb findById(Integer id) throws Exception {
viewAgentSsbDAO.getHibernateSessionGenerator().openCurrentSession();
ViewAgentssb object = viewAgentSsbDAO.findById(id);
viewAgentSsbDAO.getHibernateSessionGenerator().closeCurrentSession();
return object;
}
#Override
public void delete(ViewAgentssb entity) throws Exception{
throw new UnsupportedOperationException();
}
#Override
public List<ViewAgentssb> findAll() throws Exception{
logger.debug("Sto iniziando la query findAll() per l'entity + " + ViewAgentssb.class);
viewAgentSsbDAO.getHibernateSessionGenerator().openCurrentSession();
List<ViewAgentssb> views = viewAgentSsbDAO.findAll();
logger.debug("La query ha ritornato i seguenti risultati: + " + views.toString());
viewAgentSsbDAO.getHibernateSessionGenerator().closeCurrentSession();
return views;
}
#Override
public void deleteAll() throws Exception{
throw new UnsupportedOperationException();
}
}
the Entity:
package com.olsa.amex.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the view_agentssbs database table.
*
*/
#Entity
#Table(name="view_agentssbs")
#NamedQuery(name="ViewAgentssb.findAll", query="SELECT v FROM ViewAgentssb v")
public class ViewAgentssb implements Serializable {
private static final long serialVersionUID = 1L;
private int active;
private String agencyName;
#Lob
private String agentCode;
#Lob
private String agentName;
#Lob
private String agentPassword;
#Lob
private String agentSurname;
#Lob
private String agentUsername;
private int bExist;
#Lob
private String buyed_visure;
#Lob
private String cervedCreation;
#Lob
private String cervedDisable;
#Lob
private String cervedPassword;
#Lob
private String cervedUsername;
#Lob
private String channel_Code;
private int checkBackOffice;
#Lob
private String codiceOAM;
#Lob
private String company_cancelled_counter;
#Lob
private String company_failed_counter;
#Lob
private String company_inactive_counter;
private String countryResidence;
#Id
private String deviceID;
private String documentExpiryDate;
private String documentIssueBy;
private String documentIssuedOn;
private String documentNumber;
private String documentType;
private String email;
private int enableCrif;
private int enableVisura;
private String expr1;
#Lob
private String failed_search;
#Lob
private String groupAvatar;
#Lob
private String groupName;
private int IDAgency;
private int IDAgent;
private int IDAreaRegion;
private int IDGroup;
private int IDSubRegion;
private byte isSimpleSignature;
#Lob
private String partnerID;
#Lob
private String photo;
private String pin;
#Lob
private String protestPrejudical;
private String regione;
private String role;
private String socialSecurityNumber;
private String subRegion;
private String telephoneCell;
#Lob
private String userActive;
#Lob
private String userBOAsAgent;
#Lob
private String userCreation;
#Lob
private String userDisable;
private int userHasSignature;
private String userID;
#Lob
private String userPasswordExpired;
private int userResetPassword;
#Lob
private String userToken;
#Lob
private String venueCode;
public ViewAgentssb() {
}
public int getActive() {
return this.active;
}
public void setActive(int active) {
this.active = active;
}
public String getAgencyName() {
return this.agencyName;
}
public void setAgencyName(String agencyName) {
this.agencyName = agencyName;
}
public String getAgentCode() {
return this.agentCode;
}
public void setAgentCode(String agentCode) {
this.agentCode = agentCode;
}
public String getAgentName() {
return this.agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentPassword() {
return this.agentPassword;
}
public void setAgentPassword(String agentPassword) {
this.agentPassword = agentPassword;
}
public String getAgentSurname() {
return this.agentSurname;
}
public void setAgentSurname(String agentSurname) {
this.agentSurname = agentSurname;
}
public String getAgentUsername() {
return this.agentUsername;
}
public void setAgentUsername(String agentUsername) {
this.agentUsername = agentUsername;
}
public int getBExist() {
return this.bExist;
}
public void setBExist(int bExist) {
this.bExist = bExist;
}
public String getBuyed_visure() {
return this.buyed_visure;
}
public void setBuyed_visure(String buyed_visure) {
this.buyed_visure = buyed_visure;
}
public String getCervedCreation() {
return this.cervedCreation;
}
public void setCervedCreation(String cervedCreation) {
this.cervedCreation = cervedCreation;
}
public String getCervedDisable() {
return this.cervedDisable;
}
public void setCervedDisable(String cervedDisable) {
this.cervedDisable = cervedDisable;
}
public String getCervedPassword() {
return this.cervedPassword;
}
public void setCervedPassword(String cervedPassword) {
this.cervedPassword = cervedPassword;
}
public String getCervedUsername() {
return this.cervedUsername;
}
public void setCervedUsername(String cervedUsername) {
this.cervedUsername = cervedUsername;
}
public String getChannel_Code() {
return this.channel_Code;
}
public void setChannel_Code(String channel_Code) {
this.channel_Code = channel_Code;
}
public int getCheckBackOffice() {
return this.checkBackOffice;
}
public void setCheckBackOffice(int checkBackOffice) {
this.checkBackOffice = checkBackOffice;
}
public String getCodiceOAM() {
return this.codiceOAM;
}
public void setCodiceOAM(String codiceOAM) {
this.codiceOAM = codiceOAM;
}
public String getCompany_cancelled_counter() {
return this.company_cancelled_counter;
}
public void setCompany_cancelled_counter(String company_cancelled_counter) {
this.company_cancelled_counter = company_cancelled_counter;
}
public String getCompany_failed_counter() {
return this.company_failed_counter;
}
public void setCompany_failed_counter(String company_failed_counter) {
this.company_failed_counter = company_failed_counter;
}
public String getCompany_inactive_counter() {
return this.company_inactive_counter;
}
public void setCompany_inactive_counter(String company_inactive_counter) {
this.company_inactive_counter = company_inactive_counter;
}
public String getCountryResidence() {
return this.countryResidence;
}
public void setCountryResidence(String countryResidence) {
this.countryResidence = countryResidence;
}
public String getDeviceID() {
return this.deviceID;
}
public void setDeviceID(String deviceID) {
this.deviceID = deviceID;
}
public String getDocumentExpiryDate() {
return this.documentExpiryDate;
}
public void setDocumentExpiryDate(String documentExpiryDate) {
this.documentExpiryDate = documentExpiryDate;
}
public String getDocumentIssueBy() {
return this.documentIssueBy;
}
public void setDocumentIssueBy(String documentIssueBy) {
this.documentIssueBy = documentIssueBy;
}
public String getDocumentIssuedOn() {
return this.documentIssuedOn;
}
public void setDocumentIssuedOn(String documentIssuedOn) {
this.documentIssuedOn = documentIssuedOn;
}
public String getDocumentNumber() {
return this.documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
public String getDocumentType() {
return this.documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public int getEnableCrif() {
return this.enableCrif;
}
public void setEnableCrif(int enableCrif) {
this.enableCrif = enableCrif;
}
public int getEnableVisura() {
return this.enableVisura;
}
public void setEnableVisura(int enableVisura) {
this.enableVisura = enableVisura;
}
public String getExpr1() {
return this.expr1;
}
public void setExpr1(String expr1) {
this.expr1 = expr1;
}
public String getFailed_search() {
return this.failed_search;
}
public void setFailed_search(String failed_search) {
this.failed_search = failed_search;
}
public String getGroupAvatar() {
return this.groupAvatar;
}
public void setGroupAvatar(String groupAvatar) {
this.groupAvatar = groupAvatar;
}
public String getGroupName() {
return this.groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getIDAgency() {
return this.IDAgency;
}
public void setIDAgency(int IDAgency) {
this.IDAgency = IDAgency;
}
public int getIDAgent() {
return this.IDAgent;
}
public void setIDAgent(int IDAgent) {
this.IDAgent = IDAgent;
}
public int getIDAreaRegion() {
return this.IDAreaRegion;
}
public void setIDAreaRegion(int IDAreaRegion) {
this.IDAreaRegion = IDAreaRegion;
}
public int getIDGroup() {
return this.IDGroup;
}
public void setIDGroup(int IDGroup) {
this.IDGroup = IDGroup;
}
public int getIDSubRegion() {
return this.IDSubRegion;
}
public void setIDSubRegion(int IDSubRegion) {
this.IDSubRegion = IDSubRegion;
}
public byte getIsSimpleSignature() {
return this.isSimpleSignature;
}
public void setIsSimpleSignature(byte isSimpleSignature) {
this.isSimpleSignature = isSimpleSignature;
}
public String getPartnerID() {
return this.partnerID;
}
public void setPartnerID(String partnerID) {
this.partnerID = partnerID;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getPin() {
return this.pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getProtestPrejudical() {
return this.protestPrejudical;
}
public void setProtestPrejudical(String protestPrejudical) {
this.protestPrejudical = protestPrejudical;
}
public String getRegione() {
return this.regione;
}
public void setRegione(String regione) {
this.regione = regione;
}
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
public String getSocialSecurityNumber() {
return this.socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public String getSubRegion() {
return this.subRegion;
}
public void setSubRegion(String subRegion) {
this.subRegion = subRegion;
}
public String getTelephoneCell() {
return this.telephoneCell;
}
public void setTelephoneCell(String telephoneCell) {
this.telephoneCell = telephoneCell;
}
public String getUserActive() {
return this.userActive;
}
public void setUserActive(String userActive) {
this.userActive = userActive;
}
public String getUserBOAsAgent() {
return this.userBOAsAgent;
}
public void setUserBOAsAgent(String userBOAsAgent) {
this.userBOAsAgent = userBOAsAgent;
}
public String getUserCreation() {
return this.userCreation;
}
public void setUserCreation(String userCreation) {
this.userCreation = userCreation;
}
public String getUserDisable() {
return this.userDisable;
}
public void setUserDisable(String userDisable) {
this.userDisable = userDisable;
}
public int getUserHasSignature() {
return this.userHasSignature;
}
public void setUserHasSignature(int userHasSignature) {
this.userHasSignature = userHasSignature;
}
public String getUserID() {
return this.userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPasswordExpired() {
return this.userPasswordExpired;
}
public void setUserPasswordExpired(String userPasswordExpired) {
this.userPasswordExpired = userPasswordExpired;
}
public int getUserResetPassword() {
return this.userResetPassword;
}
public void setUserResetPassword(int userResetPassword) {
this.userResetPassword = userResetPassword;
}
public String getUserToken() {
return this.userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getVenueCode() {
return this.venueCode;
}
public void setVenueCode(String venueCode) {
this.venueCode = venueCode;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns /persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPAAmex" transaction- type="RESOURCE_LOCAL">
<class>com.olsa.amex.entities.Agency</class>
<class>com.olsa.amex.entities.AgencyRegionView</class>
<class>com.olsa.amex.entities.Agent</class>
<class>com.olsa.amex.entities.AgentAgencyRegionAndSubRegionRel</class>
<class>com.olsa.amex.entities.AgentGroup</class>
<class>com.olsa.amex.entities.AgentsInfo</class>
<class>com.olsa.amex.entities.AmexStatoPriorita</class>
<class>com.olsa.amex.entities.AmexXEROXField</class>
<class>com.olsa.amex.entities.AmexXEROXSection</class>
<class>com.olsa.amex.entities.Application</class>
<class>com.olsa.amex.entities.ApplicationField</class>
<class>com.olsa.amex.entities.ApplicationFieldStatus</class>
<class>com.olsa.amex.entities.ApplicationFieldTemplate</class>
<class>com.olsa.amex.entities.ApplicationFieldTemplateFixedValue</class>
<class>com.olsa.amex.entities.ApplicationOfferAndRegionRel</class>
<class>com.olsa.amex.entities.ApplicationOfferSuppBaseRel</class>
<class>com.olsa.amex.entities.ApplicationPacakge</class>
<class>com.olsa.amex.entities.ApplicationPackageArkDap</class>
<class>com.olsa.amex.entities.ApplicationSection</class>
<class>com.olsa.amex.entities.ApplicationSectionPdf</class>
<class>com.olsa.amex.entities.ApplicationSectionTemplate</class>
<class>com.olsa.amex.entities.ApplicationSignaturePDF</class>
<class>com.olsa.amex.entities.ApplicationStatus</class>
<class>com.olsa.amex.entities.ApplicationTemplate</class>
<class>com.olsa.amex.entities.ApplicationTrace</class>
<class>com.olsa.amex.entities.Applicationproductoffer</class>
<class>com.olsa.amex.entities.AreaRegion</class>
<class>com.olsa.amex.entities.AreaSubRegion</class>
<class>com.olsa.amex.entities.AreamanagerAgent</class>
<class>com.olsa.amex.entities.BankList</class>
<class>com.olsa.amex.entities.Cab</class>
<class>com.olsa.amex.entities.CabList</class>
<class>com.olsa.amex.entities.CervedCredenzial</class>
<class>com.olsa.amex.entities.Comuni</class>
<class>com.olsa.amex.entities.ConfigurazioneSegnalazione</class>
<class>com.olsa.amex.entities.Cordinate_Firma_Agente</class>
<class>com.olsa.amex.entities.Crif</class>
<class>com.olsa.amex.entities.ErrorSqlTrace</class>
<class>com.olsa.amex.entities.InternationalTelPrefix</class>
<class>com.olsa.amex.entities.Level_Rule</class>
<class>com.olsa.amex.entities.Nazionalita</class>
<class>com.olsa.amex.entities.NazioniIso</class>
<class>com.olsa.amex.entities.New</class>
<class>com.olsa.amex.entities.SBS_OfferList</class>
<class>com.olsa.amex.entities.SbsOfferlist</class>
<class>com.olsa.amex.entities.SectionStatus</class>
<class>com.olsa.amex.entities.SegnalazioneApplicationSection</class>
<class>com.olsa.amex.entities.Segnalazioni</class>
<class>com.olsa.amex.entities.StorageCervedVisure</class>
<class>com.olsa.amex.entities.Sysdiagram</class>
<class>com.olsa.amex.entities.Teamleader_AM</class>
<class>com.olsa.amex.entities.TempSignersInfo</class>
<class>com.olsa.amex.entities.TemplateAppkeyStore</class>
<class>com.olsa.amex.entities.TipologiaSegnalazione</class>
<class>com.olsa.amex.entities.TokenPushService</class>
<class>com.olsa.amex.entities.UsedPassword</class>
<class>com.olsa.amex.entities.VersionMobile</class>
<class>com.olsa.amex.entities.ViewAgencyareaandsubareaofferrelation</class>
<class>com.olsa.amex.entities.ViewAgentagencyregionandsubregionrel</class>
<class>com.olsa.amex.entities.ViewAgentsOfAreamanager</class>
<class>com.olsa.amex.entities.ViewAgentssb</class>
<class>com.olsa.amex.entities.ViewApplicationagent</class>
<class>com.olsa.amex.entities.ViewApplicationsegnalazionibackoffice</class>
<class>com.olsa.amex.entities.ViewAreamanagersOfTeamleader</class>
<class>com.olsa.amex.entities.ViewArearegionsubregionrel</class>
<class>com.olsa.amex.entities.ViewControlloallegati</class>
<class>com.olsa.amex.entities.ViewControlloesistenzaagente</class>
<class>com.olsa.amex.entities.ViewGetagentscompleteWoutfk</class>
<class>com.olsa.amex.entities.ViewGetnew</class>
<class>com.olsa.amex.entities.ViewGetsectionandstatus</class>
<class>com.olsa.amex.entities.ViewSection_field</class>
<class>com.olsa.amex.entities.ViewSectioncbsu</class>
<class>com.olsa.amex.entities.ViewXroxsectionandfield</class>
<class>com.olsa.amex.entities.VisureType</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://rmarjboss-001c.customer.olsa:3306/amex_digital_test_dev"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="*******"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
And here's the code I used to test out everything:
try {
logger.info("Hibernate test");
ViewAgentSsbService service = new ViewAgentSsbService();
List<ViewAgentssb> entities = service.findAll();
logger.info(entities.toString());
} catch (Exception e1) {
logger.info("Failed... " + e1.getMessage());
ErrorUtility.getError(e1);
}
And the query successfully starts, but it always returns an empty list, even tho there is data present in the MySQL DB.
EDIT: I know I can use the Repositories, but for now I just want to check if everything works as it should.
I found the problem, apparently it was all caused by the wrong jdbc connection string.
In order to generate the entities I used the following string:
jdbc:mysql://rmarjboss-001c.customer.olsa:3306/amex_digital_sbs_dev?useUnicode=yes&characterEncoding=UTF-8
What I used in my persistence.xml is this:
jdbc:mysql://rmarjboss-001c.customer.olsa:3306/amex_digital_sbs_dev
In order for everything to work correctly, I had to set the correct string in my persistence.xml:
jdbc:mysql://rmarjboss-001c.customer.olsa:3306/amex_digital_sbs_dev?useUnicode=yes&characterEncoding=UTF-8

cannot fetch the exact dto returned from ejb to liferay controller

I am doing a liferay project which use ejb at back end. so my ejb method looks like this:-
#Override
public List<RmisPaymentDetailsDto> getEpaymentDetails(String ebpCode) {
Query q = entityManager.createQuery("select s from EpaymentBo s where s.ebpCode=:ebpcode")
.setParameter("ebpcode",ebpCode);
#SuppressWarnings("unchecked")
List<ProductBo> list = q.getResultList();
Iterator<ProductBo> i = list.iterator();
List<RmisPaymentDetailsDto> rList = new ArrayList<RmisPaymentDetailsDto>();
while(i.hasNext()){
EpaymentBo ep =(EpaymentBo) i.next();
RmisPaymentDetailsDto dto = new RmisPaymentDetailsDto();
dto.setAdvertisementcode(ep.getAdvertisementcode());
dto.setAmount(ep.getAmount());
dto.setStudentmasterid(ep.getStudentmasterid());
dto.setEbpgendate(ep.getEbp_gen_date());
dto.setEbpcode(ep.getEbpCode());
dto.setPaymentstatus(ep.getPaymentstatus());
dto.setCandidatenameinnepali(ep.getCandidatenameinnepali());
rList.add(dto);
}
return rList;
}
the above method successfully fetches data from database and sets it to my RmisPaymentDetailsDto.
like this:-
now i am calling same method from my liferay controlller.
PreExaminationRemote preRef = (PreExaminationRemote) jndiContext
.lookup("PreExamination/remote");
List<RmisPaymentDetailsDto> rDto = preRef.getEpaymentDetails(ebpCode);
I am wondering how my one property(candidatenameinnepali) is lost as i return same dto from my ejb.
My dto looks like this:-
public class RmisPaymentDetailsDto implements Serializable {
private static final long serialVersionUID = 1L;
private String advertisementcode;
private String ebpcode;
private String amount;
private String studentmasterid;
private Date ebpgendate;
private String paymentstatus;
private String candidatenameinnepali;
public String getCandidatenameinnepali() {
return candidatenameinnepali;
}
public void setCandidatenameinnepali(String candidatenameinnepali) {
this.candidatenameinnepali = candidatenameinnepali;
}
public String getAdvertisementcode() {
return advertisementcode;
}
public void setAdvertisementcode(String advertisementcode) {
this.advertisementcode = advertisementcode;
}
public String getEbpcode() {
return ebpcode;
}
public void setEbpcode(String ebpcode) {
this.ebpcode = ebpcode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getStudentmasterid() {
return studentmasterid;
}
public void setStudentmasterid(String studentmasterid) {
this.studentmasterid = studentmasterid;
}
public Date getEbpgendate() {
return ebpgendate;
}
public void setEbpgendate(Date ebpgendate) {
this.ebpgendate = ebpgendate;
}
public String getPaymentstatus() {
return paymentstatus;
}
public void setPaymentstatus(String paymentstatus) {
this.paymentstatus = paymentstatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

Cannot resolve reference Local ejb-ref

I have an issue in programming an EJB application. I search a solution but I still have the same problem in intelliJ with Glassfish4 :
" Cannot resolve reference [Local ejb-ref name=EJB.AdminEJB,Local 3.x interface =Interface.AdminInterface,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session] because there are [2] ejbs in the application with interface Interface.AdminInterface."
And excuse-me for my english, I'm french.
AdminInterface in a package Interface
#Local
public interface AdminInterface {
public void creerParieur(Parieur parieur);
public void supprimerParieur (String login);
public void creerBookmaker(Bookmaker bookmaker);
public void supprimerBookmaker (String login);
public void modifParieur (Parieur parieur);
public void modifBookmaker (Bookmaker bookmaker);
public void ajouterCote(Cote cote);
public void ajouterMatch (Match match);
public List<Cote> listeCote(String log);
public List<Match> listeMatch();
public List<Parieur> listeParieur();
public List<Bookmaker> listeBookmaker();
public Parieur rechercheParieur(String id);
public Bookmaker rechercheBookmaker (String id);
public void setLogin(String login);
public String getLogin();
}
AdminEJB in a package EJB
#Stateless
public class AdminEJB implements AdminInterface{
String login;
String mdp;
#PersistenceContext(unitName = "NewPersistenceUnit")
EntityManager em;
public AdminEJB(){}
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login=login;
}
public String getMdp(){
return mdp;
}
public void setMdp(String mdp){
this.mdp=mdp;
}
public void creerParieur(Parieur parieur){
em.persist(parieur);
}
public void supprimerParieur(String login){
Parieur parieur=new Parieur ();
Query req=em.createQuery("select OBJECT(P) from Parieur P where P.login=:login");
req.setParameter("login", login);
parieur=(Parieur)req.getSingleResult();
em.remove(parieur);
}
public void modifParieur(Parieur parieur){
em.merge(parieur);
}
public List<Parieur> listeParieur(){
Query req=em.createQuery("select OBJECT(P) from Parieur P");
return req.getResultList();
}
public void creerBookmaker(Bookmaker bookmaker){
em.persist(bookmaker);
}
public void supprimerBookmaker(String login){
Bookmaker bookmaker;
Query req=em.createQuery("select OBJECT(B) from Bookmaker B where B.pseudo=:login");
req.setParameter("login", login);
bookmaker=(Bookmaker)req.getSingleResult();
em.remove(bookmaker);
}
public void modifBookmaker(Bookmaker bookmaker){
em.merge(bookmaker);
}
public List<Bookmaker> listeBookmaker(){
Query req=em.createQuery("select OBJECT(B) from Bookmaker B");
return req.getResultList();
}
public List<Match> listeMatch(){
Query req=em.createQuery("select OBJECT(M) from Match M");
return req.getResultList();
}
public Bookmaker rechercheBookmaker(String id){
return em.find(Bookmaker.class,id);
}
public Parieur rechercheParieur(String id){
return em.find(Parieur.class,id);
}
public void ajouterCote (Cote cote){
em.persist(cote);
}
public void ajouterMatch (Match match){
em.persist(match);
}
public List<Cote> listeCote(String log){
Bookmaker bookmaker = new Bookmaker();
bookmaker = this.rechercheBookmaker(log);
Query req = em.createQuery("select OBJECT(C) from Cote C where C.bookmaker=:bookmaker");
req.setParameter("bookmaker", bookmaker);
return req.getResultList();
}
}
ControlerBean in a package ManagedBean
#ManagedBean
#RequestScoped
public class ControlerBean implements Serializable{
Bookmaker bookmaker;
Pari pari;
Parieur parieur;
Match match;
Cote cote;
String nomObjetP;
String nomEnP;
String pseudoUser;
String pwdUser;
#EJB
private AdminInterface admin;
public ControlerBean(){
bookmaker = new Bookmaker();
parieur = new Parieur();
cote = new Cote();
match= new Match();
pari= new Pari();
}
public String getNomObjetP() {
return nomObjetP;
}
public void setNomObjetP(String nomObjetP) {
this.nomObjetP = nomObjetP;
}
public String getNomEnP() {
return nomEnP;
}
public void setNomEnP(String nomEnP) {
this.nomEnP = nomEnP;
}
public Pari getPari() {
return pari;
}
public void setPari(Pari pari){
this.pari=pari;
}
public Bookmaker getBookmaker() {
return bookmaker;
}
public void setBookmaker(Bookmaker bookmaker) {
this.bookmaker = bookmaker;
}
public Parieur getParieur() {
return parieur;
}
public void setParieur(Parieur parieur) {
this.parieur = parieur;
}
public Cote getCote() {
return cote;
}
public void setCote(Cote cote) {
this.cote = cote;
}
public Match getMatch(){
return match;
}
public void setMatch(Match match){
this.match=match;
}
public AdminInterface getAdmin() {
return admin;
}
public void setAdmin(AdminInterface admin) {
this.admin = admin;
}
public String getPseudoUser() { return pseudoUser; }
public void setPseudoUser(String pseudoUser) {
this.pseudoUser = pseudoUser;
}
public String getPwdUser() {
return pwdUser;
}
public void setPwdUser(String pwdUser) {
this.pwdUser = pwdUser;
}
public String addParieur(){
parieur.setArgent(1000);
admin.creerParieur(parieur);
return "OK";
}
public String modifParieur(){
admin.modifParieur(parieur);
return "OK";
}
public String supprParieur(){
admin.supprimerParieur(parieur.getLogin());
return "OK";
}
public String addBookmaker(){
admin.creerBookmaker(bookmaker);
return "OK";
}
public String modifBookmaker(){
admin.modifBookmaker(bookmaker);
return "OK";
}
public String supprBookmaker(){
admin.supprimerBookmaker(bookmaker.getPseudo());
return "OK";
}
public List<Bookmaker> listeBookmaker(){
return admin.listeBookmaker();
}
public List<Parieur> listeParieur(){
return admin.listeParieur();
}
public List<Match> listeMatch(){ return admin.listeMatch(); }
public String addCote(){
pseudoUser = admin.getLogin();
cote.setBookmaker(admin.rechercheBookmaker(pseudoUser));
admin.ajouterCote(cote);
return "OK";
}
public String addMatch(){
admin.ajouterMatch(getMatch());
return "OK";
}
}
Thank's very much for any help
When you have two EJBs implementing the same interface they need to be differentiated so that the container knows which one to inject.
Add the name parameter in the #Stateless annotation to all beans implementing the same interface. In the #EJB annotation, use the beanName parameter to inject the appropriate session bean implementation.
#Stateless(name="AdminEJB1")
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB1")
private AdminInterface myAdminEjb;
You can also skip the name parameter in the #Stateless annotation and then use the name of the implementing class as the beanName parameter in the #EJB annotation.
#Stateless
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB")
private AdminInterface myAdminEjb;
I had same error, but I didn't work with one interface for different EJBs (generated local Session Beans from entity classes). So I am putting this answer if somebody had same problem as me, as I didn't found one here. My framework generated "ejb-local-ref" tag in pom.xml on its own. After deleting it, all works perfectly.
Another cause for this problem, although uncommon, may be the delay in communicating with the JMX port. To get around this it is possible to put the key -Dhk2.parser.timeout = 300

Categories