Persisted objects overwrite the last record instead of creating a new one with Spring MVC, Google App Engine, JDO3 - google-app-engine

I'm using Spring MVC 3.1.2 with Google App Engine. I have a problem with persisting objects in the data store using JDO3. The weird problem is that whenever I persist objects (during a short period of time) the last added object doesn't get persisted in a new record it just overwrites the last record keeping the same id (the id of the last record). Here are the files that could be concerned.
User.java
#Component
#PersistenceCapable
public class User {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
private String firstName;
#Persistent
private String lastName;
#Persistent
private String email;
#Persistent
private String password;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setId(Long id) {
this.id = id;
}
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 setPassword(String password) {
this.password = password;
}
}
UserDaoImpl.java
#Repository
public class UserDaoImpl implements UserDao {
private static PersistenceManager pm;
#Override
public void add(User user) {
if (pm == null || pm.isClosed()) {
pm = PMF.get().getPersistenceManager();
}
try {
pm.makePersistent(user);
} finally {
pm.close();
}
}
}
PMF.java
public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF() {}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
UserController.java
#Controller
public class UserController {
#Autowired
UserService userService;
#Autowired
User user;
#RequestMapping(value="/adduser", method=RequestMethod.GET)
String adduser(){
return "adduser";
}
#RequestMapping(value="/adduser.do", method=RequestMethod.POST)
String saveUserr(#RequestParam String firstname,#RequestParam String lastname, #RequestParam String email, #RequestParam String password){
this.user.setFirstName(firstname);
this.user.setLastName(lastname);
this.user.setEmail(email);
this.user.setPassword(password);
userService.add(user);//this invokes the UseDaoImpl add(user)
}
}
jdoconfig.xml
<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig_3_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig http://java.sun.com/xml/ns/jdo/jdoconfig_3_0.xsd">
<persistence-manager-factory name="transactions-optional">
<property name="javax.jdo.PersistenceManagerFactoryClass"
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="appengine"/>
<property name="javax.jdo.option.NontransactionalRead" value="true"/>
<property name="javax.jdo.option.NontransactionalWrite" value="true"/>
<property name="javax.jdo.option.RetainValues" value="true"/>
<property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
<property name="datanucleus.appengine.singletonPMFForName" value="true"/>
</persistence-manager-factory>
</jdoconfig>

What I feel is you are not initializing the User Object, instead of Autowired annotation try the following code.
#RequestMapping(value="/adduser.do", method=RequestMethod.POST)
String saveUser(#RequestParam String firstname,#RequestParam String lastname, #RequestParam String email, #RequestParam String password){
User user = new User();
user.setFirstName(firstname);
user.setLastName(lastname);
user.setEmail(email);
user.setPassword(password);
userService.add(user);//this invokes the UseDaoImpl add(user)
}

Related

DynamoDB NullPointerException Error on save

Im trying to save info to DynamoDB but im currently getting the error java.lang.NullPointerException: null when using "save" on the AccountHelper class.
I followed the starter guide found on Github; https://github.com/derjust/spring-data-dynamodb
Here is my Model Class;
#DynamoDBTable(tableName = "Users")
public class User {
// #Id
private String _id;
private String bloodGroup;
private String firstName; // DO NOT change this, needs to stay firstName
private String surname;
private String email;
private String password;
private String addressline;
private String postcode;
private String latitude;
private String longitude;
public User() {}
// More Constructors, Getters & Setters
DynamoDB Config Class;
#EnableDynamoDBRepositories(includeFilters = {#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {DynamoDBRepo.class})})
#Configuration
public class DynamoDBConfig {
#Value("${amazon.aws.accesskey}")
private String amazonAWSAccessKey;
#Value("${amazon.aws.secretkey}")
private String amazonAWSSecretKey;
public AWSCredentialsProvider amazonAWSCredentialsProvider() {
return new AWSStaticCredentialsProvider(amazonAWSCredentials());
}
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
#Primary
#Bean
public DynamoDBMapperConfig dynamoDBMapperConfig() {
return DynamoDBMapperConfig.DEFAULT;
}
#Bean
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig config) {
return new DynamoDBMapper(amazonDynamoDB, config);
}
#Bean
public AmazonDynamoDB amazonDynamoDB() {
return AmazonDynamoDBClientBuilder.standard().withCredentials(amazonAWSCredentialsProvider())
.withRegion(Regions.US_EAST_1).build();
}
}
Here is the method/class where i am getting the error;
#Service
public class AccountHelper {
private DynamoDBRepo dynamoDBRepo;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public User create(String bloodGroup, String firstname, String surname, String email, String password, String addressline, String postcode) {
// Getting the error here
return dynamoDBRepo.save(new User(bloodGroup, firstname, surname, email, bCryptPasswordEncoder.encode(password), addressline, postcode));
}
// More methods below that i am not adding to keep this question to a minimum.
Here is my controller;
#Controller
#Component
public class AccountController {
#Autowired
private AccountHelper Service_functions;
#ResponseBody // Works
#PostMapping(value = "/create/{bloodGroup}/{firstname}/{surname}/{email}/{password}/{addressline}/{postcode}")
public String create( #PathVariable String bloodGroup , #PathVariable String firstname, #PathVariable String surname, #PathVariable String email, #PathVariable String password, #PathVariable String addressline, #PathVariable String postcode){
User CreateUser = Service_functions.create(bloodGroup, firstname, surname, email, password, addressline, postcode);
System.out.println("this is working");
return CreateUser.toString();
}
account properties;
spring.application.name=account-service
server.port=8020
eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
amazon.aws.accesskey="" // i removed the keys
amazon.aws.secretkey=""
Any Suggestions/Help would be greatly on where i am going wrong.
Two things you need to fix here based on your details provided.
Add #Autowired annotation on your dynamoDBRepo variable so that it can be recognised as spring managed bean.
Based on your comment
i.e. error saying that it cannot find
com.bdonor.accountservice.Repository.DynamoDBRepo
You need to include com.bdonor.accountservice.Repository package as JPA repository package and enable jpa repository scan in your configuration.

An existing connection was forcibly closed by the remote host (com.microsoft.sqlserver.jdbc.SQLServerException) Exception

i am trying to save record in my sql server database using spring when i try to run the application i am getting org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: An existing connection was forcibly closed by the remote host ClientConnectionId:1a7dc54d-3764-44ff-ab47-8793b826b093
Employee.java
package com;
public class Employee {
private int id;
private String name;
private int salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public Employee() {
}
public Employee(int id, String name, int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
}
EmployeeDao.java
package com;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate=jdbcTemplate;
}
public int saveEmployee(Employee e){
String query="insert into employee values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
return jdbcTemplate.update(query);
}
public int updateEmployee(Employee e){
String query="update employee set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee e){
String query="delete from employee where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDataSource"/>
<property name="url" value="jdbc:sqlserver://localhost:5432;databaseName=qm"/>
<property name="username" value="postgres"/>
<property name="password" value="mypass"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
and my App Test is
Test.java
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee(102,"Amit",35));
System.out.println(status);
}
}

