Store data from one Class to Another - java

In this I have tried the Registration Form in Model View Control architecture. I am unable to Store the User Data In Another class. In that the Registration field Has to be stored in the Registration Database Class and Contact information has to be stored in the Contact Information Class.
Then how Should I frame Main method
public class RegistrationData {
private String username;
private String password;
private Contact contact;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public RegistrationData(String username, String password, Contact contact) {
this.username = username;
this.password = password;
this.contact = contact;
}
}
public class Contact {
private String name;
private String phoneNumber;
private String emailId;
public Contact(String name, String phoneNumber, String emailId) {
this.name = name;
this.phoneNumber = phoneNumber;
this.emailId = emailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
public class Registration {
Scanner scanner = new Scanner(System.in);
void Registration(RegistrationData registrationData,Contact contact){
System.out.println("Username : ");registrationData.setUsername(scanner.next());
System.out.println("Password : ");registrationData.setPassword(scanner.next());
System.out.println("Name : ");contact.setName(scanner.next());
System.out.println("PhoneNumber : ");contact.setPhoneNumber(scanner.next());
System.out.println("Email id :");contact.setEmailId(scanner.next());
}
}
//Data Base Class
import java.util.ArrayList;
import java.util.List;
public class RegistrationDatabase {
List<RegistrationData> registrationData = new ArrayList<>();
public void storeData(RegistrationData registrationData){
this.registrationData.add(registrationData);
System.out.println(this.registrationData);
}
}
import java.util.LinkedList;
import java.util.List;
public class ContactDatabase {
List<Contact> contacts = new LinkedList<>();
public void addContact(Contact contact){
this.contacts.add(contact);
}
}

Correct me If I am wrong in interpreting you question
Assumption 1 :
You want to Store registration data to RegistrationInformation table from Contact Information class as well as from RegistrationInformation class
Solution 1:
As I can see there is one to one relation between Contact and registration,so You can add a association in ContactInformation class as well as you have done in RegisterInformation class
public class Contact {
//one to one relation
private RegistrationData registrationData;
.
.
.
.
and use this to store registration from Contact
Assumption 2 :
You have seperate database for Contact and Registration
Solution 2:
In that case Create a POJO class for Registration form(same as RegistrationData,but will be used to capture data from view) and then create two classes RegistrationData and Contact class and then Use the POJO to retrieve and store the information in both the database.

Related

How do i override functions in a Vaadin 12 project? ValueProvider, SelectionListener and ComponentEventListener

This will be quite a bit of code as I don't know what will be important. I was trying to recreated the basic UI Alejandro made in my tutorial session with him a few months ago, substituting a table in my database for the one he used. The errors I'm getting all seem related to overriding Vaadin Flow functions. I know that replaces the behavior of the Super method. IntelliJ opens the relevant Super method when I click on the errors, which I'm assuming it wants me to edit to solve the problem, but I have no idea how to do that.
I was going to paste a link to the code but the forum told me to just place it here.
Customer.java
package com.dbproject.storeui;
import java.time.LocalDate;
public class Customer {
private Long id;
private String lastname;
private String firstname;
private String email;
private String password;
private String phone;
private String street;
private String city;
private String st;
private int zip;
private LocalDate dob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
}
CustomerRepository.java
package com.dbproject.storeui;
import org.apache.ibatis.annotations.*;
import java.util.List;
#Mapper
public interface CustomerMapper {
#Select("SELECT * FROM customer ORDER BY id")
List<Customer> findAll();
#Update("UPDATE customer" +
"SET lastname=#{lastname}, firstname=#{firstname}, email=#{email}, password=#{password}, phone=#{phone}, street=#{street}, city=#{city}, st=${st}, zip=#{zip}, dob=#{dob}" +
"WHERE id=#{id}")
void update(Customer customer);
#Insert("INSERT INTO customer(lastname, firstname, email, password, phone, street, city, st, zip, dob) VALUES(#{lastname}, #{firstname}, #{email}, #{password}, #{phone}, #{street}, #{city}, #{st}, #{zip}, #{dob})")
#Options(useGeneratedKeys = true, keyProperty = "id")
void create(Customer customer);
}
CustomerView.java (the UI class)
package com.dbproject.storeui;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
#Route("")
public class CustomerView extends Composite<VerticalLayout> {
private final CustomerMapper customerMapper;
private Grid<Customer> grid = new Grid<>();
private TextField lastname = new TextField("Last Name");
private TextField firstname = new TextField("First Name");
private Button save = new Button("Save", VaadinIcon.CHECK.create());
private Button create = new Button("New", VaadinIcon.PLUS.create());
private VerticalLayout form = new VerticalLayout(lastname, firstname, save);
private Binder<Customer> binder = new Binder<>(Customer.class);
private Customer customer;
public CustomerView(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
grid.addColumn(Customer::getLastname).setHeader("Last Name");
grid.addColumn(Customer::getFirstname).setHeader("First Name");
grid.addSelectionListener(event -> setCustomer(grid.asSingleSelect().getValue()));
updateGrid();
save.addClickListener(event -> saveClicked());
create.addClickListener(event -> createClicked());
getContent().add(grid, create, form);
binder.bindInstanceFields(this);
binder.setBean(null);
}
private void createClicked() {
grid.asSingleSelect().clear();
setCustomer(new Customer());
}
private void saveClicked() {
binder.readBean(customer);
if (customer.getId() == null) {
customerMapper.create(customer);
} else {
customerMapper.update(customer);
}
updateGrid();
Notification.show("Saved!");
}
private void setCustomer(Customer customer) {
this.customer = customer;
form.setEnabled(customer != null);
binder.setBean(customer);
}
private void updateGrid() {
grid.setItems(customerMapper.findAll());
}
}

Adding an entity to a table at Azure in Java

I'm trying to add an entity to a table at Azure but I'm getting many errors. Here is my code:
package table;
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.table.*;
import com.microsoft.azure.storage.table.TableQuery.*;
public class tableTutorial {
public static final String storageConnectionString=
"DefaultEndpointsProtocol=https;"+
"AccountName=my_storage_name;"+
"AccountKey=my_storage_account_key;"+
"EndpointSuffix=core.windows.net";
public static void main (String args[]) {
try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount =
CloudStorageAccount.parse(storageConnectionString);
// Create the table client.
CloudTableClient tableClient =
storageAccount.createCloudTableClient();
// Create a cloud table object for the table.
CloudTable cloudTable = tableClient.getTableReference("people");
// Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
customer1.setEmail("Walter#contoso.com");
customer1.setPhoneNumber("425-555-0101");
// Create an operation to add the new customer to the people table.
TableOperation insertCustomer1 =
TableOperation.insertOrReplace(customer1);
// Submit the operation to the table service.
cloudTable.execute(insertCustomer1);
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();
}
}
}
class CustomerEntity extends TableServiceEntity {
public CustomerEntity(String lastName, String firstName) {
this.partitionKey = lastName;
this.rowKey = firstName;
}
public CustomerEntity() {
String email;
String phoneNumber;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
The errors I'm getting are:
com.microsoft.azure.storage.StorageException: An attempt was made to access an inaccessible member of the entity during serialization.
at com.microsoft.azure.storage.table.TableServiceEntity.writeEntity(TableServiceEntity.java:468)
at com.microsoft.azure.storage.table.TableEntitySerializer.getPropertiesFromDictionary(TableEntitySerializer.java:213)
at com.microsoft.azure.storage.table.TableEntitySerializer.writeJsonEntity(TableEntitySerializer.java:129)
at com.microsoft.azure.storage.table.TableEntitySerializer.writeSingleEntityToStream(TableEntitySerializer.java:63)
at com.microsoft.azure.storage.table.TableOperation.insertImpl(TableOperation.java:381)
at com.microsoft.azure.storage.table.TableOperation.performInsert(TableOperation.java:362)
at com.microsoft.azure.storage.table.TableOperation.execute(TableOperation.java:682)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:529)
at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:496)
at table.tableTutorial.main(tableTutorial.java:86)
Caused by: java.lang.IllegalAccessException: class com.microsoft.azure.storage.table.PropertyPair cannot access a member of class table.CustomerEntity with modifiers "public"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Unknown Source)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at com.microsoft.azure.storage.table.PropertyPair.generateEntityProperty(PropertyPair.java:291)
at com.microsoft.azure.storage.table.TableServiceEntity.writeEntityWithReflection(TableServiceEntity.java:211)
at com.microsoft.azure.storage.table.TableServiceEntity.writeEntity(TableServiceEntity.java:465)
Caused by: java.lang.IllegalAccessException: class com.microsoft.azure.storage.table.PropertyPair cannot access a member of class table.CustomerEntity with modifiers "public"
To serialize your entity, your CustomerEntity should be public, so it should be defined in a separate file. Also note not to declare properties in constructor method.
Here's the code for you to refer.
package table;
import com.microsoft.azure.storage.table.TableServiceEntity;
public class CustomerEntity extends TableServiceEntity {
public CustomerEntity(String lastName, String firstName) {
this.partitionKey = lastName;
this.rowKey = firstName;
}
public CustomerEntity() { }
String email;
String phoneNumber;
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

verify if an email is already in my database, using hibernate

I need to verify the email of the new user who would like to sign up in my application web. if the email is already in my database (mysql) so must don't accept this sign up and said said to him like: "your email already used".
Now I can save users in my database, but how to check them by his email for not repeat the inscription in my application web.
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I created a table "user" in my database.
Maybe there is an annotation which can help us to specify the email property as an unique one or something else.
What you can do is create a unique key on your email column in your table. After that, decorate your field using #Column(unique=true), that will indicate to Hibernate that this field has a unique key.
Also, be careful with your annotations. This is unrelated to your problem, but #ManagedBean marks the class as a bean able to interact with the view in JSF. Probably you want/need to use #Entity instead.

check if an email in my database while sign up, using hibernate

I am programming an IHM for sign up the users, I need to check if this user is already in database(mysql), checking by his email . can you help me please.
I can save my user now but how to check if this user by his email
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I have a table user in my database.
thanks for your help in advance
I would use NamedQuery for this. Define named query in your User entity like this:
...
#NamedQueries({
#NamedQuery(name = "User.findByEmail",
query = "SELECT u FROM User u WHERE u.email = :email")})
#ManagedBean(name="user")
public class User {
...
And then add method like this to your DAO
public List<User> getUsersByEmail(String email){
openSession();
Session session;
Query query = session.getNamedQuery("User.findByEmail");
query.setString("email", email);
Lis<Users> users = query.list();
closeSession();
return users;
}
This method is little bit more generic you can make it more specific returning user count only.

Neo4J Spring relateTo function cannot be resolved

Given the following class:
package com.example.model;
import java.util.Collection;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
import org.springframework.data.neo4j.annotation.RelatedToVia;
import org.springframework.security.core.GrantedAuthority;
#NodeEntity
public class User {
private static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed
String login;
String name;
String password;
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return "";
// return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(elementClass = Rating.class, type = RATED)
Iterable<Rating> ratings;
#RelatedTo(elementClass = Movie.class, type = RATED)
Set<Movie> favorites;
#RelatedTo(elementClass = User.class, type = FRIEND, direction = Direction.BOTH)
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
}
I get a compilation exception here:
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
Following the tutorial here. Any insight as to where this function resides is appreciated.
You're trying to use the advanced mapping mode. See the reference manual for more information. You'll need to set up AspectJ support in your IDE. Methods are woven into your entity classes at compile time.

Categories

Resources