Stuck in ManagedBeanPreProcessingException : Unexpected error processing managed bean - java

Can anyone help us with this?
We're trying to make the register user feature in our JSF application. We want the user log in right after he registers. After the user hits the I'm a new client commandLink, we have this exception, and we don't know how to handle it:
com.sun.faces.mgbean.ManagedBeanPreProcessingException: Unexpected error processing managed bean registerBean
at com.sun.faces.mgbean.BeanManager.preProcessBean(BeanManager.java:394)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:260)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:86)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:99)
at com.sun.el.parser.AstValue.getValue(AstValue.java:158)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIOutput.getValue(UIOutput.java:168)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:338)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1620)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.faces.mgbean.ManagedBeanPreProcessingException: Unexpected error processing managed property loginBean
at com.sun.faces.mgbean.ManagedBeanBuilder.bake(ManagedBeanBuilder.java:117)
at com.sun.faces.mgbean.BeanManager.preProcessBean(BeanManager.java:349)
... 50 more
Caused by: java.lang.NullPointerException
at com.sun.faces.mgbean.ManagedBeanBuilder.bakeBeanProperty(ManagedBeanBuilder.java:350)
at com.sun.faces.mgbean.ManagedBeanBuilder.bake(ManagedBeanBuilder.java:107)
... 51 more
Here are the LoginBean and the RegisterBean:
#ManagedBean
#SessionScoped
public class LoginBean
{
private String username, password;
private User user;
private UserManager um = UserManager.getInstance();
/**
*
*/
public LoginBean()
{
super();
}
/**
* #return the username
*/
public String getUsername()
{
return username;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
public void setUser(User user)
{
this.user = user;
username = user.getUsername();
password = user.getPassword();
}
/**
* #return the user
*/
public User getUser()
{
return user;
}
/**
* #param username
* the username to set
*/
public void setUsername(String username)
{
this.username = username;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password)
{
this.password = password;
}
public String nextPage()
{
try
{
user = um.getUser(username, password);
}
catch (NoResultException e)
{
return "failure" + REDIRECT;
}
if (user instanceof Client)
return "home_client" + REDIRECT;
return "home_admin" + REDIRECT;
}
}
#ManagedBean
#RequestScoped
public class RegisterBean
{
private String username, password, repassword, firstname, lastname, email, address, city, county, postcode, country, phone;
#ManagedProperty(value = "#{loginBean}")
private LoginBean loginBean;
// private UserManager um = UserManager.getInstance();
public RegisterBean()
{
}
/**
* #return the username
*/
public String getUsername()
{
return username;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
/**
* #return the repassword
*/
public String getRepassword()
{
return repassword;
}
/**
* #return the firstname
*/
public String getFirstname()
{
return firstname;
}
/**
* #return the lastname
*/
public String getLastname()
{
return lastname;
}
/**
* #return the email
*/
public String getEmail()
{
return email;
}
/**
* #return the address
*/
public String getAddress()
{
return address;
}
/**
* #return the city
*/
public String getCity()
{
return city;
}
/**
* #return the county
*/
public String getCounty()
{
return county;
}
/**
* #return the postcode
*/
public String getPostcode()
{
return postcode;
}
/**
* #return the country
*/
public String getCountry()
{
return country;
}
/**
* #return the phone
*/
public String getPhone()
{
return phone;
}
/**
* #return the user
*/
public LoginBean getLoginBean()
{
return loginBean;
}
/**
* #param username
* the username to set
*/
public void setUsername(String username)
{
this.username = username;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* #param repassword
* the repassword to set
*/
public void setRepassword(String repassword)
{
this.repassword = repassword;
}
/**
* #param firstname
* the firstname to set
*/
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
/**
* #param lastname
* the lastname to set
*/
public void setLastname(String lastname)
{
this.lastname = lastname;
}
/**
* #param email
* the email to set
*/
public void setEmail(String email)
{
this.email = email;
}
/**
* #param address
* the address to set
*/
public void setAddress(String address)
{
this.address = address;
}
/**
* #param city
* the city to set
*/
public void setCity(String city)
{
this.city = city;
}
/**
* #param county
* the county to set
*/
public void setCounty(String county)
{
this.county = county;
}
/**
* #param postcode
* the postcode to set
*/
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
/**
* #param country
* the country to set
*/
public void setCountry(String country)
{
this.country = country;
}
/**
* #param phone
* the phone to set
*/
public void setPhone(String phone)
{
this.phone = phone;
}
public String register()
{
this.loginBean.setUser(new Client(username, password, new ContactDetails(firstname, lastname, email, address, city, county, postcode, country, phone)));
return "home_client" + REDIRECT;
}
}
Here is the login form from login.xhtml:
<h:form>
Username: <h:inputText value="#{loginBean.username}" />
<br />
Password: <h:inputSecret value="#{loginBean.password}" />
<br />
<h:commandButton value="Login" action="#{loginBean.nextPage}" />
<h:commandLink value="I'm a new client" action="register"></h:commandLink>
</h:form>
And the register form from register.xhtml:
<h:form>
<h:outputText value="Inregistrare client nou"/>
<br/>
Username: <h:inputText value="#{registerBean.username}">
<f:validator validatorId="registerUsernameValidator"></f:validator>
</h:inputText>
<br/>
Parola: <h:inputSecret value="#{registerBean.password}"></h:inputSecret>
<br/>
Re-Parola: <h:inputSecret value="#{registerBean.repassword}"></h:inputSecret>
<br/>
<br/>
Prenume: <h:inputText value="#{registerBean.firstname}"></h:inputText>
<br/>
Nume: <h:inputText value="#{registerBean.lastname}"></h:inputText>
<br/>
E-mail: <h:inputText value="#{registerBean.email}"></h:inputText>
<br/>
Adresa: <h:inputText value="#{registerBean.address}"></h:inputText>
<br/>
Oras: <h:inputText value="#{registerBean.city}"></h:inputText>
<br/>
Judet: <h:inputText value="#{registerBean.county}"></h:inputText>
<br/>
Cod postal: <h:inputText value="#{registerBean.postcode}"></h:inputText>
<br/>
Tara: <h:inputText value="#{registerBean.country}"></h:inputText>
<br/>
Telefon: <h:inputText value="#{registerBean.phone}"></h:inputText>
<br/>
<br/>
<h:commandButton value="Inregistreaza-ma"
action="#{registerBean.register}"></h:commandButton>
Our custom RegisterUsernameValidator:
public class RegisterUsernameValidator implements Validator
{
UserManager um = UserManager.getInstance();
#Override
public void validate(FacesContext context, UIComponent arg1, Object value) throws ValidatorException
{
String username = (String) value;
if (!um.isUsernameAvailable(username))
{
FacesMessage facesMessage = new FacesMessage("Username indisponibil");
FacesContext.getCurrentInstance().addMessage("Username indisponibil", facesMessage);
}
}
}
And the validation part from faces-config.xml:
<validator>
<validator-id>registerUsernameValidator</validator-id>
<validator-class>validation.RegisterUsernameValidator</validator-class>
</validator>

com.sun.faces.mgbean.ManagedBeanPreProcessingException: Unexpected error processing managed bean registerBean
This means that processing the bean properties on RegisterBean directly after its construction has failed miserably due to a developer error (wrong configuration, inaccessible properties, invalid property type, etc). The root cause of the problem should be visible as root cause part in the stacktrace of the exception. Since you didn't share the entire stacktrace, it's hard to tell what exactly is failing.
Anyway, just read the stacktrace. The answer is in there.
Update: as per the full stacktrace:
Caused by: com.sun.faces.mgbean.ManagedBeanPreProcessingException: Unexpected error processing managed property loginBean
Caused by: java.lang.NullPointerException
The managed property for loginBean could not be set in registerBean. Verify if there is a setter in RegisterBean class and it has the right signature.
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
Unrelated to the concrete problem, this NullPointerException should really have been a PropertyNotWritableException. What JSF impl/version are you using?

Related

Thymeleaf form causes errors at th:field

I'm very new to Thymeleaf and I'm trying to make a registration form but it keeps giving me error 500's when I try to add th: attributes to my form. I assume it has something to do with the form not seeing the UserModel but I can't be sure. I feel like I've tried everything so any help would be greatly appreciated!
Here's my registration form:
<!DOCTYPE html>
<html xmlns:th=”http://www.thymeleaf.org” xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="layouts/defaultTemplate">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Register - AZSnowSports</title>
</head>
<body>
<div layout:fragment="content">
<form action="#" th:action="#{doRegister}" th:object="${userModel}" method="POST">
<table>
<tr>
<td>First Name:</td><td><input type="text" th:field="*{firstName}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">First Name Error</h5></td>
</tr>
<tr>
<td>Last Name:</td><td><input type="text" th:field="*{lastName}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">Last Name Error</h5></td>
</tr>
<tr>
<td>EMail:</td><td><input type="email" th:field="*{email}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">EMail Error</h5></td>
</tr>
<tr>
<td>Address:</td><td><input type="text" th:field="*{address}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('address')}" th:errors="*{address}">Address Error</h5></td>
</tr>
<tr>
<td>Phone Number:</td><td><input type="number" th:field="*{phoneNumber}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('phoneNumber')}" th:errors="*{phoneNumber}">Phone Number Error</h5></td>
</tr>
<tr>
<td>Username:</td><td><input type="text" th:field="*{username}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Username Error</h5></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" th:field="*{password}"></td><td><h5 style="color: red" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</h5></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Here's my controller:
package com.azsnowsports.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.azsnowsports.model.UserModel;
#Controller
#RequestMapping("/register")
public class RegisterController {
#GetMapping("/")
public String display(Model model)
{
// Display the login form view
model.addAttribute("title", "Register Form");
return "register";
}
#PostMapping("/doRegister")
public String doRegister(#Valid UserModel userModel, BindingResult bindingResult, Model model)
{
//Check for validation errors
if (bindingResult.hasErrors())
{
model.addAttribute("title", "Register Form");
return "register";
}
return "registerSuccess";
}
}
And here's my user model:
package com.azsnowsports.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class UserModel {
/**
* The user's first name
*/
#NotNull(message="FirstName is a required field.")
#Size(min = 1, max = 32, message="First Name must be between 1 and 32 characters.")
private String firstName;
/**
* The user's last name
*/
#NotNull(message="Last name is a required field.")
#Size(min = 1, max = 32, message="Last name must be between 1 and 32 characters.")
private String lastName;
/**
* The user's email
*/
#NotNull(message="EMail is a required field.")
private String email;
/**
* The user's address
*/
#NotNull(message="Address is a required field.")
private String address;
/**
* The user's phone number
*/
#NotNull(message="Phone Number is a required field.")
private int phoneNumber;
/**
* The user's username
*/
#NotNull(message="Username is a required field.")
#Size(min = 1, max = 32, message="Username must be between 1 and 32 characters.")
private String username;
/**
* The user's password
*/
#NotNull(message="Password is a required field.")
#Size(min = 1, max = 32, message="Password must be between 1 and 32 characters.")
private String password;
/**
* Constructor
*
* #param firstNameVal The first name of the user
* #param lastNameVal The last name of the user
* #param emailVal The email of the user
* #param addressVal The address of the user
* #param phoneNumber The phone number of the user
* #param usernameVal The username for the user
* #param passwordVal The password for the user
*/
public UserModel(String firstNameVal, String lastNameVal, String emailVal, String addressVal,
int phoneNumberVal, String usernameVal, String passwordVal)
{
this.firstName = firstNameVal;
this.lastName = lastNameVal;
this.email = emailVal;
this.address = addressVal;
this.phoneNumber = phoneNumberVal;
this.username = usernameVal;
this.password = passwordVal;
}
/**
* #return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* #param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* #param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the phoneNumber
*/
public int getPhoneNumber() {
return phoneNumber;
}
/**
* #param phoneNumber the phoneNumber to set
*/
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #return the username
*/
public String getUsername() {
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
Heres a screenshot of my file structure:
I added model.addAttribute("userModel", new UserModel()); into the root map of the model so it now looks like this:
#GetMapping("/")
public String display(Model model)
{
// Display the login form view
model.addAttribute("title", "Register Form");
model.addAttribute("userModel", new UserModel());
return "register";
}
This fixed it and it runs fine now!

mysql jdbc connection no error but doesnt work on the web page

I have to do a an web page that is choosing datas from database with jdbc and mysql. There is not look any problem. But page doesnt take the database values from database, it is just shows column name.What can i do to show database values on the table on the web page?
That is my staff class:
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
*
*/
public class Staff {
List <Kisiler> sorguSonucu;
public List<Kisiler> getSorguSonucu(List<Kisiler> sorguSonucu){
return sorguSonucu;
}
public List<Kisiler> getTablodakiKayitlar()
{
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
sorguSonucu = new ArrayList<Kisiler>();
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3309/staff";
String user = "admin";
String psw = "admin";
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection) DriverManager.getConnection(url, user, psw);
preparedStatement = (PreparedStatement) connection.prepareStatement("SELECT * FROM staff");
resultSet = (ResultSet) preparedStatement.executeQuery();
while(resultSet.next()){
Kisiler kisiler = new Kisiler();
kisiler.setId(resultSet.getInt("id"));
kisiler.setFirstName(resultSet.getString("firstName"));
kisiler.setLastName(resultSet.getString("lastName"));
kisiler.setTelephone(resultSet.getInt("telephone"));
kisiler.setEmail(resultSet.getString("email"));
sorguSonucu.add(kisiler);
}
}
catch(Exception e){
System.err.println("Hata meydana geldi.Hata: " + e);
}
finally{
try{
connection.close();
preparedStatement.close();
}
catch(Exception e){
System.err.println("Hata meydana geldi.Hata: " + e);
}
}
return sorguSonucu;
}
}
and i have kisiler class
class Kisiler {
private int id;
private String firstName;
private String lastName;
private int telephone;
private String email;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* #param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* #param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #return the telephone
*/
public int getTelephone() {
return telephone;
}
/**
* #param telephone the telephone to set
*/
public void setTelephone(int telephone) {
this.telephone = telephone;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
and my html codes:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>View Staff</title>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{staff.tablodakikayitlar}" var="kayitCekObjesi"
>
<h:column>
<f:facet name="header">
ID
</f:facet>
<h:outputText value="#{kayitCekObjesi.id}"/>
</h:column>
<h:column>
<f:facet name="header">
First Name
</f:facet>
<h:outputText value="#{kayitCekObjesi.firstName}"/>
</h:column>
<h:column>
<f:facet name="header">
Last Name
</f:facet>
<h:outputText value="#{kayitCekObjesi.lastName}"/>
</h:column>
<h:column>
<f:facet name="header">
Telephone
</f:facet>
<h:outputText value="#{kayitCekObjesi.telephone}"/>
</h:column>>
<h:column>
<f:facet name="header">
E-mail
</f:facet>
<h:outputText value="#{kayitCekObjesi.email}"/>
</h:column>>
</h:dataTable>
</h:form>
</h:body>
</html>
At first please check value from Database is actually return or not by debugging .If you see value actually return ;then check kisiler class have getter method for those attribute 'id;firstName;.lastName in kisiler class.please check there are getter methods for those attribute in kisiler class.

Unable to create index directory: /mnt/genapp/apps when deploy Spring MVC website

I have finished my website using Spring MVC with Maven. Now I want to deploy it to CloudBees for testing. Every settings(connecting to db, code logic,...) are ok but when I start the application, I'm facing a problem about indexing in Hibernate Search. It looks like I don't have permission to create index directory in Cloud Bees Tomcat 7 server. Below is the stack trace:
Caused by: org.hibernate.search.SearchException: Unable to initialize directory provider: org.appfuse.model.User
at org.hibernate.search.store.impl.DirectoryProviderFactory.createDirectoryProvider(DirectoryProviderFactory.java:87)
at org.hibernate.search.indexes.impl.DirectoryBasedIndexManager.createDirectoryProvider(DirectoryBasedIndexManager.java:216)
at org.hibernate.search.indexes.impl.DirectoryBasedIndexManager.initialize(DirectoryBasedIndexManager.java:89)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createDirectoryManager(IndexManagerHolder.java:241)
... 53 more
Caused by: org.hibernate.search.SearchException: Unable to create index directory: /mnt/genapp/apps/3926c2d0/fsgetter/index for index org.appfuse.model.User
at org.hibernate.search.store.impl.DirectoryProviderHelper.makeSanityCheckedDirectory(DirectoryProviderHelper.java:261)
at org.hibernate.search.store.impl.DirectoryProviderHelper.getVerifiedIndexDir(DirectoryProviderHelper.java:243)
at org.hibernate.search.store.impl.FSDirectoryProvider.initialize(FSDirectoryProvider.java:66)
at org.hibernate.search.store.impl.DirectoryProviderFactory.createDirectoryProvider(DirectoryProviderFactory.java:84)
... 56 more
Below is my POJO need to index:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name = "app_user")
#Indexed
#XmlRootElement
public class User extends BaseObject implements Serializable, UserDetails {
private static final long serialVersionUID = 3832626162173359411L;
private Long id;
private String username; // required
private String password; // required
private String confirmPassword;
private String passwordHint;
private String firstName; // required
private String lastName; // required
private String email; // required; unique
private String phoneNumber;
private String website;
private Address address = new Address();
private Integer version;
private Set<Role> roles = new HashSet<Role>();
private boolean enabled;
private boolean accountExpired;
private boolean accountLocked;
private boolean credentialsExpired;
private int freeLink;
/**
* Default constructor - creates a new instance with no values set.
*/
public User() {
}
/**
* Create a new instance and set the username.
*
* #param username login name for user.
*/
public User(final String username) {
this.username = username;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#DocumentId
public Long getId() {
return id;
}
#Column(nullable = false, length = 50, unique = true)
#Field
public String getUsername() {
return username;
}
#Column(nullable = false)
#XmlTransient
#JsonIgnore
public String getPassword() {
return password;
}
#Transient
#XmlTransient
#JsonIgnore
public String getConfirmPassword() {
return confirmPassword;
}
#Column(name = "password_hint")
#XmlTransient
public String getPasswordHint() {
return passwordHint;
}
#Column(name = "first_name", nullable = false, length = 50)
#Field
public String getFirstName() {
return firstName;
}
#Column(name = "last_name", nullable = false, length = 50)
#Field
public String getLastName() {
return lastName;
}
#Column(nullable = false, unique = true)
#Field
public String getEmail() {
return email;
}
#Column(name = "phone_number")
#Field(analyze= Analyze.NO)
public String getPhoneNumber() {
return phoneNumber;
}
#Field
public String getWebsite() {
return website;
}
/**
* Returns the full name.
*
* #return firstName + ' ' + lastName
*/
#Transient
public String getFullName() {
return firstName + ' ' + lastName;
}
#Embedded
#IndexedEmbedded
public Address getAddress() {
return address;
}
#ManyToMany(fetch = FetchType.EAGER)
#Fetch(FetchMode.SELECT)
#JoinTable(
name = "user_role",
joinColumns = { #JoinColumn(name = "user_id") },
inverseJoinColumns = #JoinColumn(name = "role_id")
)
public Set<Role> getRoles() {
return roles;
}
/**
* Convert user roles to LabelValue objects for convenience.
*
* #return a list of LabelValue objects with role information
*/
#Transient
public List<LabelValue> getRoleList() {
List<LabelValue> userRoles = new ArrayList<LabelValue>();
if (this.roles != null) {
for (Role role : roles) {
// convert the user's roles to LabelValue Objects
userRoles.add(new LabelValue(role.getName(), role.getName()));
}
}
return userRoles;
}
/**
* Adds a role for the user
*
* #param role the fully instantiated role
*/
public void addRole(Role role) {
getRoles().add(role);
}
/**
* #return GrantedAuthority[] an array of roles.
* #see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
*/
#Transient
public Set<GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new LinkedHashSet<GrantedAuthority>();
authorities.addAll(roles);
return authorities;
}
#Version
public Integer getVersion() {
return version;
}
/**
* #return the freeLink
*/
#Column(name = "freeLink")
public int getFreeLink() {
return freeLink;
}
#Column(name = "account_enabled")
public boolean isEnabled() {
return enabled;
}
#Column(name = "account_expired", nullable = false)
public boolean isAccountExpired() {
return accountExpired;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
* #return true if account is still active
*/
#Transient
public boolean isAccountNonExpired() {
return !isAccountExpired();
}
#Column(name = "account_locked", nullable = false)
public boolean isAccountLocked() {
return accountLocked;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
* #return false if account is locked
*/
#Transient
public boolean isAccountNonLocked() {
return !isAccountLocked();
}
#Column(name = "credentials_expired", nullable = false)
public boolean isCredentialsExpired() {
return credentialsExpired;
}
/**
* #see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
* #return true if credentials haven't expired
*/
#Transient
public boolean isCredentialsNonExpired() {
return !credentialsExpired;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public void setPasswordHint(String passwordHint) {
this.passwordHint = passwordHint;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setWebsite(String website) {
this.website = website;
}
public void setAddress(Address address) {
this.address = address;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setVersion(Integer version) {
this.version = version;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setAccountExpired(boolean accountExpired) {
this.accountExpired = accountExpired;
}
public void setAccountLocked(boolean accountLocked) {
this.accountLocked = accountLocked;
}
public void setCredentialsExpired(boolean credentialsExpired) {
this.credentialsExpired = credentialsExpired;
}
/**
* #param freeLink the freeLink to set
*/
public void setFreeLink(int freeLink) {
this.freeLink = freeLink;
}
/**
* {#inheritDoc}
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
final User user = (User) o;
return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null);
}
/**
* {#inheritDoc}
*/
public int hashCode() {
return (username != null ? username.hashCode() : 0);
}
/**
* {#inheritDoc}
*/
public String toString() {
ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
.append("username", this.username)
.append("enabled", this.enabled)
.append("accountExpired", this.accountExpired)
.append("credentialsExpired", this.credentialsExpired)
.append("accountLocked", this.accountLocked);
if (roles != null) {
sb.append("Granted Authorities: ");
int i = 0;
for (Role role : roles) {
if (i > 0) {
sb.append(", ");
}
sb.append(role.toString());
i++;
}
} else {
sb.append("No Granted Authorities");
}
return sb.toString();
}
}
Update application-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="true">
<!-- Activates scanning of #Autowired -->
<context:annotation-config />
<!-- Activates scanning of #Repository and #Service -->
<context:component-scan base-package="com.giangnt" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<value>
hibernate.search.default.indexBase=fsgetter/index
hibernate.dialect=${hibernate.dialect}
</value>
</property>
</bean>
</beans>
I want to ask how to create index directory in Cloud Bees tomcat 7 server so that my web application can publish for testing?
Filesystem isn't persistent, so for your safety it's write proteceted but java.io.tmpDir - as you can use this one to store whatever temp file you need, but have to know it will disappear on next deployment / restart

How to redirect user to an error page from login control upon entering wrong username and/or password?

I created a login form, and when I log in using a correct username and password it works fine.
I want to pop up an error message or error page when I enter a wrong username or password.
That means the controller will compare the given username with all the usernames in the database and if the given username is not found, an error message or error page should be displayed.
How can I do this with HTML or JavaScript? Is there a way to create a simple error message in the servlet? but I need to reload the page again.
<html>
<body>
<form action="search" onsubmit="return validateForm()">
<table>
<tr><td>Username</td>
<td><input type=text name=LoginId /></td>
</tr>
<tr><td>Password</td>
<td><input type=password name=LoginPassword /> </td>
</tr>
<tr>
<td colspan=2>
<center>
<input type=submit value=SignIn /><br>If you forgot your password, Reset your password.
</center>
</td>
</tr>
</table>
</form>
</body>
</html>
SearchServlet.java
/**
* #see HttpServlet#HttpServlet()
*/
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
CustomerDAO customerDAO = new CustomerDAO();
String username = request.getParameter("LoginId");
String password = request.getParameter("LoginPassword");
Login login = customerDAO.getLoginByName(username, password);
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<center><h1>User Information</h1></center>");
out.println("<center><table border=0x>");
out.println("<tr>");
out.println("<td>Login Id : </td><td>"+login.getLoginId()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>City : </td><td>"+login.getCity()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>State : </td><td>"+login.getState()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Cell Number : </td><td>"+login.getCellnumber()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Email :</td><td>"+login.getEmail()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Address :</td><td>"+login.getAddress()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>ZipCode : </td><td>"+login.getZipcode()+"</td>");
out.println("</tr>");
out.println("</table></center>");
out.println("<p>If these details are correct press continue or to change your information press update.</p>");
out.println("<form action='Continue.jsp'>");
out.println("<center><input type=submit value=continue></center>");
out.println("</form>");
out.println("<form action='search'>");
out.println("<center> update </center>");
out.println("</form>");
out.println("</body></html>");
Login l = new Login();
l.setLoginId(request.getParameter("LoginId"));
if(l!=null) {
HttpSession session = request.getSession();
session.setAttribute("l", l);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
CustomerDAO.java
public class CustomerDAO extends BaseDAO{
public Login getLoginByName(String username, String password) {
Login login = null;
try {
BaseDAO baseDAO = new BaseDAO();
Connection c =baseDAO.getConnection();
// String query = "select * from test.Login where LoginId=? && LoginPassword=?";
String query = "select * from test.Customer where LoginId=? && LoginPassword=?";
PreparedStatement ps = c.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
login = new Login();
login.setLoginId(rs.getString("LoginId"));
login.setCity(rs.getString("City"));
login.setState(rs.getString("State"));
login.setCellnumber(rs.getString("PhoneNumber"));
login.setEmail(rs.getString("Email"));
login.setAddress(rs.getString("Address"));
login.setZipcode(rs.getInt("ZipCode"));
System.out.println();
}
c.close();
}catch(Exception e) {
System.err.println("Username or Password you enterd is incorrect.");
}
return login;
}
Login.java
package com.dao;
public class Login {
String LoginId;
String password;
String confirmpassword;
String city;
String state;
String cellnumber;
int zipcode;
String Email;
String Address;
public Login() {
// TODO Auto-generated constructor stub
}
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCellnumber() {
return cellnumber;
}
public void setCellnumber(String cellnumber) {
this.cellnumber = cellnumber;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public void setEmail(String email) {
Email = email;
}
public String getEmail() {
return Email;
}
public void setAddress(String address) {
Address = address;
}
public String getAddress() {
return Address;
}
}
after this :
PrintWriter out = response.getWriter();
add ->
if (login == null){
out.println("<html><body>");
out.println("<center><h1>Login failed, wrong username or password</h1></center>");
out.println("</body>");
out.println("<script type='text/javascript'>");
out.println("function reload() {");
out.println("setTimeout(function(){");
out.println("window.location = '"+request.getContextPath()+"/search';}");
out.println("}, 5000);");
out.println("reload();");
out.println("</script>");
out.println("</html>");
}
}
but that is a bad way to do authentication, you will have to write your own authorization filters, and thats a lot of redudant code, instead of this use web containers authentication mechanism see securing web app
it's easy to override, can add custom login, add softlogin, roles, and stuff like this.

Getting the PropertyAccessException for hibernate for the userId

I have done an example for login using database in hibernate.My Xml and entity classes are
User.java:
import java.util.Date;
import javax.persistence.Entity;
#Entity(name="User")
public class User {
private Integer userID;
private String username;
private String password;
private Date createdDate;
/**
* Default Constructor
*/
public User() {
super();
}
public User(Integer userID, String username, String password) {
this.userID = userID;
this.username = username;
this.password = password;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
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 Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}//end of class()
UserBooks.java:
public class UsersBooks {
// Declaring all attributes
private double userID;
private String bookID;
private String permission;
// Constructors
public UsersBooks() {
super();
}
public UsersBooks(double userID, String bookID, String permission) {
super();
this.userID = userID;
this.bookID = bookID;
this.permission = permission;
}
// Getters and Setters
public double getUserID() {
return userID;
}
public void setUserID(double userID) {
this.userID = userID;
}
public String getBookID() {
return bookID;
}
public void setBookID(String bookID) {
this.bookID = bookID;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
// Overriding toString()
#Override
public String toString() {
return "UsersBooks [userID=" + userID + ", bookID=" + bookID
+ ", permission=" + permission + "]";
}//end of toString()
}//end of class
UserSocialInfo.java:
public class UserSocialInfo {
private int socialID;
private String loginProvider;
private String loginProviderUID;
private String UID;
private String nickname;
private String photoURL;
private String thumbnailURL;
private int birthDay;
private int birthMonth;
private int birthYear;
private String gender;
private String proxiedEmail;
private String country;
private String state;
private String city;
private String zip;
private String firstname;
private String lastname;
private String profileURL;
private int userID;
/**
*
*/
public UserSocialInfo() {
// TODO Auto-generated constructor stub
}
/**
* #return the socialID
*/
public int getSocialID() {
return socialID;
}
/**
* #param socialID the socialID to set
*/
public void setSocialID(int socialID) {
this.socialID = socialID;
}
/**
* #return the loginProvider
*/
public String getLoginProvider() {
return loginProvider;
}
/**
* #param loginProvider the loginProvider to set
*/
public void setLoginProvider(String loginProvider) {
this.loginProvider = loginProvider;
}
/**
* #return the loginProviderUID
*/
public String getLoginProviderUID() {
return loginProviderUID;
}
/**
* #param loginProviderUID the loginProviderUID to set
*/
public void setLoginProviderUID(String loginProviderUID) {
this.loginProviderUID = loginProviderUID;
}
/**
* #return the uID
*/
public String getUID() {
return UID;
}
/**
* #param uID the uID to set
*/
public void setUID(String uID) {
UID = uID;
}
/**
* #return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* #param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* #return the photoURL
*/
public String getPhotoURL() {
return photoURL;
}
/**
* #param photoURL the photoURL to set
*/
public void setPhotoURL(String photoURL) {
this.photoURL = photoURL;
}
/**
* #return the thumbnailURL
*/
public String getThumbnailURL() {
return thumbnailURL;
}
/**
* #param thumbnailURL the thumbnailURL to set
*/
public void setThumbnailURL(String thumbnailURL) {
this.thumbnailURL = thumbnailURL;
}
/**
* #return the birthDay
*/
public int getBirthDay() {
return birthDay;
}
/**
* #param birthDay the birthDay to set
*/
public void setBirthDay(int birthDay) {
this.birthDay = birthDay;
}
/**
* #return the birthMonth
*/
public int getBirthMonth() {
return birthMonth;
}
/**
* #param birthMonth the birthMonth to set
*/
public void setBirthMonth(int birthMonth) {
this.birthMonth = birthMonth;
}
/**
* #return the birthYear
*/
public int getBirthYear() {
return birthYear;
}
/**
* #param birthYear the birthYear to set
*/
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
/**
* #return the gender
*/
public String getGender() {
return gender;
}
/**
* #param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return the proxiedEmail
*/
public String getProxiedEmail() {
return proxiedEmail;
}
/**
* #param proxiedEmail the proxiedEmail to set
*/
public void setProxiedEmail(String proxiedEmail) {
this.proxiedEmail = proxiedEmail;
}
/**
* #return the country
*/
public String getCountry() {
return country;
}
/**
* #param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* #return the state
*/
public String getState() {
return state;
}
/**
* #param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* #return the city
*/
public String getCity() {
return city;
}
/**
* #param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* #return the zip
*/
public String getZip() {
return zip;
}
/**
* #param zip the zip to set
*/
public void setZip(String zip) {
this.zip = zip;
}
/**
* #return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* #param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* #return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* #param lastname the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* #return the profileURL
*/
public String getProfileURL() {
return profileURL;
}
/**
* #param profileURL the profileURL to set
*/
public void setProfileURL(String profileURL) {
this.profileURL = profileURL;
}
/**
* #return the userID
*/
public int getUserID() {
return userID;
}
/**
* #param userID the userID to set
*/
public void setUserID(int userID) {
this.userID = userID;
}
}
My xml files
User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.User" table="users">
<id name="userID" type="long" column="userid">
<generator class="increment" />
</id>
<property name="username" column="username" />
<property name="password" column="password" />
<property name="userID" column="userid" insert="false" update="false"/>
<property name="createdDate" column="created_date" />
</class>
</hibernate-mapping>
UserBooks.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.UsersBooks" table="users_books">
<id name="userID" type="long" column="user_id">
</id>
<property name="userID" column="user_id" insert="false" update="false"/>
<property name="bookID" column="book_id" insert="false" update="false"/>
<property name="permission" column="permissions" />
</class>
</hibernate-mapping>
UserSocialInfo.java:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.UserSocialInfo" table="user_social_info">
<id name="socialID" type="long" column="social_id">
<generator class="increment" />
</id>
<property name="socialID" column="social_id" insert="false" update="false"/>
<property name="loginProvider" column="login_provider" />
<property name="loginProviderUID" column="login_provider_uid" insert="false" update="false"/>
<property name="UID" column="uid" insert="false" update="false"/>
<property name="nickname" column="nickname" />
<property name="photoURL" column="photo_url" />
<property name="thumbnailURL" column="thumbnail_url" />
<property name="birthDay" column="birthday" />
<property name="birthMonth" column="birthmonth" />
<property name="birthYear" column="birthyear" />
<property name="gender" column="gender" />
<property name="proxiedEmail" column="proxied_email" />
<property name="country" column="country" />
<property name="state" column="state" />
<property name="city" column="city" />
<property name="zip" column="zip" />
<property name="firstname" column="firstname" />
<property name="lastname" column="lastname" />
<property name="profileURL" column="profile_url" />
<property name="userID" column="user_id" insert="false" update="false"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="fabulaFactory">
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/appname
</property>
<property name="connection.username">
user
</property>
<property name="connection.password">
pwd
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com//hibernatexmlfiles//User.hbm.xml"/>
<mapping resource="com//hibernatexmlfiles//UsersBooks.hbm.xml"/>
<mapping resource="com//hibernatexmlfiles//UserSocialInfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
While executing the project i am getting an error like this:
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.fabulait.fabula.entities.User.userID
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:70)
at org.hibernate.tuple.AbstractTuplizer.setIdentifier(AbstractTuplizer.java:130)
at org.hibernate.persister.entity.BasicEntityPersister.setIdentifier(BasicEntityPersister.java:2930)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:146)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:477)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:472)
at com.service.UserService.storeSessionInfo(UserService.java:410)
at com.web.LoginUser.doPost(LoginUser.java:122)
at com.web.LoginUser.doGet(LoginUser.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:40)
... 32 more
So please give suggestions.
It should be
from User u where u.username=:username
I assume User is the entity class (#Entity) mapped with table
Also, keep in mind if you have turned auto-import to "false", you'll need to either fully qualify the classname, or set name
#Entity(name="User")
public class User {
}
As a suggestion, for most simpler queries, it's usually easier (and more performant since you don't have to parse the hql to an AST tree) to use criteria queries. And in your case, you're just checking for any match. So iterating through the results to compare the username is redundant to what is in your where clause. The following is a much more efficient way to do what you're looking for:
Criteria c = session.createCriteria(User.class);
c.add(Restrictions.eq("username", username));
c.setProjection(Projections.rowCount());
Number count = (Number) c.uniqueResult();
return (count.intValue() > 0);

Categories