Want to import image to mongo using springboot - mongodb

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);
}

Related

How to achieve MVVM + Live Data with retofit generic Api call in Android?

I want to create retrofit2 generic Api call in MVVM Architechture. I have not found any proper tutorial regardng this topic. I have done MVVM Architecture successfully . but I want to make Retrofit Api call generic through out the Application .Please help me out.
here is my code Repository
public class MainRepository {
// private List<ContactList> users = new ArrayList<>();
private MutableLiveData<ContactList> mutableLiveData = new MutableLiveData<>();
private Application application;
public MainRepository(Application application) {
this.application = application;
}
public MutableLiveData<ContactList> getMutableLiveData() {
Retrofit retrofit = ApiClient.getClient();
ApiListInterface apiListInterface = retrofit.create(ApiListInterface.class);
Call<ContactList> call = apiListInterface.getContacts();
call.enqueue(new Callback<ContactList>(){
#Override
public void onResponse(Call<ContactList> call, Response<ContactList> response) {
ContactList contactLists = response.body();
if (contactLists != null ) {
// users = (List<ContactList>) contactLists.ge;
mutableLiveData.setValue(contactLists);
}
}
#Override
public void onFailure(Call<ContactList> call, Throwable t) {
Log.d("ListSize"," - > Error "+ t.getMessage());
}
});
return mutableLiveData;
}
}
here is my ViewModel class
public class MainViewModel extends AndroidViewModel {
private MainRepository mainRepository;
public MainViewModel(#NonNull Application application) {
super(application);
mainRepository = new MainRepository(application);
}
public LiveData<ContactList> getAllUsers() {
return mainRepository.getMutableLiveData();
}
}
Here is My all Model class
public class ContactList {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = null;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
public class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("phone")
#Expose
private Phone phone;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
}
public class Phone {
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("home")
#Expose
private String home;
#SerializedName("office")
#Expose
private String office;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
}
Here is My Activity
public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
getUserList();
}
private void getUserList() {
mainViewModel.getAllUsers().observe(this, new Observer<ContactList>() {
#Override
public void onChanged(ContactList contactLists) {
Log.d("contacts_list",contactLists.getContacts().toString());
}
});
}
}

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.

Rest Client: Javax.ws.rs

