How to finish validation with sending all form data in Vaadin 8? Unfortunetly I dont understand binder concept :( I wrote a field validation but what now? It works. My user see when I demand that he fill out a field but is there any easy way to validate my all form? How can I "tell" to my save button that my form is valid?
In my editor Im defining a validator
#SpringComponent
#PrototypeScope
public class VaadinStringEditor extends TextField implements HasValueComponent<String> {
private Binder<String> binder;
BinderValidationStatus<String> status;
#PostConstruct
public void init() {
setWidth("100%");
binder = new Binder<>();
}
#Override
public void initDefaults() {
setValue("");
status = binder.validate();
}
#Override
public void setConfiguration(EditorConfiguration editorConfiguration) {
Validator<String> validator = ((TextFieldConfiguration) editorConfiguration).getValidator();
if (validator != null) {
binder.forField(this).withValidator(validator).asRequired("Mandatory").bind(s -> getValue(),
(b, v) -> setValue(v));
}
public BinderValidationStatus<String> getStatus() {
return status;
}
public void setStatus(BinderValidationStatus<String> status) {
this.status = status;
}
public boolean validate() {
BinderValidationStatus<String> status = binder.validate();
return status.isOk();
}
}
}
I have also an TextEditorConfiguration added:
public class TextFieldConfiguration implements EditorConfiguration {
private Validator<String> validator;
private int validated;
public TextFieldConfiguration(Validator<String> validator) {
this.validator = validator;
}
public TextFieldConfiguration() {
this.validator = null;
}
public Validator<String> getValidator() {
return validator;
}
public int getValidated() {
return validated;
}
public void setValidated(int validated) {
this.validated = validated;
}
}
In my case there are plenty of editors like DateEditor and so on. UI Valtidation works well. Since one month I can not find a way how to connect it to submit button to prevent send a form.
In the form class I have defined all questions
for example:
question = new AseQuestion(AseQuestionId.DATE_OF_NOTIFICATION, EditorType.DATE_EDITOR);
question.setDescription(
"When it happend?");
question.setEditorConfiguration(new DateFieldConfiguration(dateRequiredValidator(), dateNotAllowedValidator()));
return question;
question = new AseQuestion(AseQuestionId.QUESTION2, EditorType.STRING_EDITOR);
question.setDescription("
"Write something");
private Validator<String> textRequiredValidator() {
return Validator.from(v -> v != null && StringUtils.trimAllWhitespace((String) v).length() != 0,
"It cannot be empty!!!");
And the class where I have a submit button
public class QuestionWindow extends Window {
#Autowired
private transient VaadinStringEditor editor;
private Button createSaveButton() {
Button saveButton = new Button(i18n.getWithDefault("newAseQuestions.save", "Übernehmen"));
saveButton.addClickListener(e -> {
if (editor.getBinder.validate()) {
Notification.show("This is the caption OK", "This is the description",
Notification.Type.HUMANIZED_MESSAGE);
} else {
Notification.show("This is the caption", "This is the description",
Notification.Type.HUMANIZED_MESSAGE);
System.out.println("kurwa");
}
saveAse();
});
return saveButton;
}
OK lets assume we haven this POJO:
public class Person {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
And we want to edit it.
So we build the following form:
public class Form {
private TextField firstname;
private TextField lastname;
private Binder<Person> binder = new Binder<>();
void bindFields() {
binder.forField(firstname).withValidator(textRequiredValidator())
.asRequired("Mandatory").bind(Person::getFirstname, Person::setFirstname);
binder.forField(lastname).withValidator(textRequiredValidator())
.asRequired("Mandatory").bind(Person::getLastname, Person::setLastname);
}
public void setDatasource(Person person) {
binder.setBean(person);
}
private Validator<String> textRequiredValidator() {
return Validator.from(v -> v != null && StringUtils.trimAllWhitespace((String) v).length() != 0,
"It cannot be empty!!!");
}
public boolean validate() {
BinderValidationStatus<Person> status = binder.validate();
return status.isOk();
}
}
In order to use this form we need to call bindFields first (e.g. constructor, init).
Than a controller or so calls setDatasource with the person we want to edit.
After this the user can fill or edit the form and when the user finishes the status of the form can be retrieved via validate.
If you need the errors from the fields you get them from the BinderValidationStatus.
For more information look at https://vaadin.com/docs/v8/framework/datamodel/datamodel-forms.html
Related
trying to access JSON data from the following:
{"actions":[{"actionType":0,"email":"contact#tonyspizza.com","faIcon":"fa-envelope",
"name":"Contact Us","subject":"Email from Tony's Pizza App"},
{"actionType":2,"faIcon":"fa-phone","name":"Call Us","number":"5204558897"}],
"total":2}
I'm trying to use retrofit to access the 'actions' as each individual classes. (i.e. ActionEmail, ActionPhone, etc). I cannot figure out a way to separate these into separate classes and not have one class with all the properties.
Thanks in advance!
Call<ActionWrapperObject> getActions(// Put your api call body in there);
Here is your ActionWrapperObject
public class ActionWrapperObject {
ArrayList<ActionModel> actions;
public ArrayList<ActionModel> getActions() {
return actions;
}
public void setActions(ArrayList<ActionModel> actions) {
this.actions = actions;
}
}
Here is your ActionModel
public class ActionModel {
int actionType;
String email;
String faIcon;
String name;
String subject;
public int getActionType() {
return actionType;
}
public void setActionType(int actionType) {
this.actionType = actionType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFaIcon() {
return faIcon;
}
public void setFaIcon(String faIcon) {
this.faIcon = faIcon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
You in your response
Your api call.enqueue(new Callback<ActionWrapperObject>() {
#Override
public void onResponse(Call<ActionWrapperObject> call, Response<ActionWrapperObject> response) {
ActionWrapperObject actionWrapperObj= response.body();
if (actionWrapperObj!= null) {
ArrayList<ActionModel> actionModelList= actionWrapperObj.getActions();
//Here you got the list of actions. Do what ever you want with them. You can
// differentiate each action on its type.
}
}
What I infer is you want to generate fields of the ActionModel class dynamically. You can refer to generating JSON pojo dynamically using reflection.
Here is the problem, when I send my object to server using retrofit I got it null. I'm doing this to create the json object:
HashMap<String, UserModel> map = new HashMap<>();
map.put("user", user);
But, when the json arrives in the server I got something like this:
{"user":null}
Then I printed ny json file with this line:
Log.d("TAG", new JSONObject(map).toString());
And I saw the same null object.
So, here is my question, Why is this happening? And how can I fix that?
Here goes some information about my project:
Retrofit version: 2.0.0
Retrofit serializer: jackson version 2.0.0
using also jackson to convert JodaTime version 2.4.0
here goes how I get retrofit instance:
public T buildServiceInstance(Class<T> clazz){
return new Retrofit.Builder().baseUrl(BuildConfig.API_HOST)
.addConverterFactory(JacksonConverterFactory.create())
.build().create(clazz);
}
I call that method here:
public static final IUserApi serviceInstance = new ApiBuildRequester<IUserApi>()
.buildServiceInstance(IUserApi.class);
Method declaration on interface IUserApi:
#POST("User.svc/Save")
Call<ResponseSaveUserApiModel> save(#Body HashMap<String, UserModel> map);
And at last, but I guess, not less important:
public class UserModel implements Parcelable {
private String idUser;
private String name;
private String email;
#JsonProperty("password")
private String safePassword;
private String salt;
private String phoneNumber;
private String facebookProfilePictureUrl;
private String facebookUserId;
public UserModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSafePassword() {
return safePassword;
}
public void setSafePassword(String safePassword) {
this.safePassword = safePassword;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFacebookProfilePictureUrl() {
return facebookProfilePictureUrl;
}
public void setFacebookProfilePictureUrl(String facebookProfilePictureUrl) {
this.facebookProfilePictureUrl = facebookProfilePictureUrl;
}
public String getFacebookUserId() {
return facebookUserId;
}
public void setFacebookUserId(String facebookUserId) {
this.facebookUserId = facebookUserId;
}
#Override
public int describeContents() {
return 0;
}
public UserModel(Parcel in) { // Deve estar na mesma ordem do "writeToParcel"
setIdUser(in.readString());
setName(in.readString());
setEmail(in.readString());
setSafePassword(in.readString());
setPhoneNumber(in.readString());
setFacebookProfilePictureUrl(in.readString());
setFacebookUserId(in.readString());
}
#Override
public void writeToParcel(Parcel dest, int flags) { //Deve estar na mesma ordem do construtor que recebe parcel
dest.writeString(idUser);
dest.writeString(name);
dest.writeString(email);
dest.writeString(safePassword);
dest.writeString(phoneNumber);
dest.writeString(facebookProfilePictureUrl);
dest.writeString(facebookUserId);
}
public static final Parcelable.Creator<UserModel> CREATOR = new Parcelable.Creator<UserModel>(){
#Override
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
#Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Debug screen:
#Selvin and #cricket_007 You are the best!
I got this using your hint that my printing was wrong, and I found the solution.
I have two types of users in my app, facebook users or native users, two forms, but just one object, and here was the problem, when I sent facebook objects (complete) it worked fine, but when I tried to send native users, with some null properties, it crashed my serialization.
So I had to check every property before send it, it's just a workaround, but for now it's enough, thank you a lot folks!
I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
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:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}
I am new to implement Azure Mobile Service. I have refer the demo of ToDoItem given by Azure.
In same manner i have make class User for my own app. Then I am inserting the data in to the MobileServiceTable but it gives me error like below:
{"message":"The operation failed with the following error: 'A null store-generated value was returned for a non-nullable member 'CreatedAt' of type 'CrazyLabApp.Models.User'.'."}
I have not created any field like this as it is not created in ToDoItem demo as well. I have seen that there are 4 fields that are by Default created by the MobileServiceTable. createdAt is one of the field of that.
I am wonder about whats wrong i am doing.
Check my below Userclass:
public class User {
#com.google.gson.annotations.SerializedName("id")
private String ServiceUserId;
#com.google.gson.annotations.SerializedName("email")
private String Email;
#com.google.gson.annotations.SerializedName("firstname")
private String FirstName;
#com.google.gson.annotations.SerializedName("lastname")
private String LastName;
#com.google.gson.annotations.SerializedName("profilepic")
private String ProfilePic;
#com.google.gson.annotations.SerializedName("introduction")
private String Introduction;
#com.google.gson.annotations.SerializedName("website")
private String Website;
#com.google.gson.annotations.SerializedName("title")
private String Title;
#com.google.gson.annotations.SerializedName("_createdAt")
private Date CreatedAt;
#com.google.gson.annotations.SerializedName("coverimage")
private ArrayList<CoverImage> CoverImages;
/*public Date getCreatedAt() {
return CreatedAt;
}
public void setCreatedAt(Date createdAt) {
CreatedAt = createdAt;
}*/
#com.google.gson.annotations.SerializedName("followers")
private ArrayList<User> Followers;
#com.google.gson.annotations.SerializedName("likes")
private ArrayList<Likes> Likes;
#com.google.gson.annotations.SerializedName("collections")
private ArrayList<Collections> Collections;
#com.google.gson.annotations.SerializedName("comments")
private ArrayList<Comments> Comments;
#com.google.gson.annotations.SerializedName("stories")
private ArrayList<Story> Stories ;
//-------------- Methods
public ArrayList<Story> getStories() {
return Stories;
}
public void setStories(ArrayList<Story> stories) {
Stories = stories;
}
public ArrayList<com.promact.crazylab.model.Comments> getComments() {
return Comments;
}
public void setComments(ArrayList<com.promact.crazylab.model.Comments> comments) {
Comments = comments;
}
public ArrayList<com.promact.crazylab.model.Collections> getCollections() {
return Collections;
}
public void setCollections(ArrayList<com.promact.crazylab.model.Collections> collections) {
Collections = collections;
}
public ArrayList<com.promact.crazylab.model.Likes> getLikes() {
return Likes;
}
public void setLikes(ArrayList<com.promact.crazylab.model.Likes> likes) {
Likes = likes;
}
public ArrayList<User> getFollowers() {
return Followers;
}
public void setFollowers(ArrayList<User> followers) {
Followers = followers;
}
public ArrayList<CoverImage> getCoverImages() {
return CoverImages;
}
public void setCoverImages(ArrayList<CoverImage> coverImages) {
CoverImages = coverImages;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getWebsite() {
return Website;
}
public void setWebsite(String website) {
Website = website;
}
public String getIntroduction() {
return Introduction;
}
public void setIntroduction(String introduction) {
Introduction = introduction;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getServiceUserId() {
return ServiceUserId;
}
public void setServiceUserId(String serviceUserId) {
ServiceUserId = serviceUserId;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).ServiceUserId == ServiceUserId;
}
}
Also check below code the way i am inserting it:
final User u = new User();
u.setFirstName(mName);
u.setEmail(mEmail);
u.setProfilePic(mUrl);
mUserTable = mClient.getTable(User.class);
// Insert the new item
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final User entity = mUserTable.insert(u).get();
} catch (Exception e){
//createAndShowDialog(e, "Error");
System.out.println("Error: "+e.toString());
}
return null;
}
}.execute();
Please help me in this.
The "_createdat" column will be populated automatically by Azure Mobile Services so there is no need to include it in your model. Delete this property from the User class. Its presence is probably overwriting the auto-populated value with a null.
you can solve this problem by just deleting createdAt column from your user table in azure.
Why this error is coming :
I am not sure But I guess this error is coming because createdAt is a non-nullable member and you cannot left it null.
EDIT :
Another aspect of the system columns is that they cannot be sent by the client. For new tables (i.e., those with string ids), if an insert of update request contains a property which starts with ‘__’ (two underscore characters), the request will be rejected. The ‘__createdAt’ property can, however, be set in the server script (although if you really don’t want that column to represent the creation time of the object, you may want to use another column for that) – one way where this (rather bizarre) scenario can be accomplished. If you try to update the ‘__updatedAt’ property, it won’t fail, but by default that column is updated by a SQL trigger, so any updates you make to it will be overridden anyway.
for more info take a look here :-http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx
I have an app (Spring MVC + Hibernate) and AppFuse Framework too.
I have two entities: User and Robot with a Many-To-One relationship.
I need to add a drop down list to for owner (User) to the Robot form (robotForm.jsp).
The Robot entity has a User. I read that I must create a custom Editor for User. (UserCustomEditor extends PropertyEditorSupport) and override referenceData in the RobotFormController add in the initBinder too.
RobotFormController
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat(getText("date.format"));
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null,
new CustomDateEditor(dateFormat, true));
binder.registerCustomEditor(Long.class, null,
new CustomNumberEditor(Long.class, null, true));
binder.registerCustomEditor(User.class, new UserEditor(userManager));
}
// ...
protected Map referenceData(HtppServletRequest request) throws Exception {
Map ownersMap = new HashMap();
ownersMap.put("owners", userManager.getUsers();
return ownersMap;
}
userManager.getUsers(); return a List of Users.
UserEditor (maybe here is my error).
public class UserEditor extends PropertyEditorSupport {
private final UserManager userManager;
protected final transient Log log = LogFactory.getLog(getClass());
public UserEditor(UserManager userManager) throws IllegalArgumentException {
this.userManager = userManager;
}
#Override
public void setAsText(String text) throws IllegalArgumentException {
if (text != null && text.length() > 0) {
try {
User user = userManager.getUser(new String (text));
super.setValue(user);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException();
}
} else {
super.setValue(null);
}
}
#Override
public String getAsText() {
User user = (User) super.getValue();
return (user != null ? (user.getId()+"").toString(): "");
}
}
robotForm.jsp
<form:select path="owner" itemValue="id" itemLabel="name" items="${owners}"
</form:select>
I get a NullPointerException in the
ownersMap.put("owners", userManager.getUsers(); line of the referenceData method.
Edit:
UserManagerImpl
#Service(value = "userManager")
public class UserManagerImpl implements UserManager {
#Autowired
UserDao dao;
public void setUserDao(UserDao dao) {
this.dao = dao;
}
public List getUsers() {
return dao.getUsers();
}
public User getUser(String userId) {
return dao.getUser(Long.valueOf(userId));
}
public void saveUser(User user) {
dao.saveUser(user);
}
public void removeUser(String userId) {
dao.removeUser(Long.valueOf(userId));
}
}
Robot.java
public class Robot extends BaseObject {
private static final long serialVersionUID = -1932852212232780150L;
private Long id;
private String name;
private Date birthday;
private User owner;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
The only thing I am seeing why you are having a null in there is that 'userManager' has not been instantiated.
You can check if it has been through (userManager == null).
Your code looks good to me, not looking into the logic. I think your configuration of Spring's IoC is the problem here.
Can you post your *.xml files.
This would help out solve your problems.
Cheers!