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
Related
I am attempting to update an Employee row in my Employee table using JDBI. However, the bindBean method doesn't appear to like my bean. I have included getters and setters. The bean has a public default constructor. The property names of the object are an exact match for the database column names. So the LastName String for instance, corresponds to a LastName database column. Exact match. What am I doing wrong here? Am I misconstruing how bindBean works? I also tried this same code with a prefix in front of the :parameters, still no dice.
EDIT: After a little more research, I believe the issue is coming from the fact that my column names and properties start with capital letters. Annotating my getters and setters with #ColumnName and the appropriate uppercase column names does not appear to be helping though.
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
Dao Method:
#Override
public void updateEmployee(Employee empl){
try(Handle handle = daoFactory.getDataSourceController().open()){
handle.createUpdate("UPDATE Employees SET LastName = :LastName, FirstName = :FirstName, EmailAddress = :EmailAddress, OnVacation = :OnVacation, Active = :Active, EscalationLevel = :EscalationLevel," +
" ScheduleExempt = :ScheduleExempt, GroupID = :GroupID, ScheduleID = :ScheduleID, SecurityGID = :SecurityGID, JobTitle = :JobTitle, Blurb = :Blurb WHERE IDX = :IDX")
.bindBean(empl)
.execute();
handle.commit();
}
catch(Exception e){
if(verbose){ e.printStackTrace(); }
logger.logError("Web-EmployeeDaoService-E04", "Error updating single user in DB.");
}
}
And my bean:
package app.pojos.Employee;
import java.io.Serializable;
import java.sql.Timestamp;
public class Employee implements Serializable {
private int IDX;
private String LastName;
private String FirstName;
private String EmailAddress;
private boolean OnVacation;
private boolean Active;
private int EscalationLevel;
private boolean ScheduleExempt;
private int GroupID;
private int ScheduleID;
private int SecurityGID;
private String JobTitle;
private String Blurb;
private Timestamp LastSeen;
private String ProfilePic;
//Default constructor
public Employee(){}
//Data mapped getters and setters
public int getIDX(){ return IDX; }
public void setIDX(int IDX){ this.IDX = IDX; }
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; }
public String getProfilePic(){ return ProfilePic; }
public void setProfilePic(String ProfilePic){ this.ProfilePic = ProfilePic; }
public String getEmailAddress(){ return EmailAddress; }
public void setEmailAddress(String emailAddress){ this.EmailAddress = emailAddress; }
public int getGroupID(){ return GroupID; }
public void setGroupID(int GroupID){ this.GroupID = GroupID; }
public boolean getScheduleExempt(){ return ScheduleExempt; }
public void setScheduleExempt(boolean ScheduleExempt){ this.ScheduleExempt = ScheduleExempt; }
public boolean getOnVacation(){ return OnVacation; }
public void setOnVacation(boolean OnVacation){ this.OnVacation = OnVacation; }
public boolean getActive(){ return Active; }
public void setActive(boolean Active){ this.Active = Active; }
public int getEscalationLevel(){ return EscalationLevel; }
public void setEscalationLevel(int EscalationLevel){ this.EscalationLevel = EscalationLevel; }
public int getScheduleID(){ return ScheduleID; }
public void setScheduleID(int ScheduleID){ this.ScheduleID = ScheduleID; }
public int getSecurityGID(){ return SecurityGID; }
public void setSecurityGID(int SecurityGID){ this.SecurityGID = SecurityGID; }
public String getJobTitle(){ return JobTitle; }
public void setJobTitle(String JobTitle){ this.JobTitle = JobTitle; }
public String getBlurb(){ return Blurb; }
public void setBlurb(String Blurb){ this.Blurb = Blurb; }
public Timestamp getLastSeen() { return LastSeen; }
public void setLastSeen(Timestamp LastSeen) { this.LastSeen = LastSeen; }
//Extra helper functions
public String getFullName(){ return this.FirstName + " " + this.LastName; }
}
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
See this response for clarity. If you're like me and made the mistake of going against best practice naming conventions and capitalized all of your bean properties, this is an easy solution. You only need to change how you reference the properties in your create/update/insert queries and nothing else.
Hello Stack overflow,
I have the following Problem:
I have these entity classes:
public class UnknownEntity extends NetworkEntity{
#Id
#GeneratedValue(strategy = UuidStrategy.class)
private String id;
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getId() {
return id;
}
}
#NodeEntity
public class NetworkEntity {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
protected String id;
public List<NetworkInterfaceEntity> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<NetworkInterfaceEntity> interfaces) {
this.interfaces = interfaces;
}
#Relationship(type = "is_composed_of")
protected List<NetworkInterfaceEntity> interfaces ;
}
#NodeEntity
public class NetworkInterfaceEntity {
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InterfaceState getState() {
return state;
}
public void setState(InterfaceState state) {
this.state = state;
}
public List<NetworkInterfaceEntity> getSubInterfaces() {
return subInterfaces;
}
public void setSubInterfaces(List<NetworkInterfaceEntity> subInterfaces) {
this.subInterfaces = subInterfaces;
}
public long getBytesSent() {
return bytesSent;
}
public void setBytesSent(long bytesSent) {
this.bytesSent = bytesSent;
}
public long getBytesRecived() {
return bytesRecived;
}
public void setBytesRecived(long bytesRecived) {
this.bytesRecived = bytesRecived;
}
#Id
private String interfaceId;
private String ipAddress;
private String netmask;
private String macAddress;
private String name;
private InterfaceState state;
#Relationship(type = "is_composed_of")
private List<NetworkInterfaceEntity> subInterfaces;
private long bytesSent;
private long bytesRecived;
}
When I now try to query the UnknownEntities via a Neo4j Crud Repository with a custom #Query Method, the UnknownEntities wont be nested with the necessary NetworkInterfaceObjects, even tough my query returns these.
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN collect(unknown),nodes(p),rels(p)")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
In this particular case the NetworkInterfaceEntities do not contain more subInterfaces, so I only want the NetworkInterfaceEntities that belong the the UnknownEntity. But when I use this Query I only get UnknownEntities where the NetworkInterfaceList is null. I even tried different Querys to no avail for example:
"MATCH p=(u:UnknownEntitie)-[:is_composed_of]-(n:NetworkInterfaceEntity) WHERE n.ipAddress in {0} RETURN collect(n),nodes(p),rels(p)".
My Question is, if what I want is even possible with SDN4 Data and if it is, how I can achieve this, Since my alternative is to query the database for every NetworkInterface separately, which I think is really ugly.
Any help would be much appreciated.
please try if returning the full path like this:
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN p")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
works for your. If not, try naming the objects in question, i.e. RETURN i as subInterfaces works for you.
Are you using Spring Data Neo4j 4 or 5? If you're on 4, consider the upgrade to 5 to be on a supported level.
Please let me know, if this helps.
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
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!