i'm starting with Rest and don't have no idea how to implement it properly. I got an exercise: i must implement a Rest-Client with the RestClient-API from javax.ws.rs standard library and i tried by using the code below, but i'm getting a null pointer exception. But the resource are there and when i try directly from the browser (http://localhost:8080/sep/rest/customers/112). Now my question how can i do it properly. Some constraints, i must use XML (not JSON) for the Data-support.
Hier my client-code:
public Response createCustomer(Customer customer){
log.info("Starting: Rest Create a Customer with Name: " + Customer.class.getName());
this.customerWebTarget = this.client.target(URL);
Response response = this.customerWebTarget.request().
buildPost(Entity.entity(customer, MediaType.APPLICATION_XML)).invoke();
log.info("Ending: Rest Create a Customer with Name: " + response.getEntity().getClass().getName());
return response;
}
CustomerResource-Code:
#Path("customers")
public class CustomerResource implements IAllowedMethods<Customer> {
private static final long serialVersionUID = -6367055402693237329L;
private Logger logger = Logger.getLogger(CustomerResource.class.getName());
#Inject
private CustomerService service;
public CustomerResource() {
logger.info("create of instance " + this.getClass().getName());
}
#Override
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response get() {
List<Customer> list = service.loadAll(Customer.FINDALL, Customer.class);
if (list != null && !list.isEmpty()) {
ResponseCustomerList responseList = new ResponseCustomerList();
responseList.setList(list);
return Response.ok(responseList).build();
}
return Response.status(Status.NOT_FOUND).build();
}
.
.
.
Customer Code:
import de.ostfalia.sep.adapter.XMLIntegerAdapter;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private static final long serialVersionUID = 80668466040239995L;
#XmlID
#XmlJavaTypeAdapter(XMLIntegerAdapter.class)
private Integer customerNumber;
private String customerName;
private String contactLastName;
private String contactFirstName;
private String phone;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
#XmlIDREF
private Employee salesRepEmployee;
private BigDecimal creditLimit;
private Set<Payment> payments;
private Set<Order> orders;
public Customer() {
}
public Customer(Integer customernumber) {
this.customerNumber = customernumber;
}
public Customer(Integer customerNumber, String customerName, String contactLastName, String contactFirstName,
String phone, String addressLine1, String city, String country) {
this.customerNumber = customerNumber;
this.customerName = customerName;
this.contactLastName = contactLastName;
this.contactFirstName = contactFirstName;
this.phone = phone;
this.addressLine1 = addressLine1;
this.city = city;
this.country = country;
}
public Integer getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(Integer customerNumber) {
this.customerNumber = customerNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Employee getSalesRepEmployee() {
return salesRepEmployee;
}
public void setSalesRepEmployee(Employee salesRepEmployee) {
this.salesRepEmployee = salesRepEmployee;
}
public BigDecimal getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(BigDecimal creditLimit) {
this.creditLimit = creditLimit;
}
#Override
public int hashCode() {
int hash = 0;
hash += (customerNumber != null ? customerNumber.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerNumber == null && other.customerNumber != null)
|| (this.customerNumber != null && !this.customerNumber.equals(other.customerNumber))) {
return false;
}
return true;
}
#Override
public String toString() {
return customerNumber.toString();
}
public Set<Payment> getPayments() {
return payments;
}
public void setPayments(Set<Payment> payments) {
this.payments = payments;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
Instead of response.getEntity(), use response.readEntity(String.class) to get the data as a String. If you want to deserialize it to a POJO, then just pass that class to the readEntity.
Also you should make sure to check the status code (response.getStatus()) to make sure it's a success status.

JavaFX properties fail to persist

I'm using some JavaFX properties in my app:
#Entity(name = "Klanten")
#Table(name = "Klanten")
#NamedQueries({
#NamedQuery(name = "Klanten.findAll", query = "select k from Klanten k")
})
public class Klant implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int klantId;
#Transient
private final SimpleStringProperty naam = new SimpleStringProperty();
//private String naam;
//private String straat;
#Transient
private final SimpleStringProperty straat = new SimpleStringProperty();
private String telefoon;
private String huisnummer;
private String gsm;
private String woonplaats;
private String email;
private String postcode;
#OneToMany(mappedBy = "Klant", cascade = CascadeType.REMOVE)
private List<Raam> ramen;
public Klant() {
}
public Klant(String naam) {
this.naam.set(naam);
}
#Override
public String toString() {
return this.naam.get();
}
#Access(AccessType.PROPERTY)
#Column(name="naam")
public String getNaam() {
return this.naam.get();
}
public void setNaam(String naam){
this.naam.set(naam);
}
public List<Raam> getRamen() {
return this.ramen;
}
#Id
public int getKlantId() {
return klantId;
}
public void setKlantId(int klantId) {
this.klantId = klantId;
}
#Access(AccessType.PROPERTY)
#Column(name="straat")
public String getStraat() {
return straat.get();
}
public void setStraat(String straat) {
this.straat.set(straat);
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer(String huisnummer) {
this.huisnummer = huisnummer;
}
public String getGsm() {
return gsm;
}
public void setGsm(String gsm) {
this.gsm = gsm;
}
public String getWoonplaats() {
return woonplaats;
}
public void setWoonplaats(String woonplaats) {
this.woonplaats = woonplaats;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public StringProperty naamProperty() {
return naam;
}
public StringProperty straatProperty() {
return straat;
}
}
However when I let JPA generate my database, the column "naam" and "straat" aren't generated. I get no error. How can I resolve this?
I tried all the things listed here:
Possible solution 1
Possible solution 2
These didn't work.
You can try to use regular properties and then have another get method which returns a new SimpleStringProperty, i.e.:
public StringProperty naamProperty() {
return new SimpleStringProperty(naam);
}
public StringProperty straatProperty() {
return new SimpleStringProperty(straat);
}

dropdownchoice with choicerenderer, how to get values

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();