i am a newbie to java.I am trying to create a library system.
Which classes should be abstract? do i need more classes?
Yes you need many classes, Your classes should look like this :
class Person{
//attributes, getters and setters
}
class User extends Person{
//attributes, getters and setters
}
class Members extends Person{
}
class Librarian extends Person{
}
class Book{
//attributes, getters and setters
}
public class Person {
private String FirstName;
private String LastName;
private String Gender;
private String Contact;
private String Email;
public Person() {
}
public Person(String FirstName, String LastName, String Gender, String Contact, String Email) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Contact = Contact;
this.Email = Email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getGender() {
return Gender;
}
public void setGender(String Gender) {
this.Gender = Gender;
}
public String getContact() {
return Contact;
}
public void setContact(String Contact) {
this.Contact = Contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
}
public class User extends Person {
private String Password;
private String Username;
boolean isEnabled;
public User() {
}
public User(String Password, String Username, boolean isEnabled) {
this.Password = Password;
this.Username = Username;
this.isEnabled = isEnabled;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public boolean isIsEnabled() {
return isEnabled;
}
public void setIsEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
public class Guest extends User {
public Guest() {
}
public Guest(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
public void App(){
}
}
public class Members extends User{
public Members() {
}
public Members(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
}
public class Libararian extends User {
public Libararian() {
}
public Libararian(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
}
public class Book {
private String Title;
private String Publisher;
private String Category;
public Book(String Title, String Publisher, String Category) {
this.Title = Title;
this.Publisher = Publisher;
this.Category = Category;
}
public Book() {
}
public String getTitle() {
return Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String Publisher) {
this.Publisher = Publisher;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
}
Related
I want to create a POJO class with Constructor for the POST request body which has nested JSON, But I am not sure how to call JSONArray inside it?
PS: I do not want to set data using the setter method, I want to use Constructor for setting the data.
Here is the JSON:
{
"FirstName": "test",
"LastName": "account",
"PASSWORD": "Password123*",
"Email": [
{
"TYPE": "Primary",
"VALUE": "arpitay6#mail7.io"
}
]}
POJO I've created -
import java.util.List;
public class PostAccountCreateAPI {
private List <Email> email;
private String password;
private String firstname;
private String lastname;
public PostAccountCreateAPI(List<Email> email, String password, String firstname, String lastname) {
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Email> getEmail() {
return email;
}
public void setEmail(List<Email> email) {
this.email = email;
}
}
package pojo;
public class Email {
private String type;
private String value;
public Email(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
In the main method, I am calling POJO using -
PostAccountCreateAPI PostAccountCreateAPIPayLoad = new PostAccountCreateAPI("pri#mail7.io", "P#$$w0rd", "arpita", "garg");
But It is not working. Can anyone please suggest how to do this?
Ok....Here I am Giving a complete example:
The PostAccountCreateApi class:
import java.util.List;
public class PostAccountCreateAPI{
private String FirstName;
private String LastName;
private String PASSWORD;
private List<Email> Email;
public PostAccountCreateAPI(){}
public PostAccountCreateAPI(String FirstName, String LastName, String PASSWORD, List<Email> Email){
this.FirstName = FirstName;
this.LastName = LastName;
this.PASSWORD = PASSWORD;
this.Email = Email;
}
public void setFirstName(String FirstName){
this.FirstName = FirstName;
}
public String getFirstName(){
return this.FirstName;
}
public void setLastName(String LastName){
this.LastName = LastName;
}
public String getLastName(){
return this.LastName;
}
public void setPASSWORD(String PASSWORD){
this.PASSWORD = PASSWORD;
}
public String getPASSWORD(){
return this.PASSWORD;
}
public void setEmail(List<Email> Email){
this.Email = Email;
}
public List<Email> getEmail(){
return this.Email;
}
}
The Email Class:
public class Email {
String TYPE;
String VALUE;
public Email() {
}
public Email(String TYPE, String VALUE) {
this.TYPE = TYPE;
this.VALUE = VALUE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTYPE() {
return this.TYPE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
public String getVALUE() {
return this.VALUE;
}
}
The main class with a dummy main method:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Email> emailList = new ArrayList<>();
emailList.add(new Email("Primary", "pri#mail7.io"));
emailList.add(new Email("Primary", "amimulahsan7#gmail.com"));
//And list goes on......
PostAccountCreateAPI postAccountCreateAPI = new PostAccountCreateAPI("arpita", "garg",
"P#$$w0rd", emailList);
}
}
The first parameter to the constructor is List<Email>, but you are currently passing a String as the first argument to the constructor. Create a list of Email objects and then invoke the PostAccountCreateAPI constructor.
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 am having trouble understanding why my userRepository is returning null even when there is a record like it in my table. I tried doing it with my demo codes and it works but when I try doing it with user Authentication it does not work.
Security Services
#Path("/securityservice")
public class SecurityServices {
private UserRepository userRepo;
// http://localhost:8990/login/securityservice/security
#GET
#Path("security")
#Produces(MediaType.APPLICATION_JSON)
public Response getOrderById(#QueryParam("orderId") int orderID,
#HeaderParam("Authorization") String authString) throws JSONException {
JSONObject json = new JSONObject();
if (isUserAuthenticated(authString)) {
json.put("INFO", "Authorized User!");
return Response.status(200)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
} else {
json.put("ERROR", "Unauthorized User!");
return Response.status(403)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
}
}
private boolean isUserAuthenticated(String authString) {
//authString = Basic 3hfjdksiwoeriounf
String[] authParts = authString.split("\\s+");
//authParts[0] = Basic
//authParts[1] = 3hfjdksiwoeriounf
String authInfo = authParts[1];
byte[] bytes = Base64.getDecoder().decode(authInfo);
String decodedAuth = new String(bytes);
// decodedAuth = dj:1234
String[] credentials = decodedAuth.split(":");
//credentials[0]=dj
//credentials[1]=1234
System.out.println("HELLO"+credentials[0]);
System.out.println("HELLO"+credentials[1]);
User user = userRepo.findByUsername(credentials[0]); //this line returns null
if (user != null) {
return true;
} else {
return false;
}
}
User class (Getters and setters for the JPA Repo)
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String password;
private String username;
#Column(name="accesstype")
private String accessType;
public User() {
super();
}
public User(String firstName, String lastName, String password,
String username, String accessType) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.username = username;
this.accessType = accessType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
When I use Retrofit to call Login API, I face a little problem: the response body is null. And the the Response Message contains this message:
"Response{protocol=http/1.1, code=200, message=OK, url=http://gagron.com/api/login.php}"
class interface
public interface getLoginDataService {
public String BaseURL = Constants.mBase_Url;
#FormUrlEncoded
#POST(Constants.mLogin)
Call<UserModel> login(#Field("email") String email, #Field("password") String password);
}
Login Method
public void loginConnector(String email, String password) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Connectors.getLoginDataService.BaseURL)
.addConverterFactory(GsonConverterFactory.create(new Gson())).build();
Connectors.getLoginDataService getLoginDataService = retrofit.create(Connectors.getLoginDataService.class);
getLoginDataService.login(email, password).enqueue(new Callback<UserModel>() {
#Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
UserModel model= response.body();
Log.i("Successmsg", "" + response.toString());
Log.i("Successmsg1", "" + model.getFirstName());
;
}
#Override
public void onFailure(Call<UserModel> call, Throwable t) {
Log.i("Errormsg", t.getMessage() + "");
}
});
}
And finally user Model which consider the Response.
Class UserModel
public class UserModel {
#SerializedName("FirstName")
#Expose
private String firstName;
#SerializedName("LastName")
#Expose
private String lastName;
#SerializedName("Email")
#Expose
private String email;
#SerializedName("Mobile")
#Expose
private String mobile;
#SerializedName("Gender")
#Expose
private String gender;
#SerializedName("Password")
#Expose
private String password;
#SerializedName("Salt")
#Expose
private String salt;
#SerializedName("Address")
#Expose
private String address;
#SerializedName("PostalCode")
#Expose
private String postalCode;
#SerializedName("DateOfBirth")
#Expose
private String dateOfBirth;
#SerializedName("role")
#Expose
private String role;
#SerializedName("newsletter")
#Expose
private String newsletter;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getNewsletter() {
return newsletter;
}
public void setNewsletter(String newsletter) {
this.newsletter = newsletter;
}
}
In your loginConnector method you can use call.request().url() to display/debug the request URL you are calling.
Additionally you can use a REST client to make a POST request to that URL and check the difference between both responses. Nowadays Insomnia REST client is a good option for that.
I hope that may help you.
inside your onResponse add
if (response.isSuccessful()) {
if (response.body() != null) {UserModel model= response.body();
Log.i("Successmsg", "" + response.toString());
Log.i("Successmsg1", "" + model.getFirstName());
}
} else {
Toast.makeText(LoginSM.this, getString(R.string.wrongdata), Toast.LENGTH_SHORT).show();
}
I am using spring security to login and logout, eveything works fine.
I can get username from logged user fine, however i need userID,
I would like to know how can i get user as an object from logged in user or how could i get userID
#RequestMapping("/contato")
public String contato(Model model, Principal principal ){
String userName = principal.getName();
model.addAttribute("userName",userName);
System.out.println(userName);
return "contato";
}
Bean
import java.sql.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class Users {
private int user_id;
#NotBlank
#Size(min=1, max=100, message="Name must be between 1 and 100 characters")
private String firstname;
#NotBlank
private String surname;
#NotNull
private Date dob;
#NotBlank
#Email
private String username;
#NotBlank
private String telephone;
#NotBlank
private String address;
#NotBlank
private String city;
#NotBlank
private String country;
#NotBlank
private String postcode;
#NotBlank
#Size(min=6, message="Password must be have more than 6 characters")
private String password;
private boolean enabled = false;
private String authority;
public Users() {
}
public Users(int user_id, String firstname, String surname, Date dob, String username, String telephone,
String address, String city, String country, String postcode, String password, boolean enabled,
String authority) {
super();
this.user_id = user_id;
this.firstname = firstname;
this.surname = surname;
this.dob = dob;
this.username = username;
this.telephone = telephone;
this.address = address;
this.city = city;
this.country = country;
this.postcode = postcode;
this.password = password;
this.enabled = enabled;
this.authority = authority;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Can anyone please help me to get user id from logged user
I have also tried using
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Users user =(Users)authentication.getPrincipal();
but it still did not work
The simplest approach would be to leverage the UserDetails and UserDetailsService interfaces.
Write a simple UserDetailsService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return findUserByUsername(username); //load the user from somewhere (e.g. Database)
}
}
Have your Users class implement the UserDetails interface:
public class Users implements UserDetails {
private String username;
private String userId;
private String password;
private String role;
public Users(String username, String userId, String password, String role) {
this.username = username;
this.userId = userId;
this.password = password;
this.role = role;
}
//...
}
Finally, when you call this static method you'll receive the Users object from which you can extract the userId:
Users user = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();