dropdownchoice with choicerenderer, how to get values - wicket

i have problem trying to get some values. this is my situation (wicket)
i have a dropdownchoice study_template, i don't have problem populating the DDC, the problem is when i try to get some value (id or name). this is the code
ChoiceRenderer choiceRenderer = new ChoiceRenderer("name", "id");
study_template = new DropDownChoice( "study_template",new PropertyModel( this, "selectedTemplate" ),template_names , choiceRenderer);
template_names is a list< SelectOption > with the values obtain from a DB. this works OK.
this is the class that i use to populate the DDC
public class SelectOption implements java.io.Serializable {
private long id;
private String name;
public SelectOption(long id, String name ) {
this.id = id; this.name=name;
}
public long getId()
{return id; }
public String getName()
{return name; }
}
normally i can get the value with study_template.getModelObject(), but in this case it doesn't work, i don't have any ideas about to obtain the id and the name , i know that i need GETID() and GETNAME(), but i don't know how to use it, any help will be appreciated

You could use something as below:
public class SpikePage extends WebPage {
class Person {
String id;
String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public SpikePage() {
Person employee = new Person("E001", "ABC");
Person manager = new Person("E002", "XYZ");
List personList = new ArrayList(2);
personList.add(employee);
personList.add(manager);
Form form = new Form("form");
final DropDownChoice personDropDownChoice = new DropDownChoice("person", new ArrayList(personList), new IChoiceRenderer() {
#Override
public Object getDisplayValue(Person object) {
return object.getId().concat("-").concat(object.getName());
}
#Override
public String getIdValue(Person object, int index) {
return object.getId();
}
});
personDropDownChoice.setOutputMarkupId(true);
personDropDownChoice.setNullValid(false);
form.add(personDropDownChoice);
final Label label = new Label("name");
label.setOutputMarkupId(true);
form.add(label);
personDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
Person selectedPerson = personDropDownChoice.getModelObject();
label.setDefaultModelObject("Hi ".concat(selectedPerson.getName()));
target.add(label);
}
});
add(form);
}
}

Thanks for your answer, i already get it work
i use this
private SelectOption selectedTemplate;
and then
selectedTemplate.getId();

Related

Want to import image to mongo using springboot

