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;
}
}
Related
I am currently new to do website project with JSF specification. as you all know, JSF should include xhtml for the server page and managed bean to determine the class method, and I have made connection between my project and MySQL localhost.
The problem is, i created 1 main table for User categories which include common attributes such as name, gender etc. and i made other two table that specify the user for its role. The thing is that the main User table that contain user_ID as PRIMARY KEY to become the reference for the other 2 tables FOREIGN KEY ex: student, staff.
If i created a registration form on the server page, how should i determine the method to separate the data into the database from coming to the wrong table?
LoginBean.Java
private String fullName_;
private String gender_;
private String phoneNumber_;
private String IC_;
private String email_;
private String Address_;
private String password_;
public String getFullName_() {
return fullName_;
}
public void setFullName_(String fullName_) {
this.fullName_ = fullName_;
}
public String getGender_() {
return gender_;
}
public void setGender_(String gender_) {
this.gender_ = gender_;
}
public String getPhoneNumber_() {
return phoneNumber_;
}
public void setPhoneNumber_(String phoneNumber_) {
this.phoneNumber_ = phoneNumber_;
}
public String getIC_() {
return IC_;
}
public void setIC_(String IC_) {
this.IC_ = IC_;
}
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 getPassword_() {
return password_;
}
public void setPassword_(String password_) {
this.password_ = password_;
}
public String saveUser(LoginBean loginBean){
UserDao dao = new UserDao(); //METODE SIMPAN KE DATABASE!!!
User user = new User();
user.setFullName(loginBean.getFullName_());
user.setGender(loginBean.getGender_());
user.setPhoneNumber(Integer.parseInt(loginBean.getPhoneNumber_()));
user.setIc(loginBean.getIC_());
user.setEmail(loginBean.getEmail_());
user.setPassword(loginBean.getPassword_());
dao.saveStudent(user);//untuk menyimpan di database
Map<String,Object> sessionMapObj = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
sessionMapObj.put("msg", "Data "+user.getIc() +"successfull!");
return"/sukses.xhtml?faces-redirect=true";
}
User.java
private Integer userId;
private String fullName;
private String gender;
private Integer phoneNumber;
private String ic;
private String email;
private String address;
private String password;
private Set students = new HashSet(0);
private Set staffs = new HashSet(0);
public User() {
}
public User(String fullName, String gender, Integer phoneNumber, String ic, String email, String address, String password, Set students, Set staffs) {
this.fullName = fullName;
this.gender = gender;
this.phoneNumber = phoneNumber;
this.ic = ic;
this.email = email;
this.address = address;
this.password = password;
this.students = students;
this.staffs = staffs;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getIc() {
return this.ic;
}
public void setIc(String ic) {
this.ic = ic;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Set getStudents() {
return this.students;
}
public void setStudents(Set students) {
this.students = students;
}
public Set getStaffs() {
return this.staffs;
}
public void setStaffs(Set staffs) {
this.staffs = staffs;
}
I suppose you want to have a look at jdbc. Java Database Connectivity allows you to create sql queries in java. However, alot of times a Java Persistence API is used (JPA) in Java EE applications. This is a specification on how you can store and retrieve Java-Objects from a database. A very common implementation of that is the hibernate framework.
If you want to enable Hibernate capabilies for your jsf project, follow this guide:
https://howtodoinjava.com/hibernate/hibernate-3-introduction-and-writing-hello-world-application/. If your project isn't build with Maven, just ignore that part of the tutorial.
With hibernate for eg. you can create a User Entity. You can follow this easy tutorial on how to create entities: https://www.baeldung.com/jpa-entities
Now let's suppose you don't want to use any of that and just want a default solution with jdbc:
import java.sql.*;
public class Userdao
{
public static void saveUser(User user)
{
try
{
value1 = user.getId();
value2 = user.getFirstName();
value3 = user.getLastName();
String myUrl = "jdbc:somesql:localhost/test";
//now we load the driver
Class.forName("oracle.jdbc.driver.OracleDriver"); //download the correct driver of your database and add as library to your project
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String addUserQuery = "INSERT INTO table_name (column1, column2, column3, ...) VALUES (" + value1 + ", " + value2 + ", " + value3, + "...);" //column1 could be Userid-Primarykey, 2 Name ...
Statement addSt = conn.createStatement();
addSt.executeQuery(addUserQuery)
// create the java statement for retrieving
String query = "SELECT + from table_name";
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
int id = rs.getInt("id");
String firstName = rs.getString("first_name"); //first_name being the column name
String lastName = rs.getString("last_name");
// print the Name
System.out.format("%s, %s\n", id, firstName, lastName);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Foreign Key references are handled in the database, so for. eg. if you want to get the child objects you simply need a query that joins the tables, and then extract the corresponding values from the result set.
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.
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());
}
}
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.
This question already has answers here:
How to serialize object to CSV file?
(8 answers)
Closed 9 years ago.
what would be the best way to have information in a JavaBean be put into a CSV file? I am making a registration page and have set all the parameters of my User JavaBean through a JSP page using I need to store this information into a csv from a servlet everytime someone registers so I can retrieve this information when they use the login JSP page.
Here is my JavaBean
package bean.user;
public class User_profile {
private String First_Name;
private String Last_Name;
private String ssn;
private String birthday;
private String home_phone;
private String password;
private String gender;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getHome_phone() {
return home_phone;
}
public void setHome_phone(String home_phone) {
this.home_phone = home_phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
You can use introspection to retrieve all the properties of your bean with their corresponding read/write method then call them by reflection.
Here is an example with this simple class:
public class User {
private String login;
private String name;
private String surname;
private Integer age;
//Getters and setters
}
Now, I create a user and dump its properties in a String with comma separated values :
User u = new User();
u.setAge(18);
u.setLogin("myLogin");
u.setName("myName");
u.setSurname("mySurname");
for(PropertyDescriptor pd : Introspector.getBeanInfo(User.class).getPropertyDescriptors()){
//I don't want to get the "class" property
if(!pd.getName().equals("class")){
Method readMethod = pd.getReadMethod();
System.out.print(readMethod.invoke(u)+",");
}
}
Output :
18,myLogin,myName,mySurname,
Note: For the simplicity of this example, I did not suppress the ',' at the end of the output and did not handle case when properties contain character ','.
Use jsefa if you really really want CSV but this is better suited to store the details in some sort or repository/DB.
You can use this library http://jexcelapi.sourceforge.net/ or any such library which can help you convert your java objects in CSV form. One more for you http://kasparov.skife.org/csv/