one to many relationship in java google ap engine caused error ? - google-app-engine

i have implement a system to save information about user .
So i have aggregation at my class so the user class has list from contact class ...etc
in the first page "test it's just for register the user just by phone number " that must save the user in database but this cause error when i deploye my project in Google app engine < 500 server error >
and the other page for update the exist user who previously has been registered, so at this will add to the list which the user object has .
user class
#PersistenceCapable
public class User implements Serializable{
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public String userNumber;
#Persistent (mappedBy = "userC")
public List<Contact> UserContacts =new ArrayList<Contact>();
public void AddContact(String name,String number) {
Contact C=new Contact();
C.ContactName=name;
C.PhoneNumber=number;
this.UserContacts.add(C); }
}
Contact class
#PersistenceCapable
public class Contact implements Serializable{
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public String ContactName;
#Persistent
public String PhoneNumber;
#Persistent
public User userC; }
this page cause register for the user test will get user phone number and sign up should create new user with this number
test page
#SuppressWarnings("serial")
public class Test extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><body><form method = \"POST\" action=\"/signup\">" + "please enter ur number :"+"<h4><label>name : <input name = \"userphoneNUMBER\" type = \"text \" size = \"25 \" /> </label>"+"<p> <input type = \"submit\" value = \"Submit\" />"+ "</form></body></html>");
}
}
this page take the number to create user
#SuppressWarnings("serial")
public class SignUP extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
String user_PhoneNumber=req.getParameter("userphoneNUMBER");
User obj = new User();
obj.userNumber=user_PhoneNumber;
resp.getWriter().println(obj.userNumber );
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(obj);
} finally {
pm.close();
} } }
this page to continue update value at user object who already exist
#SuppressWarnings("serial")
public class Testinfo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><body><form method = \"POST\" action=\"/saveinfo\">" +
"<center> <h2>please fill this form :</h2> </br> "+
"<h4><label> ContactName : <input name = \"ContactName\" type = \"text \" size = \"25 \" /> </label>"
+
"<p> <input type = \"submit\" value = \"Submit\" />"+
"</form></body></html>");
}
}
this page to save the information which cause error and no value will save at app engine
#SuppressWarnings("serial")
public class SaveInfo extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
String ContactName = req.getParameter("ContactName");
String ContactNumber = req.getParameter("ContactNumber");
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select from " + User.class.getName());
List<User> list = (List<User>) query.execute();
for (User obj : list) {
if (obj.userNumber.equals("111")) {
pm.currentTransaction().begin();
obj.AddContact(ContactName, ContactNumber);
pm.makePersistent(obj);
pm.currentTransaction().commit(); }
}
pm.close(); } }
this 111 for testing which i entered before as user phone number .
So how can i deal with lists and aggregation issues ??
when going to update the user information this error occurred
Uncaught exception from servlet
javax.jdo.JDOUserException: Identifier expected at character 1 in "*" at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:375)
at org.datanucleus.jdo.JDOQuery.execute(JDOQuery.java:230)
at sstooree.SaveInfo.doPost(SaveInfo.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:102)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)

the problem in the query
change this
Query query = pm.newQuery("select from " + User.class.getName());
to
Query query = pm.newQuery("select * from " + User.class.getName());
you are not selecting any column . which cause a sql syntax error

Related

Uncaught exception from servlet java.io.IOException at app engine. 500 Server Error after running app second time

I have just started with App Engine and I have tried to make a very simple app which adds Person objects with distinctive names to the datastore. This the object:
#PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Person {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
#Unique
private String name;
public Person(String nameIn){
this.name = nameIn;
}
public Long getId(){
return this.id;
}
public void setId(Long idIn){
this.id = idIn;
}
}
This servlet is responsible for persisting objects on datastore. But prior to that, the method doesUserExist(String) checks whether object with the same 'name' field exists:
#SuppressWarnings("serial")
public class PersonDatastoreServlet extends HttpServlet {
private static final String PARAM_NAME = "name";
private PersistenceManager pmf = PMF.get().getPersistenceManager();
public void doGet(HttpServletRequest req, HttpServletResponse response)
throws IOException {
String name = req.getParameter(PARAM_NAME);
PrintWriter printWriter = response.getWriter();
try{
if(!doesUserExist(name)) {
Person p = new Person(name);
pmf.makePersistent(p);
response.setContentType("text/html");
printWriter.println("<h1>"+p.getId()+"</h1>");
}
else {
response.setContentType("text/html");
printWriter.println("<p>User already exists</p>");
}
}
catch(Exception e) {
throw new IOException();
}
finally{
pmf.close();
}
}
private boolean doesUserExist(String nameIn) {
Query q = pmf.newQuery(Person.class);
q.setFilter("name == lastNameParam");
q.declareParameters("String lastNameParam");
String name = nameIn;
try{
List<Person> list = (List<Person>) q.execute(name);
if (list.isEmpty()){
return false;
}
else return true;
}
finally{
q.closeAll();
}
}
}
The take seems very straightforward, but it just not working. I have a form which processing the request. When I run my app for the first time it does successfully create and persist an object, however whenever i want to add another object with a different name, I am getting the Error
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
It indicates that the query causes the problem but I have idea what is wrong with my query. Can anybody help please?