Having trouble creating only one model ,created a photo model and payee model but want to add photo model to payee model but wont accept the binary part of photo . Keep getting binary error when trying to post off of postman ,aware that need to change controller but a bit stuck ,any links or advise for a begginner would be gratefull
//Payee model
public class Payee {
#Id
private String id;
private Contact contact;
private String notes;
private String project;
private String member;
private Integer staffMember;
private Photo photo;
private BankAccount userBankAccount;
private PayeeBankAccount payeeBankAccountList;
//Payee constructor
public Payee(Contact contact, String notes, String project, String member, Integer staffMember,
Photo photo, BankAccount userBankAccount, PayeeBankAccount payeeBankAccountList) {
this.contact = contact;
this.notes = notes;
this.project = project;
this.member = member;
this.staffMember = staffMember;
this.photo = photo;
this.userBankAccount = userBankAccount;
this.payeeBankAccountList = payeeBankAccountList;
}
// Getters and Setters
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public Contact getContact() { return contact; }
public void setContact(Contact contact) { this.contact = contact; }
public String getNotes() { return notes; }
public void setNotes(String notes) { this.notes = notes; }
public String getProject() { return project; }
public void setProject(String project) { this.project = project; }
public String getMember() { return member; }
public void setMember(String member) { this.member = member; }
public Integer getStaffMember() { return staffMember; }
public void setStaffMember(Integer staffMember) { this.staffMember = staffMember; }
public Photo getPhoto() {return photo;}
public void setPhoto(Photo photo) {this.photo = photo;}
public BankAccount getUserBankAccount() { return userBankAccount; }
public void setUserBankAccount(BankAccount userBankAccount) { this.userBankAccount = userBankAccount}
public PayeeBankAccount getPayeeBankAccountList() { return payeeBankAccountList; }
public void setPayeeBankAccountList(PayeeBankAccount payeeBankAccountList){this.payeeBankAccountList= payeeBankAccountList; }
}
//photo model
public class Photo {
#Id
private String id;
private String title;
private Binary image;
//Photo constructor
public Photo(String id, String title, Binary image) {
this.id = id;
this.title = title;
this.image = image;
}
public Photo(String title) {
super();
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
#Override
public String toString() {
return "Photo \[id=" + id + ", title=" + title + ", image=" + image + "\]";
}
}
//photo service
#Service
public class PhotoService {
#Autowired
private PhotoRepository photoRepo;
public Photo getPhoto(String id) {
return photoRepo.findById(id).get();
}
public String addPhoto(String title, MultipartFile file) throws IOException {
Photo photo = new Photo(title);
photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes()));
photo = photoRepo.insert(photo);
return photo.getId();
}
}
Photo and payee PostMapping should be in one ,dont know where to go with this part
//add payee
#PostMapping('/addPayee')
public void insert(#RequestBody Payee payee){
this.payeeRepository.save(payee);
}
//add photo
#PostMapping('/photos/add')
public String addPhoto(#RequestBody Payee payee , #RequestParam("title") String title, #RequestParam("image") MultipartFile image, Model model)
throws IOException {
String id = photoService.addPhoto(title,image);
return id;
}][1]][1]
[1]: https://i.stack.imgur.com/lF6KZ.png
Figured it out in you model have image as binary and in youre controller have some like
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity update(#RequestPart("payee") #Valid Payee payee, #RequestPart("file") #Valid MultipartFile image) throws IOException
{
// routine to update a payee including image
if (image != null)
payee.setImage(new Binary(BsonBinarySubType.BINARY, image.getBytes()));
Payee result = payeeRepository.save(payee);
return ResponseEntity.ok().body(result);
}

POST REST request including a foreign key OnToMany Mapping

i'm new to Springboot. I'm trying to implement a simple REST api using :
-Springboot, JPA & rest along with hibernate
I have a 2 tables database, Notebook that contains 1 to many notes
I already setup the 2 tables and relationships. I also created a NotebookRepository and NoteRepository to get basic CRUD operations via the springboot rest. The Database connection and relationships are functionning
but i don't know how to add a new note (it has a notebook_id foreign key which msut NOT be NULL) and everytime i tryto post something along these lines
{
"title:"abc",
"text":"whatever",
"notebook":{
"id":2
}
}
i get this error :
Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'notebook_id' cannot be null
#Entity
#Table(name="notebook")
public class NoteBook {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#OneToMany(mappedBy="notebook", cascade=CascadeType.ALL)
List<Note> notes;
public NoteBook() {
}
public NoteBook(String name) {
this.name = name;
}
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 List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public void addNote(Note note) {
if(notes == null) {
notes = new ArrayList<>();
}
note.setNotebook(this);
notes.add(note);
}
#Entity
#Table(name="note")
public class Note {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="title")
private String title;
#Column(name="text")
private String text;
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name="notebook_id")
private NoteBook notebook;
public Note() {
}
public Note(String title, String text) {
this.title = title;
this.text = text;
}
#RepositoryRestResource(collectionResourceRel = "note", path = "notes")
public interface NoteRepository extends JpaRepository<Note, Integer>{
//No code...
}
#RepositoryRestResource(collectionResourceRel = "notebook", path = "notebooks")
public interface NotebookRepository extends JpaRepository<NoteBook, Integer>{
}
The problem is that the class Note doesn't have a constructor with NoteBook parameter to pass the created NoteBook object to, so the solution is to add this constructor:
public Note(String title, String text, NoteBook noteBook) {
this.title = title;
this.text = text;
this.noteBook = noteBook;
}
and it's enough to send the JSON object as you do, but just be aware of case-sensitivity:
{ "title:"abc", "text":"whatever", "noteBook":{ "id":2 } }
I think you need to add referencedColumnName = "id" for JoinColumn annotation for notebook field in Note class.
Maybe you have problem with IDENTITY generation type. See this problem with null pointer

Spring boot CrudRepository save - exception is org.hibernate.type.SerializationException: could not serialize

Not sure why I have an issue here, but when I save with a CrudRepository with these objects, I get the SerializationException (with no further information). Can someone take a look at my objects and offer me some insight into why they can't serialize? My pom.xml is attached last as well in case that helps somehow. I'm using a Postgres database.
EDIT: The database and now - tables are created, but objects are not creating rows.
The actual CrudRepository interface:
public interface AccountRepository extends CrudRepository<ZanyDishAccount, String> {}
ZanyDishAccount entity:
#Entity
public class ZanyDishAccount {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id; // internal id of the customer account for a Zany Dish subscription
private String status;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "company_id")
private Company company;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "order_id")
private Order order;
public ZanyDishAccount() {}
public ZanyDishAccount(Company company, Order order) {
this.company = company;
this.order = order;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+ ", company = " + company + ", status = " + status + "]";
}
}
Company entity:
#Entity
public class Company {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String phoneNumber;
private String website;
private String name;
private String uuid;
private String country;
public Company() {}
public Company(String phoneNumber, String website, String name, String uuid, String country) {
this.phoneNumber = phoneNumber;
this.website = website;
this.uuid = uuid;
this.country = country;
}
public String getPhoneNumber ()
{
return phoneNumber;
}
public void setPhoneNumber (String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public String getWebsite ()
{
return website;
}
public void setWebsite (String website)
{
this.website = website;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getUuid ()
{
return uuid;
}
public void setUuid (String uuid)
{
this.uuid = uuid;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
#Override
public String toString()
{
return "ClassPojo [phoneNumber = "+phoneNumber+", website = "+website+", name = "+name+", uuid = "+uuid+", country = "+country+"]";
}
}
Order entity:
#Entity
#Table(name = "_order")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String pricingDuration;
private Items[] items;
private String editionCode;
public Order() {}
public Order(String pricingDuration, Items[] items, String editionCode) {
this.pricingDuration = pricingDuration;
this.items = items;
this.editionCode = editionCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPricingDuration ()
{
return pricingDuration;
}
public void setPricingDuration (String pricingDuration)
{
this.pricingDuration = pricingDuration;
}
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getEditionCode ()
{
return editionCode;
}
public void setEditionCode (String editionCode)
{
this.editionCode = editionCode;
}
#Override
public String toString()
{
return "ClassPojo [pricingDuration = "+pricingDuration+", items = "+items+", editionCode = "+editionCode+"]";
}
}
Thanks for your help!
Mike
Hm, this seems multi-faceted. Let's see if I can help at all. Last thing first...
No tables being created automatically.
I would take a look at this section in Spring's docs for the most basic approach: Initialize a database using Hibernate. For example, spring.jpa.hibernate.ddl-auto: create-drop will drop and re-create tables each time the application runs. Simple and easy for initial dev work. More robust would be leveraging something like Flyway or Liquibase.
Serialization issue
So without logs, and the fact that you have no tables created, the lack of a persistence layer would be the assumed culprit. That said, when you have tables and data, if you do not have a repository for all of the related tables, you'll end up with a StackOverflow error (the serialization becomes circular). For that, you can use #JsonBackReference (child) and #JsonManagedReference (parent). I have been successful using only #JsonBackReference for the child.
Items[]
I'm not sure what Item.class looks like, but that looks like an offensive configuration that I missed the first round.
Change private Items[] items; to private List<Item> items = new ArrayList<Item>();. Annotate with #ElementCollection.
Annotate Item.class with #Embeddable.

Bidirectional one to one mapping in GAE using JDO?

How can I implement a bidirectional one-to-one mapping using Google Application Engine (GAE) using Java Data Objects (JDO)?
I have a User class which holds contactInfo object and a ContactInfo class that holds a user object
#PersistenceCapable(identityType ="APPLICATION", detachable = "true")
public class User{
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
private String name;
#Persistent(dependent = "true")
private ContactInfo child;
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 ContactInfo getChild() {
return child;
}
public void setChild(ContactInfo child) {
this.child = child;
}
}
#PersistenceCapable(identityType ="APPLICATION", detachable = "true")
public class ContactInfo {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
#Persistent(mappedBy = "child")
private User parent;
private String contactDetail;
public Key getId() {
return id;
}
public void setId(Key id) {
this.id = id;
}
public String getContactDetail() {
return contactDetail;
}
public void setContactDetail(String contactDetail) {
this.contactDetail = contactDetail;
}
}
Following error i am getting while testing API from API explorer
com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.demo.jdo.ContactInfo[\"user\"]->com.demo.jdo.User[\"contactInfo\"]->com.demo.jdo.ContactInfo[\"user\"]-
Standard JDO 1-1 bidir is simply found from http://www.datanucleus.org/products/accessplatform_3_1/jdo/orm/one_to_one.html#bi
GAE ought to be no different in this respect; last time I used it (maybe 3 yrs ago) they had some tests, think those under here http://code.google.com/p/datanucleus-appengine/source/browse/#svn%2Ftrunk%2Ftests%2Fcom%2Fgoogle%2Fappengine%2Fdatanucleus
Your question provides no definition of what you have tried in terms of annotations
Got the Solution, problem was with wrong use of mappedBy & presence of getter and setter of parent object in child.
#Persistent(mappedBy = "") annotation should only be at non-owner side
In on-owner/ child side there should not be any getter/setter present for owner/parent object.
Working code:
User.java
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class User {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
private String name;
#Persistent(dependent = "true")
private ContactInfo contactInfo;
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 ContactInfo getContactInfo() {
return contactInfo;
}
public void setContactInfo(ContactInfo contactInfo) {
this.contactInfo = contactInfo;
}
}
ContactInfo.java
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class ContactInfo {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
#Persistent(mappedBy = "contactInfo")
/*
* Important: Do not create getter and setters for this object else
* bidirectional mapping gives error
*/
private User user;
private String contactDetail;
public Key getId() {
return id;
}
public void setId(Key id) {
this.id = id;
}
public String getContactDetail() {
return contactDetail;
}
public void setContactDetail(String contactDetail) {
this.contactDetail = contactDetail;
}
}

Apache Wicket : Getting Selected Dropdown Value from a table on UI

I have an object something like
public class Table {
private String id;
private String name;
private List<Field> fieldsList;
}
public class Field {
private List<Column> columnList;
}
public class Column{
String id;
}
So, Here my workflow is a Table consists of multiple Field's and a Field will have multiple Column's. so, on webUI i need to show a Table with name and Field Dropdown as rows. When user selects a field, then i need to dynamically get the selected field and the render the columns belonging to the selected field. Here, how to get the selected Fields from web UI. I tried with AjaxFormComponentUpdatingBehavior("onchange"). But i am getting all the fields of that dropdown.
My DropDown Choice is as follows :
IChoiceRenderer choiceRenderer = new ChoiceRenderer("Name", "id");
DropDownChoice dropDownChoice = new DropDownChoice("ddc");
dropDownChoice.setChoiceRenderer(choiceRenderer);
dropDownChoice.setChoices(table.getFieldsList());
dropDownChoice.setModel(new CompoundPropertyModel(new Field()));
dropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
//Following is returning all the List of Fields.
Object defaultModelObject = getModelObject();
}
});
How to handle such scenario. Please help...
See complete example below.
Main parts are ViewModel(VM) and ViewModelLoader(VML).
VM is what you want to display in the UI. VML fills VM with data from say database.
With PropertyModel I'm binding dropdown items and selected value.
To update doropdown I'm updating VM and adding component to the AjaxRequestTarget.
public class PlayingWithDropDownPage extends WebPage {
public PlayingWithDropDownPage() {
final ViewModelLoader viewModelLoader = new ViewModelLoader();
final ViewModel viewModel = viewModelLoader.load();
IChoiceRenderer choiceRenderer = new ChoiceRenderer("name", "id");
final DropDownChoice dropDownChoice = new DropDownChoice("dropDown");
dropDownChoice.setChoiceRenderer(choiceRenderer);
dropDownChoice.setChoices(viewModel.getItemsModel());
dropDownChoice.setModel(viewModel.getSelectedModel());
dropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
viewModelLoader.load(viewModel);
target.add(dropDownChoice);
}
});
add(dropDownChoice);
}
public static class ViewModel implements Serializable {
private WhatToShow whatToShow;
private List<Item> items = new ArrayList<>();
private Item selected;
public IModel<List<Item>> getItemsModel() {
return new PropertyModel<>(this, "items");
}
public IModel<Item> getSelectedModel() {
return new PropertyModel<>(this, "selected");
}
}
public static class ViewModelLoader extends LoadableDetachableModel<ViewModel> {
#Override
protected ViewModel load() {
return load(new ViewModel());
}
protected ViewModel load(ViewModel vm) {
vm.items.clear();
if (vm.whatToShow == WhatToShow.City) {
vm.whatToShow = WhatToShow.Person;
vm.items.add(new Person("1", "John", "Smith"));
vm.items.add(new Person("2", "Robert", "Evans"));
vm.items.add(new Person("3", "Jeff", "Jones"));
} else {
vm.whatToShow = WhatToShow.City;
vm.items.add(new City("1", "London"));
vm.items.add(new City("2", "Moscow"));
vm.items.add(new City("3", "Kiev"));
}
return vm;
}
}
public static interface Item {
public String getId();
public String getName();
}
private enum WhatToShow {
Person,
City
}
public static class City implements Item {
public String id;
public String name;
public City(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String getId() {
return id;
}
#Override
public String getName() {
return name;
}
}
public static class Person implements Item {
public String id;
public String fname;
public String lname;
public Person(String id, String fname, String lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
}
#Override
public String getId() {
return id;
}
#Override
public String getName() {
return String.format("%s %s", fname, lname);
}
}
}