Registration user using JSF, JPA, how to hash password?

I want to create users in database with md5 password, but I don't have idea, how to do it best. I am using JSF (+PrimeFaces) and JPA.
Pieces of code:
registration.xhml:
<p:password id="password" value="#{userBean.password}" match="repeatPassword" required="true" label="Password"> <f:validateLength minimum="8" /> </p:password>
UserBean:
#ManagedBean
#RequestScoped
public class UserBean {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void register(){
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setPassword(password);
dao.addUser(user);
}
User
#Entity
#Table(name = "users")
public class User implements Serializable {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

How to convert bootstrap datetimepicker string to java datetime

angular controller
$http({
method: 'POST',
url: '/Eatery/save',
contentType:'application/json',
dataType:'json',
data:resvnCtrl.user
})
Spring mvc controller
#RequestMapping(value="/save",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int save(#RequestBody Reservation reservation) {
System.out.println(reservation.getTime());
return reservationRepo.save(reservation);
}
Java model
#Entity
#Table(name="reservations")
public class Reservation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String cnf;
private String name;
private String email;
private String phone;
#JsonDeserialize(using=CustomJsonDateDeserializer.class)
private LocalDateTime time;
private int seats;
private String note;
public Reservation() { }
public Reservation(String cnf, String name, String email, String phone,
LocalDateTime time, int seats, String note) {
this.cnf = cnf;
this.name = name;
this.email = email;
this.phone = phone;
this.time = time;
this.seats = seats;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCnf() {
return cnf;
}
public void setCnf(String cnf) {
this.cnf = cnf;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
From browser console
email: "kerhb#regerg.e"
name: "kjergk"
note: "wefwef"
phone: "1234567899"
seats: 2
time: "10/23/2015 5:53 PM"
Custom date deserializer
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
#Override
public Date deserialize(JsonParser jsonparser,
DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date = jsonparser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
I have a bootstrap datetimepicker on UI and a java REST webservice at the backend. when i send date select, i got "The request sent by the client was syntactically incorrect.". the datetime string which is sent did not map to the java model. can someone spot my error
#Marged is rigth saying that you didn't cover AM/PM in your date pattern. The proper patter would be yyyy-MM-dd HH:mm a. Note also that you don't need a custom deserializer for this, can rather use #DateTimeFormat
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm a")
private LocalDateTime time;

Save gwt entities to google application engine datastore with jdo, using rpc

Hello iam new to GWT framework. I want to persist my domain objects/entities to google application engine datastore using rpc. A simple implementation to test if i can make multiple rpc calls ( greetServer() , saveStudent() )
Student
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.gwt.user.client.rpc.IsSerializable;
#PersistenceCapable
public class Student implements IsSerializable {
private static final long serialVersionUID = 1L;
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
#Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private int studentId;
#Persistent private String firstName;
#Persistent private String lastName;
public Student(){}
public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public int getStudentId() {
return studentId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
GreetingService (default code generated by Eclipse IDE)
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
**String saveStudent(Student s) throws IllegalArgumentException;**
}
GreetingServiceAsync
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
**void saveStudent(Student s, AsyncCallback<String> callback)
throws IllegalArgumentException;**
}
GreetingServiceImpl
import javax.jdo.PersistenceManager;
import com.d.client.GreetingService;
import com.d.client.Student;
import com.d.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public String greetServer(String input) throws IllegalArgumentException
...
String serverInfo = getServletContext().getServerInfo();
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
...
}
#Override
public String saveStudent(Student s) throws IllegalArgumentException {
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(s);
return "student save - ok";
}
}
PMF
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
EntryPoint
...
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
greetingService.greetServer("greet",
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
greetingService.saveStudent(new Student("kostas","trichas"),
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
...
Is the above implementation correct? I deployed this sample application to gae and it did not persisted the object student (you can browse the entities at gae datastore viewer)
check it please:
http://gwtgaedatastore.appspot.com
Change your int studentID to Long id to get it working
This works with your original code (ie., Long id):
#Extension (vendorName="jpox", key="key-auto-increment" ,value="true")
Or, change id to String and your orig code works.
I could not get Long PK to work with datanucleus using gae.pk-id.

Resources