JDO Entity modification is not persisted

I'm using Google App Engine and I created an persistent entity using Google documentation about JDO. The class is the following:
#PersistenceCapable
public class Message {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public long id;
#Persistent
public Text message;
#Persistent
public boolean isNew;
#Persistent
public long categoryId;
#Persistent
public boolean plus;
#Persistent
public Date lastUpdate;
Message(long id, String message, boolean isNew, long categoryId, Date lastUpdate, boolean plus) {
this.id = id;
this.message = new Text(message);
this.isNew = isNew;
this.categoryId = categoryId;
this.lastUpdate = lastUpdate;
this.plus = plus;
}
}
And than, I create the a HttpServlet with the following doPost code:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
Date tenDaysAgo = new Date(new Date().getTime()-TEN_DAYS_IN_MILISSECOND);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Query queryMessages = pm.newQuery(Message.class);
queryMessages.setFilter("isNew == True && lastUpdate <= lastUpdateParam");
queryMessages.declareParameters(Date.class.getName() + " lastUpdateParam");
List<Message> results = (List<Message>) queryMessages.execute(tenDaysAgo);
for(Message msg : results) {
msg.isNew = false;
pm.makePersistent(msg);
}
//pm.makePersistentAll(results);
writer.print(results.size() + " messages changed.");
}finally {
pm.close();
}
}
But, when I do a post request I receive the message "3048 messages changed." and I check the database and the data is unchanged. The persistence is not working to persist the changes I made in the object. Even though using makePersistentAll( list ) or makePersistent( object ) the result is the same: no change in the database.
What I'm missing?
Thank you!
You need to create a JDO transaction to keep track of changes and then commit them to issue the update SQL statements:
pm.currentTransaction().begin();
for(Message msg : results) {
msg.isNew = false;
}
pm.currentTransaction().commit();

One to many relationship at google app engine can't work? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
one to many relationship in java google ap engine caused error ?
i have implement a system to save information about user .
So i have aggregation at my class so the user class has list from contact class ...etc
in the first page "test it's just for register the user just by phone number " that must save the user in database but this cause error when i deploye my project in Google app engine < 500 server error >
and the other page for update the exist user who previously has been registered, so at this will add to the list which the user object has .
user class
#PersistenceCapable
public class User implements Serializable{
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public String userNumber;
#Persistent (mappedBy = "userC")
public List<Contact> UserContacts =new ArrayList<Contact>();
public void AddContact(String name,String number) {
Contact C=new Contact();
C.ContactName=name;
C.PhoneNumber=number;
this.UserContacts.add(C); }
}
Contact class
#PersistenceCapable
public class Contact implements Serializable{
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public String ContactName;
#Persistent
public String PhoneNumber;
#Persistent
public User userC; }
this page cause register for the user test will get user phone number and sign up should create new user with this number
test page
#SuppressWarnings("serial")
public class Test extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><body><form method = \"POST\" action=\"/signup\">" + "please enter ur number :"+"<h4><label>name : <input name = \"userphoneNUMBER\" type = \"text \" size = \"25 \" /> </label>"+"<p> <input type = \"submit\" value = \"Submit\" />"+ "</form></body></html>");
}
}
this page take the number to create user
#SuppressWarnings("serial")
public class SignUP extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
String user_PhoneNumber=req.getParameter("userphoneNUMBER");
User obj = new User();
obj.userNumber=user_PhoneNumber;
resp.getWriter().println(obj.userNumber );
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(obj);
} finally {
pm.close();
} } }
this page to continue update value at user object who already exist
#SuppressWarnings("serial")
public class Testinfo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><body><form method = \"POST\" action=\"/saveinfo\">" +
"<center> <h2>please fill this form :</h2> </br> "+
"<h4><label> ContactName : <input name = \"ContactName\" type = \"text \" size = \"25 \" /> </label>"
+
"<p> <input type = \"submit\" value = \"Submit\" />"+
"</form></body></html>");
}
}
this page to save the information which cause error and no value will save at app engine
#SuppressWarnings("serial")
public class SaveInfo extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
String ContactName = req.getParameter("ContactName");
String ContactNumber = req.getParameter("ContactNumber");
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select * from " + User.class.getName());
List<User> list = (List<User>) query.execute();
for (User obj : list) {
if (obj.userNumber.equals("111")) {
pm.currentTransaction().begin();
obj.AddContact(ContactName, ContactNumber);
pm.makePersistent(obj);
pm.currentTransaction().commit(); }
}
pm.close(); } }
this 111 for testing which i entered before as user phone number .
So how can i deal with lists and aggregation issues ??
when going to update the user information this error occurred
Uncaught exception from servlet
javax.jdo.JDOUserException: Identifier expected at character 1 in "*" at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:375)
at org.datanucleus.jdo.JDOQuery.execute(JDOQuery.java:230)
at sstooree.SaveInfo.doPost(SaveInfo.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:102)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
by trying to change the query
from
Query query = pm.newQuery("select * from " + User.class.getName());
to
Query query = pm.newQuery("select from " + User.class.getName());
that make the code work successfully without any error :)

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.

