J2EE NetBeans em.persistance(something) doesn't add data in table - java

I'm writing my first project with J2EE. I would like to populate some tables of a DB by a servlet.
For example:
This is my entity "Administrator.java"
package cinema.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Amministratore implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String user_name;
private String psw;
private String name;
private String surname;
private String email;
public Administrator () {
}
public Administrator (String user_name, String name, String surname,String psw, String email) {
this.user_name=user_name;
this.name=name;
this.surname=surname;
this.psw=psw;
this.email=email;
}
public String getPsw () {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
public String getUserName () {
return user_name;
}
public void setUserName (String user_name) {
this.user_name=user_name;
}
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 String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname=surname;
}
public String getEmail() {
return email;
}
public void getEmail(String email) {
this.email=email;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Amministratore)) {
return false;
}
Amministratore other = (Amministratore) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "cinema.entity.Amministratore[ id=" + id + " ]";
}
}
This is my servlet:
package cinema.servlet;import cinema.entity.Administrator;
import cinema.interfacce.AdminBeanRemote;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "InitializeServlet", urlPatterns = {"/InitializeServlet"})
public class InitializeServlet extends HttpServlet {
#EJB
AdminBeanRemote adminBean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
adminBean.cleanAdmin();
adminBean.addNewAdmin("admin1", "Silvia", "Fichera", "admin1", "admin1#cinema.it");
adminBean.addNewAdmin("admin2", "Giulia", "Fichera", "admin2", "admin2#cinema.it");
adminBean.addNewGestore("gestore1", "Mike", "Bongiorno", "gestore1", "gestore1#cinema.it");
adminBean.addNewAdmin("gestore2", "Carlo", "Conti", "gestore2", "gestore2#cinema.it");
try {
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
} finally {
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
And in AdminBean I have the functions cleanAdmin() and addNewAdmin:
package cinema.bean;
import cinema.entity.*;
import cinema.interfacce.AdminBeanRemote;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;`
#Stateless
#Remote
public class AdminBean implements AdminBeanRemote {
#PersistenceContext
private EntityManager em;
#Override
public void cleanAdmin() {
List admin = em.createQuery("SELECT c FROM Administrator c").getResultList();
for(Iterator iter = admin.iterator(); iter.hasNext();) {
em.remove(iter.next());
}
em.flush();
}
#Override
public boolean addNewAdmin(String user_name, String name, String surname, String psw, String email)throws PersistenceException {
if(em.find(Administrator.class, user_name)!=null) {
System.out.println("Admin already existing");
return false;
}else{
Administrator administrator;
administrator = new Administrator(user_name, name, surname, psw, email);
em.persist(administrator);
}
return true;
}
}
Any suggestions?
I can't find the file persistance.xml and NetBeans creates my tables in its samples db.
Thanks for your help and sorry if there's incorrect syntax!

Related

User Update Test in the Junit Doesn't Work

I'm trying make a test to Update User method that first get a User by id and after update the user , work it, but when I try to make a test in the Junit show me that couldn't find the user by Id. Can anyone help me, please?
UserClass
package br.com.projectsmanagement.entities;
import java.util.Date;
import java.util.Objects;
import jakarta.persistence.*;
#Entity
#Table(name = "tb_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro;
public User() {
}
public User(String name, String email, String password, Date dataCadastro) {
this.name = name;
this.email = email;
this.password = password;
this.dataCadastro = dataCadastro;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return Objects.equals(id, other.id);
}
}
UserServiceImpl
#Override
public User updateUser(Long id, User user) {
try {
User userUpdated = userRepository.findById(id).get();
userUpdated.setName(user.getName());
userUpdated.setPassword(user.getPassword());
return userRepository.saveAndFlush(userUpdated);
} catch (NoSuchElementException e) {
throw new InvalidIdException("Usuário não encontrado!");
}
}
And finally my UserServiceImplTest
package br.com.projectsmanagement.services.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import br.com.projectsmanagement.entities.User;
import br.com.projectsmanagement.exception.EmailExistException;
import br.com.projectsmanagement.repositories.UserRepository;
#SpringBootTest
class UserServiceImplTest {
#InjectMocks
private UserServiceImpl userServiceImpl;
#Mock
private UserRepository userRepository;
private User user;
private Optional<User> optionalUser;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
startUser();
}
#Test
void whenFindAllThenReturnAnListofUsers() {
when(userRepository.findAll()).thenReturn(List.of(user));
List<User> response = userServiceImpl.listUsers();
assertNotNull(response);
assertEquals(1, response.size());
assertEquals(User.class, response.get(0).getClass());
}
#Test
void whenFindByIdThenReturnAnUserInstance() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
Optional<User> response = userServiceImpl.getUserById(1L);
assertThat(response).isPresent();
assertEquals(optionalUser.getClass(), response.getClass());
assertEquals(optionalUser.get().getName(), "Valdir");
}
#Test
void whenRegisterThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenRegisterThenReturnAnEmailExistException() {
when(userRepository.findByEmail(anyString())).thenReturn(user);
try {
userServiceImpl.registerUser(user);
} catch (ClassCastException e) {
assertEquals(EmailExistException.class, e.getClass());
assertEquals("Esse e-mail já está cadastrado!", e.getMessage());
}
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}
#Test
void testDeleteUser() {
fail("Not yet implemented");
}
private void startUser() {
user = new User("Valdir", "valdir#gmail.com", "123456", new Date());
optionalUser = Optional.of(new User("Valdir", "valdir#gmail.com", "123456", new Date()));
}
}
I modified my class many times, but even doesn't work it
I think in your test case whenUpdateThenReturnSuccess(), you forgot to mock the userRepository.findById(id) that you call when updating your user.
If not mocked, it returns null.
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
when(userRepository.saveAndFlush(any(User.class))).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}

How to validate the Nested Objects using Spring Validation in Spring boot?

I am developing a project in which one of the many requirement is to custom validate the two objects for which I am passing both objects to the controller from a single form.
I am frequently receiving the exception on the particular statement which I don't know how to manage or solve it.
package com.practive.course.configure;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.practive.course.model.Credentials;
import com.practive.course.model.Student;
#Component
public class StudentValidator implements Validator {
private final Validator credentialValidator;
public StudentValidator(Validator credentialValidator) {
if (credentialValidator == null) {
throw new IllegalArgumentException(
"The supplied [Validator] is required and must not be null.");
}
if (!credentialValidator.supports(Credentials.class)) {
throw new IllegalArgumentException(
"The supplied [Validator] must support the validation of [Address] instances.");
}
this.credentialValidator = credentialValidator;
}
/**
* This Validator validates Customer instances, and any subclasses of Customer too
*/
public boolean supports(Class clazz) {
return Student.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
Student student = (Student) target;
System.out.println(student.getMyname());
System.out.println("below");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty"); //this line generates the exception
System.out.println("above");
//ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
try {
errors.pushNestedPath("credentials");
ValidationUtils.invokeValidator(this.credentialValidator, student.getCred(), errors);
} finally {
errors.popNestedPath();
}
}
}
#PostMapping("/registration")
public String postRegister(Student student,Credentials credential,BindingResult bindingResult,RedirectAttributes redirect) {
try{
validator.validate(student,bindingResult);
}catch(Exception e) {
System.out.println("problem is here "+e.getMessage());
}
try {
if(bindingResult.hasErrors()) {
return "registration";
}
}catch(Exception e) {
System.out.println("problem is in biding "+e.getMessage());
}
appService.registerStudent(student,credential);
return "redirect:/login";
}
package com.practive.course.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
#Entity
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String myname;
private String mobile;
private String email;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="credid")
private Credentials cred;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMyname() {
return myname;
}
public void setMyname(String myname) {
this.myname = myname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Credentials getCred() {
return cred;
}
public void setCred(Credentials cred) {
this.cred = cred;
}
}
package com.practive.course.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Credentials {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String usermobile;
private Role roles;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsermobile() {
return usermobile;
}
public void setUsermobile(String usermobile) {
this.usermobile = usermobile;
}
public Role getRoles() {
return roles;
}
public void setRoles(Role roles) {
this.roles = roles;
}
}
The stacktrace :
Invalid property 'email' of bean class [com.practive.course.model.Credentials]: Bean property 'email' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The above exception is being generated when I am trying to validate
The stacktrace shows that Invalid property 'email' of bean class [com.practive.course.model.Credentials] , the validator method is trying to get the email property of the Credentials object while from your code it is visible that the "email" is part of the Student class.

Getting Date as null when using java.sql.Date

I am trying to insert the date into database and I am using java.sql.Date but the problem when user is submitting the form I am getting Null value. As per some restriction I am only allowed to use java.sql.Date not util.Date.
Entity
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="Users")
public class Users {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="User_ID")
private int ID;
#Column(name="User_first_name")
#NotEmpty(message="Field cannot be left blank")
private String First_Name;
#Column(name="user_last_name")
private String Last_Name;
#Column(name="user_contact")
private int Contact;
#Column(name="user_email")
private String Email;
#Column(name="user_date_birth")
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date DateOfBirth;
#Column(name="user_joining_date")
private Date DateOfJoining;
#Column(name="user_salary")
#NotNull
private int Salary;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public int getContact() {
return Contact;
}
public void setContact(int contact) {
Contact = contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public Date getDateOfJoining() {
return DateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
DateOfJoining = dateOfJoining;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
}
Controller
package com.example.crud;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.crud.entities.Users;
import com.example.crud.service.TaskService;
#Controller
public class HomeController {
#Autowired
private TaskService service;
private Logger logger = LoggerFactory.getLogger(HomeController.class);
#InitBinder
public void initBinder(WebDataBinder binder){
System.out.println("exe");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(java.sql.Date.class,"DateOfBirth", new CustomDateEditor(sdf, true));
}
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String index(Map<String, Object> model){
Users users = new Users();
model.put("users", users);
logger.debug("users");
return "home";
}
#RequestMapping(value="/Register", method=RequestMethod.POST)
public String Register(#ModelAttribute("users") Users users, BindingResult result, Model model){
System.out.println(users.getFirst_Name());
System.out.println(users.getDateOfBirth());
// service.Register(users);
return "home";
}
}
Register your own custom editor.
public class SqlDateEditor extends PropertyEditorSupport {
private DateFormat dateFormat;
public SqlDateEditor (final DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
#Override
public void setAsText(String text) {
try {
setValue(new java.sql.Date(this.dateformat.parse(text).getTime())
} catch (ParseException e) {
throw new IllegalArgumentException("Could not parse date: " + e.getMessage());
}
}
#Override
public String getAsText() {
java.sql.Date value = (java.sql.Date) getValue();
return (value != null ? this.dateFormat.format(value) : "");
}
}
At your controller:
#InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(java.sql.Date.class, new SqlDateEditor(new SimpleDateFormat("dd/MM/yyyy")));
}

Remove a filed from JSON response?

I have already created a restful api using java and glassfish but I'm facing a problem (not an error).
When I receive the JSON response from my API it works fine but contains the name of the beans.
{"***countriesBean***":[ //(I need my response without this field)
{"CountryID":"3","CountryName":"asdasdasd","DefaultCurrencyID":"0","DefaultLanguageID":"0"},{"CountryID":"16","CountryName":"sddd","DefaultCurrencyID":"1","DefaultLanguageID":"0"},{"CountryID":"1","CountryName":"Lebanon","DefaultCurrencyID":"3","DefaultLanguageID":"0"},{"CountryID":"2","CountryName":"asdasd","DefaultCurrencyID":"0","DefaultLanguageID":"2"}
]
}
this is the bean
package beans;
import javax.ws.rs.FormParam;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author ahmad.s
*/
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class CountriesBean {
// #XmlElement
#XmlElement(name="CountryID")
private Integer COUNTRY_ID;
#XmlElement(name="CountryName")
private String COUNTRY_NAME;
#XmlElement(name="LanguageID")
private Integer LANGUAGE_ID;
#XmlElement(name="DefaultCurrencyID")
private Integer DEFAULT_CURRENCY_ID;
#XmlElement(name="DefaultLanguageID")
private Integer DEFAULT_LANGUAGE_ID;
#XmlElement(name="TaskID")
private Integer TASK_ID;
#XmlElement(name="CurrencyID")
private Integer CURRENCY_ID;
public Integer getCURRENCY_ID() {
return CURRENCY_ID;
}
public void setCURRENCY_ID(Integer CURRENCY_ID) {
this.CURRENCY_ID = CURRENCY_ID;
}
public Integer getTASK_ID() {
return TASK_ID;
}
public void setTASK_ID(Integer TASK_ID) {
this.TASK_ID = TASK_ID;
}
public Integer getDEFAULT_LANGUAGE_ID() {
return DEFAULT_LANGUAGE_ID;
}
public void setDEFAULT_LANGUAGE_ID(Integer DEFAULT_LANGUAGE_ID) {
this.DEFAULT_LANGUAGE_ID = DEFAULT_LANGUAGE_ID;
}
public Integer getDEFAULT_CURRENCY_ID() {
return DEFAULT_CURRENCY_ID;
}
public void setDEFAULT_CURRENCY_ID(Integer DEFAULT_CURRENCY_ID) {
this.DEFAULT_CURRENCY_ID = DEFAULT_CURRENCY_ID;
}
public Integer getCOUNTRY_ID() {
return COUNTRY_ID;
}
public void setCOUNTRY_ID(Integer COUNTRY_ID) {
this.COUNTRY_ID = COUNTRY_ID;
}
public String getCOUNTRY_NAME() {
return COUNTRY_NAME;
}
public void setCOUNTRY_NAME(String COUNTRY_NAME) {
this.COUNTRY_NAME = COUNTRY_NAME;
}
public Integer getLANGUAGE_ID() {
return LANGUAGE_ID;
}
public void setLANGUAGE_ID(Integer LANGUAGE_ID) {
this.LANGUAGE_ID = LANGUAGE_ID;
}
}
this the Countries Service Class
package service;
import beans.CountriesBean;
import com.xperteam.DBC.DataBaseConnection;
import entity.Countries;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
*
* #author ahmad.s
*/
#Stateless
#Path("countries")
public class CountriesFacadeREST extends AbstractFacade<Countries> {
#PersistenceContext(unitName = "WeddingRestApiPU")
private EntityManager em;
public CountriesFacadeREST() {
super(Countries.class);
}
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(Countries entity) {
super.create(entity);
}
#PUT
#Path("{id}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void (#PathParam("id") Long id, Countries entity) {
super.(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Long id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Countries find(#PathParam("id") Long id) {
return super.find(id);
}
#GET
#Override
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
return em;
}
#GET
#Path("/getAllCountries") // webresources/beans.contactbean/getContactID?ContactID=? get contact info by id
#Produces(MediaType.APPLICATION_JSON)
public ArrayList<CountriesBean> getAllCountries() {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<CountriesBean> CountriesList = new ArrayList<CountriesBean>();
CountriesBean CountriesBean = null;
StringBuffer query = new StringBuffer();
query.append(" SELECT ");
query.append(" COUNTRIES.COUNTRY_ID, ");
query.append(" COUNTRIES_TRANS.COUNTRY_TRANS_NAME,COUNTRIES.DEFAULT_CURRENCY_ID,COUNTRIES.DEFAULT_LANGUAGE_ID ");
query.append(" FROM COUNTRIES INNER JOIN COUNTRIES_TRANS ON COUNTRIES_TRANS.COUNTRY_ID=COUNTRIES.COUNTRY_ID ");
query.append(" WHERE COUNTRIES_TRANS.LANGUAGE_ID = 1 ");
int counter = 1;
try {
DataBaseConnection DataBaseConnection = new DataBaseConnection();
Connection con = DataBaseConnection.GetConnection();
preparedStatement = con.prepareStatement(new String(query));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
CountriesBean = new CountriesBean();
CountriesBean.setCOUNTRY_ID(resultSet.getInt("COUNTRY_ID"));
CountriesBean.setCOUNTRY_NAME(resultSet.getString("COUNTRY_TRANS_NAME"));
CountriesBean.setDEFAULT_CURRENCY_ID(resultSet.getInt("DEFAULT_CURRENCY_ID"));
CountriesBean.setDEFAULT_LANGUAGE_ID(resultSet.getInt("DEFAULT_LANGUAGE_ID"));
CountriesList.add(CountriesBean);
}
con.close();
} catch (SQLException sqlException) {
CountriesList = null;
System.out.println("getWeddingType : " + sqlException.getMessage());
} catch (NamingException ex) {
Logger.getLogger(CountriesFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
} finally {
query = null;
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception exception) {
}
}
return CountriesList;
}
}
I cannot verify your problem without your code.
Please see a basic example with your expectation:
public class Customer {
String fullName;
String email;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer{" +
"fullName='" + fullName + '\'' +
", email='" + email + '\'' +
'}';
}
}
..
#Path("/services")
public class MaisonService {
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public Customer getSampleCustomer() {
Customer sampleCustomer = new Customer();
sampleCustomer.setFullName("Trinh Toan Trung");
sampleCustomer.setEmail("trinhtoantrung#gmail.com");
return sampleCustomer;
}
..
The output:
{"email":"trinhtoantrung#gmail.com","fullName":"Trinh Toan Trung"}
There are many simple ways to do it, following is the most simplest as you are able to get the response as your POJO or DTO clas
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);

Google App Engine User Registration System

I am creating a user registration system in google app engine, and so far I could develop the registration side of the app. But I can't log in and create a HttpSession.
Here what I did, I created login.jsp and two text boxes to input email and password.
And then I created Bean class and DAO class as following.
package com.myfirstguide.beans;
import javax.servlet.http.HttpSession;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
public class UserDAO {
public static UserBean login(UserBean bean){
String email = bean.getEmail();
String password = bean.getPassword();
try{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Account");
q.addFilter("email", Query.FilterOperator.EQUAL, email);
q.addFilter("password", Query.FilterOperator.EQUAL, password);
PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();
if(result != null){
bean.setValid(true);
}
//return bean;
}catch(Exception e){
}
return bean;
}
}
Here is the Bean class.
package com.myfirstguide.beans;
public class UserBean {
private String username;
private String password;
private String firstName;
private String lastName;
private String email;
public boolean valid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public void setEmail(String semail){
email = semail;
}
public String getEmail(){
return email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
lastName = newLastName;
}
public String getPassword() {
return password;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public String getUsername() {
return username;
}
public void setUserName(String newUsername) {
username = newUsername;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
And here is the Servlet.
package com.myfirstguide.users;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.myfirstguide.beans.UserBean;
import com.myfirstguide.beans.UserDAO;
public class SignIn extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
try{
UserBean ubean = new UserBean();
ubean.setEmail(email);
ubean.setPassword(password);
ubean = UserDAO.login(ubean);
if(ubean.isValid()){
HttpSession session = req.getSession(true);
session.setAttribute("currentSessionUser",ubean);
resp.sendRedirect("index.jsp?session=" + ubean.getFirstName()); //logged-in page
}
}catch(Throwable e){
System.out.println(e);
}
}
}
And I don't know JPA. And if there is better way to do this, please tell me.
Thank you!
Have you enabled sessions?
https://developers.google.com/appengine/docs/java/config/appconfig#Enabling_Sessions

Categories

Resources