Spring + Hibernate JPA Question

I'm trying to use Hibernate with JPA/EntityManager to do database activities
Right now I'm getting this error and I have no idea what it means.
Before I had this code and it works fine.
public class JdbcProductDao extends Dao implements ProductDao {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public List<Product> getProductList() {
logger.info("Getting products!");
List<Product> products = getSimpleJdbcTemplate().query(
"select id, description, price from products",
new ProductMapper());
return products;
}
public void saveProduct(Product prod) {
logger.info("Saving product: " + prod.getDescription());
int count = getSimpleJdbcTemplate().update(
"update products set description = :description, price = :price where id = :id",
new MapSqlParameterSource().addValue("description", prod.getDescription())
.addValue("price", prod.getPrice())
.addValue("id", prod.getId()));
logger.info("Rows affected: " + count);
}
private static class ProductMapper implements ParameterizedRowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
But this code using EntityManager
public class JdbcProductDao implements ProductDao {
/** Logger for this class and subclasses */
//protected final Log logger = LogFactory.getLog(getClass());
#PersistenceContext()
private EntityManager entityManager;
public JdbcProductDao(){
}
public Product getReference(Product product){
return getEntityManager().getReference(product.getClass(),product.getId());
}
public void persist(Product product){
getEntityManager().persist(product);
}
public EntityManager getEntityManager(){
return entityManager;
}
public void setEntityManager(EntityManager entityManager){
this.entityManager = entityManager;
}
#SuppressWarnings("unchecked")
public List<Product> getProductList(){
return getEntityManager().createNativeQuery("select id, description, price from products").getResultList();
}
public void saveProduct(Product product){
getEntityManager().createNativeQuery("update products set description = " + product.getDescription() + " , price = " + product.getPrice() + " where id = " + product.getId());
}
private static class ProductMapper implements ParameterizedRowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
The error I get is "java.lang.NumberFormatException: For input string: "description"
Has anybody experienced something similar to this before?
Edit:
The stack trace is below
java.lang.NumberFormatException: For input string: "description"
java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
java.lang.Integer.parseInt(Integer.java:449)
java.lang.Integer.parseInt(Integer.java:499)
javax.el.ArrayELResolver.coerce(ArrayELResolver.java:153)
javax.el.ArrayELResolver.getValue(ArrayELResolver.java:45)
javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
org.apache.el.parser.AstValue.getValue(AstValue.java:118)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:935)
org.apache.jsp.WEB_002dINF.jsp.hello_jsp._jspx_meth_c_005fout_005f1(hello_jsp.java:245)
org.apache.jsp.WEB_002dINF.jsp.hello_jsp._jspx_meth_c_005fforEach_005f0(hello_jsp.java:210)
org.apache.jsp.WEB_002dINF.jsp.hello_jsp._jspService(hello_jsp.java:92)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:236)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:257)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1183)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:902)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Look at the stacktrace - there is nothing to do with JPA, you have EL syntax error in the attributes of <c:out> tag in you JSP.

Resources