authentification with jsf and postgresql - postgresql

i try to do authentification with jsf and postgres database.
my class conect.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class connect {
private boolean connected;
private String pass;
private String user;
private String message;
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String check()
{
Connection c = null;
Statement stmt = null;
try {
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/login", "postgres", "1234");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM users;" );
while ( rs.next() ) {
int iduser = rs.getInt("iduser");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println( "ID = " + iduser );
System.out.println( "USERNAME = " + username );
System.out.println( "PASSWORD = " + password );
if(user.equals(username) &&(pass.equals(password))){
message="admin";
}
else message="error";
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
}
System.out.println("Operation done successfully");
return message;
}
public connect() {
}
public static void main( String args[] ){
connect c= new connect();
c.check();
}
}
The program recovers well information from the database, the problem is that this program takes into account just the latest username and password of the "users" table. Can someone tell me where is the problem

Related

Grid not updating after entity attributes are changed

In my project, I have "Events" and "Users". Users sign up for events. Anyways the Events entity has a "participants" attribute which is an int that is the total capacity of the event, that is supposed to decrement every time a User signs up for the Event. Each Event also has an ArrayList attribute called "registrants" that is supposed to contain all the current User entities that have signed up for the Event.
My issue is that when a User signs up for an Event, this capacity attribute "participants" does not decrease at all like it is supposed to, which I suspect means the ArrayList "registrants" is also not be updated with the User that signs up. I re-check the EventManagementView after using a User to sign up for an event to see if the capacity is ever dropped from its initial set value, but it never is. Here's all the code that is directly used with this issue:
Events.java class for Events entity:
package ymca.tracker.application.data.entity;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import ymca.tracker.application.data.AbstractEntity;
#Embeddable
#Entity
public class Events extends AbstractEntity{
private String name;
private java.time.LocalDate startDate;
private java.time.LocalDate endDate;
private java.time.LocalTime startTime;
private java.time.LocalTime endTime;
private String recurring;
// The capacity attribute I was referring to above
public int participants;
private String nonMemberPrice;
private String memberPrice;
private String location;
private String description;
// Registrants ArrayList that is supposed to hold all the User entities that sign up for an event
#ElementCollection
#OneToMany(fetch = FetchType.EAGER)
public List<User> registrants = new ArrayList<User>();
public Events() {
}
public Events(String name, LocalDate startDate, LocalDate endDate, LocalTime startTime, LocalTime endTime,
String recurring, int participants, String nonMemberPrice, String memberPrice, String location,
String description, ArrayList<User> registrants) {
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.startTime = startTime;
this.endTime = endTime;
this.recurring = recurring;
this.participants = participants;
this.nonMemberPrice = nonMemberPrice;
this.memberPrice = memberPrice;
this.location = location;
this.description = description;
this.registrants = registrants;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.time.LocalDate getStartDate() {
return startDate;
}
public void setStartDate(java.time.LocalDate startDate) {
this.startDate = startDate;
}
public java.time.LocalDate getEndDate() {
return endDate;
}
public void setEndDate(java.time.LocalDate endDate) {
this.endDate = endDate;
}
public java.time.LocalTime getStartTime() {
return startTime;
}
public void setStartTime(java.time.LocalTime startTime) {
this.startTime = startTime;
}
public java.time.LocalTime getEndTime() {
return endTime;
}
public void setEndTime(java.time.LocalTime endTime) {
this.endTime = endTime;
}
public String getRecurring() {
return recurring;
}
public void setRecurring(String recurring) {
this.recurring = recurring;
}
public int getParticipants() {
return participants;
}
public void setParticipants(int participants) {
this.participants = participants;
}
// This method is called (only with value 1 for now) to decrease participants count
public void decreaseCapacity(int numToDecreaseBy) {
this.participants = this.participants - numToDecreaseBy;
}
public String getMemberPrice() {
return memberPrice;
}
public void setMemberPrice(String memberPrice) {
this.memberPrice = memberPrice;
}
public String getNonMemberPrice() {
return nonMemberPrice;
}
public void setNonMemberPrice(String nonMemberPrice) {
this.nonMemberPrice = nonMemberPrice;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<User> getRegistrants() {
return registrants;
}
public void setGuests(ArrayList<User> registrants) {
this.registrants = registrants;
}
// This method is called to add a User to the registrants ArrayList
public void addRegistrant(User user) {
this.registrants.add(user);
}
public void removeRegistrant(User user) {
this.registrants.remove(user);
}
}
User.java class for User entity:
package ymca.tracker.application.data.entity;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import ymca.tracker.application.data.AbstractEntity;
#Embeddable
#Entity
public class User extends AbstractEntity {
private boolean familyAccount;
private String firstName;
private String lastName;
private String username;
private String password;
private String passwordSalt;
private String passwordHash;
private ymca.tracker.application.data.entity.Role role;
public User() {
}
public User(boolean familyAccount, String firstName, String lastName,
String username, String password, ymca.tracker.application.data.entity.Role role) {
this.familyAccount = familyAccount;
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.role = role;
this.password = password;
this.passwordSalt = RandomStringUtils.random(32);
this.passwordHash = DigestUtils.sha1Hex(password + passwordSalt);
}
public boolean checkPassword(String password) {
return DigestUtils.sha1Hex(password + passwordSalt).equals(passwordHash);
}
public boolean getFamilyAccount() {
return familyAccount;
}
public void setFamilyAccount(boolean familyAccount) {
this.familyAccount = familyAccount;
}
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 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 String getPasswordSalt() {
return passwordSalt;
}
public void setPasswordSalt(String passwordSalt) {
this.passwordSalt = passwordSalt;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public ymca.tracker.application.data.entity.Role getRole() {
return role;
}
public void setRole(ymca.tracker.application.data.entity.Role role) {
this.role = role;
}
}
My Staff/Admin account uses this EventManagementView below to initially create the event:
package ymca.tracker.application.views.eventmanagement;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dependency.Uses;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.timepicker.TimePicker;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.data.VaadinSpringDataHelpers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import ymca.tracker.application.data.entity.Events;
import ymca.tracker.application.data.entity.User;
import ymca.tracker.application.data.service.EventsService;
#PageTitle("Event Management")
#Route(value = "event-management")
#Uses(Icon.class)
public class EventManagementView extends Div implements BeforeEnterObserver {
private final String EVENTS_ID = "eventsID";
private final String EVENTS_EDIT_ROUTE_TEMPLATE = "event-management/%s/edit";
private Grid<Events> grid = new Grid<>(Events.class, false);
private TextField name;
private DatePicker startDate;
private DatePicker endDate;
private TimePicker startTime;
private TimePicker endTime;
private TextField recurring;
private IntegerField participants;
private TextField nonMemberPrice;
private TextField memberPrice;
private TextField location;
private TextField description;
private Button delete = new Button("Delete");
private Button cancel = new Button("Cancel");
private Button save = new Button("Save");
private BeanValidationBinder<Events> binder;
private Events events;
private EventsService eventsService;
public EventManagementView(#Autowired EventsService eventsService) {
this.eventsService = eventsService;
addClassNames("event-management-view", "flex", "flex-col", "h-full");
// Create UI
SplitLayout splitLayout = new SplitLayout();
splitLayout.setSizeFull();
createGridLayout(splitLayout);
createEditorLayout(splitLayout);
add(splitLayout);
// Configure Grid
grid.addColumn("name").setAutoWidth(true);
grid.addColumn("startDate").setAutoWidth(true);
grid.addColumn("endDate").setAutoWidth(true);
grid.addColumn("startTime").setAutoWidth(true);
grid.addColumn("endTime").setAutoWidth(true);
grid.addColumn("recurring").setAutoWidth(true);
grid.addColumn("participants").setAutoWidth(true);
grid.addColumn("nonMemberPrice").setAutoWidth(true);
grid.addColumn("memberPrice").setAutoWidth(true);
grid.addColumn("location").setAutoWidth(true);
grid.addColumn("description").setAutoWidth(true);
grid.setItems(query -> eventsService.list(
PageRequest.of(query.getPage(), query.getPageSize(), VaadinSpringDataHelpers.toSpringDataSort(query)))
.stream());
grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);
grid.setHeightFull();
// when a row is selected or deselected, populate form
grid.asSingleSelect().addValueChangeListener(event -> {
if (event.getValue() != null) {
UI.getCurrent().navigate(String.format(EVENTS_EDIT_ROUTE_TEMPLATE, event.getValue().getId()));
} else {
clearForm();
UI.getCurrent().navigate(EventManagementView.class);
}
});
// Configure Form
binder = new BeanValidationBinder<>(Events.class);
// Bind fields. This is where you'd define e.g. validation rules
binder.bindInstanceFields(this);
delete.addClickListener(e -> {
binder.removeBean();
eventsService.delete(this.events.getId());
eventsService.update(this.events);
clearForm();
refreshGrid();
Notification.show("Event deleted");
UI.getCurrent().navigate(EventManagementView.class);
});
cancel.addClickListener(e -> {
clearForm();
refreshGrid();
});
save.addClickListener(e -> {
try {
if (this.events == null) {
this.events = new Events();
}
/*
Since the ArrayList isn't set by the grid editor, I hardcoded an
empty ArrayList to go with the new Event here
*/
ArrayList<User> registrants = new ArrayList<User>();
this.events.setGuests(registrants);
binder.writeBean(this.events);
eventsService.update(this.events);
clearForm();
refreshGrid();
Notification.show("Event details saved.");
UI.getCurrent().navigate(EventManagementView.class);
} catch (ValidationException validationException) {
Notification.show("An exception happened while trying to save the event details.");
}
});
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
Optional<UUID> eventsId = event.getRouteParameters().get(EVENTS_ID).map(UUID::fromString);
if (eventsId.isPresent()) {
Optional<Events> eventsFromBackend = eventsService.get(eventsId.get());
if (eventsFromBackend.isPresent()) {
populateForm(eventsFromBackend.get());
} else {
Notification.show(
String.format("The requested event was not found, ID = %s", eventsId.get()), 3000,
Notification.Position.BOTTOM_START);
// when a row is selected but the data is no longer available,
// refresh grid
refreshGrid();
event.forwardTo(EventManagementView.class);
}
}
}
private void createEditorLayout(SplitLayout splitLayout) {
Div editorLayoutDiv = new Div();
editorLayoutDiv.setClassName("flex flex-col");
editorLayoutDiv.setWidth("400px");
Div editorDiv = new Div();
editorDiv.setClassName("p-l flex-grow");
editorLayoutDiv.add(editorDiv);
FormLayout formLayout = new FormLayout();
name = new TextField("Event Name");
startDate = new DatePicker("Start Date");
endDate = new DatePicker("End Date");
startTime = new TimePicker("Start Time");
startTime.setStep(Duration.ofMinutes(10));
endTime = new TimePicker("End Time");
endTime.setStep(Duration.ofMinutes(10));
recurring = new TextField("Recurring Event?");
participants = new IntegerField("Number of Participants");
nonMemberPrice = new TextField("Non-Member Price");
memberPrice = new TextField("Member Price");
location = new TextField("Location");
description = new TextField("Description");
Component[] fields = new Component[]{name, startDate, endDate, startTime, endTime, recurring, participants, nonMemberPrice, memberPrice, location, description};
for (Component field : fields) {
((HasStyle) field).addClassName("full-width");
}
formLayout.add(fields);
editorDiv.add(formLayout);
createButtonLayout(editorLayoutDiv);
splitLayout.addToSecondary(editorLayoutDiv);
}
private void createButtonLayout(Div editorLayoutDiv) {
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setClassName("w-full flex-wrap bg-contrast-5 py-s px-l");
buttonLayout.setSpacing(true);
cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
buttonLayout.add(save, cancel, delete);
editorLayoutDiv.add(buttonLayout);
}
private void createGridLayout(SplitLayout splitLayout) {
Div wrapper = new Div();
wrapper.setId("grid-wrapper");
wrapper.setWidthFull();
splitLayout.addToPrimary(wrapper);
wrapper.add(grid);
}
private void refreshGrid() {
grid.select(null);
grid.getLazyDataView().refreshAll();
}
private void clearForm() {
populateForm(null);
}
private void populateForm(Events value) {
this.events = value;
binder.readBean(this.events);
}
}
The portion of code that handles event sign up for a User (If you'd prefer to see the whole class for this view instead of just this method please let me know):
private VerticalLayout createSignUpFormLayout(Dialog signUpForm) {
signUpForm.getElement().setAttribute("aria-label", "Registration Form");
TextField firstName = new TextField("First Name");
TextField lastName = new TextField("Last Name");
H2 headline = new H2("Registration Form");
headline.getStyle().set("margin-top", "0");
Button cancel = new Button("Cancel", e -> signUpForm.close());
Button submit = new Button("Submit", e -> {
if(fillChecker(firstName.getValue(), lastName.getValue()) == true) {
String fn = firstName.getValue();
String ln = lastName.getValue();
User guest = new User(false, fn, ln,
"null", "null", Role.GUEST);
Set<Events> selected = grid.getSelectedItems();
Events[] curEvent = selected.toArray(new Events[1]);
Events selectedEvent = curEvent[0];
if(selectedEvent == null) {
Notification.show("No Event Selected!", 5000, Position.TOP_CENTER);
} else {
userRepository.save(guest); // Saves guest sign-up info to user repository
selectedEvent.addRegistrant(guest);; // Adds guest sign-up info to events guest list
selectedEvent.decreaseCapacity(1); // Decrease events participants count by 1
signUpForm.close();
Notification.show("Registered 1 Guest", 5000, Position.TOP_CENTER);
}
} else {
Notification.show("Please complete the form to register", 5000, Position.TOP_CENTER);
}
});

JPA Repository save method creates new instance instead of merging

In my project there are events that users sign up for. When a user signs up for an event, the events capacity decreases by 1 and the users name is added to a String attribute for the event. After these changes are made to the event in my code, I call eventsRepository.save(event), which I thought just merges the newly updated event, but for some reason my database is just creating a whole new event with a new ID with the new values.
Here are some pictures of the issue:
The event data before a user signs up (UUID in repository included)
The event data after a user signs up
Code for a User:
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import ymca.tracker.application.data.AbstractEntity;
#Embeddable
#Entity
public class User extends AbstractEntity {
private boolean familyAccount;
private String firstName;
private String lastName;
private String username;
private String password;
private String passwordSalt;
private String passwordHash;
private ymca.tracker.application.data.entity.Role role;
public User() {
}
public User(boolean familyAccount, String firstName, String lastName,
String username, String password, ymca.tracker.application.data.entity.Role role) {
this.familyAccount = familyAccount;
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.role = role;
this.password = password;
this.passwordSalt = RandomStringUtils.random(32);
this.passwordHash = DigestUtils.sha1Hex(password + passwordSalt);
}
public boolean checkPassword(String password) {
return DigestUtils.sha1Hex(password + passwordSalt).equals(passwordHash);
}
public boolean getFamilyAccount() {
return familyAccount;
}
public void setFamilyAccount(boolean familyAccount) {
this.familyAccount = familyAccount;
}
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 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 String getPasswordSalt() {
return passwordSalt;
}
public void setPasswordSalt(String passwordSalt) {
this.passwordSalt = passwordSalt;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public ymca.tracker.application.data.entity.Role getRole() {
return role;
}
public void setRole(ymca.tracker.application.data.entity.Role role) {
this.role = role;
}
}
Code for an Events:
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import ymca.tracker.application.data.AbstractEntity;
#Embeddable
#Entity
public class Events extends AbstractEntity {
private String name;
private java.time.LocalDate startDate;
private java.time.LocalDate endDate;
private java.time.LocalTime startTime;
private java.time.LocalTime endTime;
private String recurring;
private int participants;
private String nonMemberPrice;
private String memberPrice;
private String location;
private String description;
private String users;
// Not currently used
#ElementCollection
#OneToMany(fetch = FetchType.LAZY)
private List<User> registrants = new ArrayList<User>();
public Events() {
}
public Events(String name, LocalDate startDate, LocalDate endDate, LocalTime startTime, LocalTime endTime,
String recurring, int participants, String nonMemberPrice, String memberPrice, String location,
String description, String users, List<User> registrants) {
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.startTime = startTime;
this.endTime = endTime;
this.recurring = recurring;
this.participants = participants;
this.nonMemberPrice = nonMemberPrice;
this.memberPrice = memberPrice;
this.location = location;
this.description = description;
this.users = " ";
this.registrants = registrants;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.time.LocalDate getStartDate() {
return startDate;
}
public void setStartDate(java.time.LocalDate startDate) {
this.startDate = startDate;
}
public java.time.LocalDate getEndDate() {
return endDate;
}
public void setEndDate(java.time.LocalDate endDate) {
this.endDate = endDate;
}
public java.time.LocalTime getStartTime() {
return startTime;
}
public void setStartTime(java.time.LocalTime startTime) {
this.startTime = startTime;
}
public java.time.LocalTime getEndTime() {
return endTime;
}
public void setEndTime(java.time.LocalTime endTime) {
this.endTime = endTime;
}
public String getRecurring() {
return recurring;
}
public void setRecurring(String recurring) {
this.recurring = recurring;
}
public int getParticipants() {
return participants;
}
public void setParticipants(int participants) {
this.participants = participants;
}
public void decreaseCapacity(int numToDecreaseBy) {
this.participants = this.participants - numToDecreaseBy;
}
public String getMemberPrice() {
return memberPrice;
}
public void setMemberPrice(String memberPrice) {
this.memberPrice = memberPrice;
}
public String getNonMemberPrice() {
return nonMemberPrice;
}
public void setNonMemberPrice(String nonMemberPrice) {
this.nonMemberPrice = nonMemberPrice;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsers() {
return users;
}
public void setUsers(String users) {
this.users = users;
}
public void addUser(String user) {
this.users = this.users + user + "\n";
}
public List<User> getRegistrants() {
return registrants;
}
public void setGuests(ArrayList<User> registrants) {
this.registrants = registrants;
}
public void addRegistrant(User user) {
this.registrants.add(user);
}
public void removeRegistrant(User user) {
this.registrants.remove(user);
}
public boolean checkRegistrant(User user) {
return this.registrants.contains(user);
}
}
Code for Guest Users to sign up located in this View (save call is marked with comment) (updated with id column code):
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.Grid.SelectionMode;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.grid.dataview.GridListDataView;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.Notification.Position;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.orderedlayout.FlexComponent.Alignment;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import ymca.tracker.application.data.entity.Events;
import ymca.tracker.application.data.entity.Role;
import ymca.tracker.application.data.entity.User;
import ymca.tracker.application.data.service.EventsRepository;
import ymca.tracker.application.data.service.EventsService;
import ymca.tracker.application.data.service.UserRepository;
import ymca.tracker.application.views.MainLayout;
#PageTitle("Guest Events")
#Route(value = "guest-events", layout = MainLayout.class)
public class GuestEventsView extends Div {
private EventsService eventsService;
private EventsRepository eventsRepository;
private UserRepository userRepository;
private Grid<Events> grid;
private GridListDataView<Events> gridListDataView;
private Grid.Column<Events> idColumn;
private Grid.Column<Events> signUpColumn;
private Grid.Column<Events> nameColumn;
private Grid.Column<Events> startDateColumn;
private Grid.Column<Events> endDateColumn;
private Grid.Column<Events> startTimeColumn;
private Grid.Column<Events> endTimeColumn;
private Grid.Column<Events> recurringColumn;
private Grid.Column<Events> participantsColumn;
private Grid.Column<Events> priceColumn;
private Grid.Column<Events> locationColumn;
private Grid.Column<Events> descriptionColumn;
public GuestEventsView(EventsService eventsService, EventsRepository eventsRepository, UserRepository userRepository) {
this.eventsService = eventsService;
this.eventsRepository = eventsRepository;
this.userRepository = userRepository;
addClassName("guest-events-view");
setSizeFull();
Button signUpButton = createSignUpButton();
add(signUpButton);
createGrid();
add(grid);
}
private void createGrid() {
createGridComponent();
addColumnsToGrid();
}
private void createGridComponent() {
grid = new Grid<>();
grid.setSelectionMode(SelectionMode.SINGLE);
grid.addThemeVariants(GridVariant.LUMO_NO_BORDER, GridVariant.LUMO_COLUMN_BORDERS);
grid.setHeight("100%");
List<Events> events = getEvents();
gridListDataView = grid.setItems(events);
}
private void addColumnsToGrid() {
createIdColumn();
createNameColumn();
createStartDateColumn();
createEndDateColumn();
createStartTimeColumn();
createEndTimeColumn();
createRecurringColumn();
createParticipantsColumn();
createPriceColumn();
createLocationColumn();
createDescriptionColumn();
}
private Button createSignUpButton() {
// Create the Dialog object which will be the signUpForm
Dialog signUpForm = new Dialog();
// Create the layout for the signUpForm, passing in the Dialog and selected Event
VerticalLayout signUpFormLayout = createSignUpFormLayout(signUpForm);
// Add the created layout to the signUpForm
signUpForm.add(signUpFormLayout);
// Only the signUpForm can be interacted with when it appears on the screen
signUpForm.setModal(true);
Button signUpButton = new Button("Sign Up");
signUpButton.addClickListener(e -> signUpForm.open());
return signUpButton;
}
private VerticalLayout createSignUpFormLayout(Dialog signUpForm) {
signUpForm.getElement().setAttribute("aria-label", "Registration Form");
TextField firstName = new TextField("First Name");
TextField lastName = new TextField("Last Name");
H2 headline = new H2("Registration Form");
headline.getStyle().set("margin-top", "0");
Button cancel = new Button("Cancel", e -> signUpForm.close());
Button submit = new Button("Submit", e -> {
if(fillChecker(firstName.getValue(), lastName.getValue()) == true) {
String fn = firstName.getValue();
String ln = lastName.getValue();
User guest = new User(false, fn, ln,
"null", "null", Role.GUEST);
Set<Events> selected = grid.getSelectedItems();
Events[] curEvent = selected.toArray(new Events[1]);
Events selectedEvent = curEvent[0];
if(selectedEvent == null) {
Notification.show("No Event Selected!", 5000, Position.TOP_CENTER);
} else {
userRepository.save(guest); // Saves guest sign-up info to user repository
selectedEvent.addUser(fn + " " + ln);
selectedEvent.decreaseCapacity(1); // Decrease events participants count by 1
// ISSUE HERE
// Currently saves new version of event instead of merging
UUID toDelete = selectedEvent.getId();
eventsRepository.save(selectedEvent);
eventsRepository.deleteById(toDelete);
signUpForm.close();
Notification.show("Registered 1 Guest", 5000, Position.TOP_CENTER);
}
} else {
Notification.show("Please complete the form to register", 5000, Position.TOP_CENTER);
}
});
submit.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
HorizontalLayout buttonLayout = new HorizontalLayout(cancel, submit);
buttonLayout.setAlignItems(Alignment.END);
buttonLayout.getStyle().set("margin-top", "var(--lumo-space-m");
VerticalLayout signUpFormLayout = new VerticalLayout(headline, firstName, lastName, buttonLayout);
signUpFormLayout.setPadding(false);
signUpFormLayout.setSpacing(false);
signUpFormLayout.setAlignItems(Alignment.STRETCH);
signUpFormLayout.getStyle().set("width", "18rem").set("max-width", "100%");
return signUpFormLayout;
}
private boolean fillChecker(String firstName, String lastName) {
if(firstName.equals("") || lastName.equals("")) {
return false;
}
return true;
}
private void createIdColumn() {
idColumn = grid.addColumn(Events::getId, "id").setHeader("ID").setAutoWidth(true);
}
private void createNameColumn() {
nameColumn = grid.addColumn(Events::getName, "name").setHeader("Name").setAutoWidth(true);
}
private void createStartDateColumn() {
startDateColumn = grid.addColumn(Events::getStartDate, "startDate").setHeader("Start Date").setAutoWidth(true);
}
private void createEndDateColumn() {
startDateColumn = grid.addColumn(Events::getEndDate, "endDate").setHeader("End Date").setAutoWidth(true);
}
private void createStartTimeColumn() {
startTimeColumn = grid.addColumn(Events::getStartTime, "startTime").setHeader("Start Time").setAutoWidth(true);
}
private void createEndTimeColumn() {
startDateColumn = grid.addColumn(Events::getEndTime, "endTime").setHeader("End Time").setAutoWidth(true);
}
private void createRecurringColumn() {
recurringColumn = grid.addColumn(Events::getRecurring, "recurring").setHeader("Recurring?").setAutoWidth(true);
}
private void createParticipantsColumn() {
participantsColumn = grid.addColumn(Events::getParticipants, "participants").setHeader("Capacity").setAutoWidth(true);
}
private void createPriceColumn() {
priceColumn = grid.addColumn(Events::getNonMemberPrice, "price").setHeader("Price").setAutoWidth(true);
}
private void createLocationColumn() {
locationColumn = grid.addColumn(Events::getLocation, "location").setHeader("Location").setAutoWidth(true);
}
private void createDescriptionColumn() {
descriptionColumn = grid.addColumn(Events::getDescription, "description").setHeader("Description").setAutoWidth(true);
}
private List<Events> getEvents() {
List<Events> list = eventsService.findAllEvents();
List<Events> toReturn = new ArrayList<Events>();
Events e;
int size = list.size();
for(int i = 0; i < size; i++) {
Events temp = list.get(i);
e = createEvents(temp.getName(), temp.getStartDate(), temp.getEndDate(), temp.getStartTime(), temp.getEndTime(),
temp.getRecurring(), temp.getParticipants(), temp.getNonMemberPrice(), temp.getLocation(), temp.getDescription());
toReturn.add(e);
}
return toReturn;
}
private Events createEvents(String name, java.time.LocalDate startDate, java.time.LocalDate endDate,
java.time.LocalTime startTime, java.time.LocalTime endTime, String recurring, int participants,
String price, String location, String description) {
Events e = new Events();
e.setName(name);
e.setStartDate(startDate);
e.setEndDate(endDate);
e.setStartTime(startTime);
e.setEndTime(endTime);
e.setRecurring(recurring);
e.setParticipants(participants);
e.setNonMemberPrice(price);
e.setLocation(location);
e.setDescription(description);
return e;
}
};
Here is my AbstractEntity class:
import java.util.UUID;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public abstract class AbstractEntity {
#Id
#GeneratedValue
private UUID id;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#Override
public int hashCode() {
if (id != null) {
return id.hashCode();
}
return super.hashCode();
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof AbstractEntity)) {
return false; // null or other class
}
AbstractEntity other = (AbstractEntity) obj;
if (id != null) {
return id.equals(other.id);
}
return super.equals(other);
}
}
Results of adding an Id Column to the sign up grid:
What does AbstractEntity contain? I'm guessing that your are missing the #Id annotation on your unique identifier for events, or that it is not mapped and goes missing before the entity is saved to the database. Without the id JPA has no way of knowing that this is an updated entity instead of a new one.
Debug the code and check that the entity contains the right ID at this line:
eventsRepository.save(selectedEvent)

sqlitedatabase update where clauses

i am getting a string category and address name from other class
what i need is to update categories table with specific address_id which is foreign key to address table. and address table contains a address_name.
So I am getting address_name from other class and i want to update categories table which specific address_id with given address_name and change its categories name to string category.
this is code that i have tried but it did not work, it does not gives error in android studio but it does not actually updates in the database.
public void updateData(String categories, String positionName){
ContentValues contentValues = new ContentValues();
contentValues.put("categories_name", categories);
Log.d(TAG, "updateData: " + categories );
database.update("categories", contentValues, "address_id = ?", new String[]{"(SELECT address_id FROM address WHERE address_name = " + positionName + ")"});
this is my address table
CREATE TABLE "address" (
"address_id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"address_name" TEXT UNIQUE,
"lat" BLOB NOT NULL,
"lng" BLOB NOT NULL,
"date" NUMERIC);
and this is my categories table
CREATE TABLE "categories" (
"Categories_id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"categories_name" TEXT NOT NULL DEFAULT 'place' CHECK(categories_name in ('place','home','work')),
"address_id" INTEGER NOT NULL UNIQUE,
FOREIGN KEY("address_id") REFERENCES "address"("address_id"));
public class EditProfile extends AppCompatActivity {
Button searchBtn;
EditText userName_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup genderRadioGroup;
RadioButton genderRadioBtn;
Button editBtn;
Button deleteBtn;
Intent intent;
DBHandler dbHandler;
public static final String USERID_EDITPROFILE = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
userName_editText = (EditText)findViewById(R.id.editprof_userName);
password_editText = (EditText)findViewById(R.id.editprof_password);
dob_editText = (EditText)findViewById(R.id.editprof_dob);
genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
editBtn = (Button)findViewById(R.id.editprof_editbtn);
deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
intent = getIntent();
dbHandler = new DBHandler(EditProfile.this);
setUserDetails();
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if(username == null){
Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(username);
if(users == null){
Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
}
else{
dbHandler.deleteInfo(username);
Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
startActivity(redirectintent_home);
}
}
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
String username = userName_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
genderRadioBtn = (RadioButton)findViewById(selectedGender);
String gender = genderRadioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
users.setId(userID);
dbHandler.updateInfor(users);
Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
startActivity(redirectintent_home);
}
});
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = userName_editText.getText().toString();
if (username == null){
Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users_search = dbHandler.readAllInfor(username);
if(users_search == null){
Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
}
else{
userName_editText.setText(users_search.getUsername());
password_editText.setText(users_search.getPassword());
dob_editText.setText(users_search.getDob());
int id = users_search.getId();
Intent redirectintent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
startActivity(redirectintent);
}
}
}
});
}
public void setUserDetails(){
String userID_String = intent.getStringExtra(Home.USERID);
if(userID_String == null){
Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
startActivity(redirectintent_home);
}
int userID = Integer.parseInt(userID_String);
UserProfile.Users users = dbHandler.readAllInfor(userID);
userName_editText.setText(users.getUsername());
password_editText.setText(users.getPassword());
dob_editText.setText(users.getDob());
}
}
*********db hander*******************
/**
* Created by Suraj on 10/6/2018.
*/
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context) {
super(context, "user_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT
,"+UserProfile.Users.COL_USERNAME+" TEXT UNIQUE," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB +" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
//onUpgardeMethod// String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTO INCREMENT
,"+UserProfile.Users.COL_USERNAME+" TEXT," +
UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB+" TEXT"+")";
Log.d("createQuery",createQuery);
try {
db.execSQL(createQuery);
}
catch (Exception e){
e.printStackTrace();
Log.e("Exception",e.getMessage());
}
}
public boolean addInfo(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
String insertQuery = "INSERT INTO "+UserProfile.Users.TABLE_NAME+"("+UserProfile.Users.COL_USERNAME+","+UserProfile.Users.COL_PASSWORD+",
"+UserProfile.Users.COL_GENDER+","+
UserProfile.Users.COL_DOB+") VALUES('"+users.getUsername()+"','"+users.getPassword()+"','"+users.getGender()+"','"+users.getDob()+"')";
Log.d("insertQuery",insertQuery);
try {
db.execSQL(insertQuery);
return true;
}
catch (Exception e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
db.close();
return false;
}
public boolean updateInfor(UserProfile.Users users){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String username = users.getUsername();
String password = users.getPassword();
String dob = users.getDob();
String gender = users.getGender();
int id = users.getId();
values.put(UserProfile.Users.COL_DOB,dob);
values.put(UserProfile.Users.COL_GENDER,gender);
values.put(UserProfile.Users.COL_PASSWORD,password);
values.put(UserProfile.Users.COL_USERNAME,username);
int result = db.update(UserProfile.Users.TABLE_NAME,values,UserProfile.Users.COL_ID+" = ?",new String[]{String.valueOf(id)});
if(result >0)
return true;
return false;
}
public ArrayList<UserProfile.Users> readAllInfor(){
ArrayList<UserProfile.Users> userList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String readAllQuery = "SELECT * FROM "+UserProfile.Users.TABLE_NAME;
Cursor cursor = db.rawQuery(readAllQuery,null);
if(cursor.moveToFirst()){
do{
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
userList.add(users);
}while (cursor.moveToNext());
}
return userList;
}
public UserProfile.Users readAllInfor(String userName){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME + " = '"+ userName+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public UserProfile.Users readAllInfor(int id){
SQLiteDatabase db = this.getWritableDatabase();
String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_ID + " = '"+ id+"'";
Cursor cursor = db.rawQuery(readSingleQuery,null);
if(cursor.moveToFirst()){
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setId(Integer.parseInt(cursor.getString(0)));
users.setUsername(cursor.getString(1));
users.setPassword(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setDob(cursor.getString(4));
return users;
}
return null;
}
public void deleteInfo(String username){
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery = "DELETE FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME +" = '"+ username +"' ";
Log.d("deleteQuery ",deleteQuery);
db.execSQL(deleteQuery);
db.close();
}
}
ProfileMangement
public class ProfileManagement extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
EditText dob_editText;
RadioGroup radioGroup;
RadioButton gender_radioBtn;
Button saveProfBtn;
public final static String USERID_PROFILEMGMT = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
username_editText = (EditText)findViewById(R.id.profmgmt_userName);
password_editText = (EditText)findViewById(R.id.profmgmt_password);
dob_editText = (EditText)findViewById(R.id.profmgmt_dob);
radioGroup = (RadioGroup)findViewById(R.id.profmgmt_radiogroup);
saveProfBtn = (Button)findViewById(R.id.profmgmt_btn);
final DBHandler dbHandler = new DBHandler(ProfileManagement.this);
saveProfBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = username_editText.getText().toString();
String password = password_editText.getText().toString();
String dob = dob_editText.getText().toString();
int selectedGender = radioGroup.getCheckedRadioButtonId();
gender_radioBtn = (RadioButton)findViewById(selectedGender);
String gender = gender_radioBtn.getText().toString();
UserProfile.Users users = UserProfile.getProfile().getUser();
users.setUsername(username);
users.setPassword(password);
users.setDob(dob);
users.setGender(gender);
boolean result = dbHandler.addInfo(users);
if(result == true){
Toast.makeText(ProfileManagement.this,"Successfully added",Toast.LENGTH_SHORT).show();
UserProfile.Users newusers = dbHandler.readAllInfor(username);
int userID = newusers.getId();
Intent intent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
intent.putExtra(USERID_PROFILEMGMT,Integer.toString(userID));
startActivity(intent);
}
}
});
}
}
public final class UserProfile {
private UserProfile(){
}
public static UserProfile getProfile(){
UserProfile userProfile = new UserProfile();
return userProfile;
}
class Users implements BaseColumn{
public static final String TABLE_NAME = "UserInfo";
public static final String COL_ID = "_ID";
public static final String COL_USERNAME = "userName ";
public static final String COL_DOB = "dateOfBirth";
public static final String COL_GENDER = "Gender";
public static final String COL_PASSWORD = "Password";
private int id;
private String username;
private String dob;
private String gender;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
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 Users getUser(){
Users users = new Users();
return users;
}
}
public class Home extends AppCompatActivity {
EditText username_editText;
EditText password_editText;
Button loginbtn;
Button registerbtn;
public static final String USERID = "userID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
username_editText = (EditText)findViewById(R.id.home_userName);
password_editText = (EditText)findViewById(R.id.home_password);
loginbtn = (Button)findViewById(R.id.home_loginBtn);
registerbtn = (Button)findViewById(R.id.home_registerBtn);
final DBHandler dbHandler = new DBHandler(Home.this);
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("com.modelpaper.mad.it17121002.ProfileManagement");
startActivity(intent);
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userName = username_editText.getText().toString();
String password = password_editText.getText().toString();
if(userName == null){
Toast.makeText(Home.this,"Login Unsuccessful",Toast.LENGTH_SHORT).show();
}
else{
UserProfile.Users users = dbHandler.readAllInfor(userName);
if(users == null){
Toast.makeText(Home.this,"Invalid username or password",Toast.LENGTH_SHORT).show();
}
else{
int userID = users.getId();
Intent editProfIntent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
editProfIntent.putExtra(USERID,Integer.toString(userID));
startActivity(editProfIntent);
}
}
}
});
}
}

Jersey RESTful POST operation gets null values of #PathParam and does not INSERT expected values in MySQL

My RESTful POST operation is as follows
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.transaction.annotation.Transactional;
#Path("/dbuser")
public class DBUserRestServices extends DbConnectionDAO{
#POST
#Path("/postuser1") //Problem here???
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED})
#Transactional
public Response userPOSTOperation( #PathParam("userid") int userid,#PathParam("username") String username,
#PathParam("password") String password) throws SQLException{
UserObject userobj = new UserObject(userid, username, password);
username= userobj.getUsername();
password= userobj.getPassword();
System.out.println("UserName " + username + "\t\t"+ "Password :" + password);
dbConnection = new DbConnectionDAO();
String sqlQuery = "INSERT INTO user (username, password) values ('" +"username" +"',"+ "'password" +"')";
System.out.println("Query executed : " + sqlQuery );
try{
connection = DbConnectionDAO.setDBConnection();
statement = connection.createStatement();
numRowsChanged = statement.executeUpdate(sqlQuery);
System.out.println("numRowsChanged : " + numRowsChanged );
if (numRowsChanged<=0)
{
System.out.println("Oops!! The insertion operation failed");
}
else{
System.out.println("The POST operation with username = " + username + ", password "+ password+" has been completed");
}
} catch (Exception e)
{
System.out.println(e.getMessage());
}
return Response.ok().build();
}
}
//
// The DbConnectionDAO.java file is
public class DbConnectionDAO {
public static Connection connection;
public static Statement statement;
public static PreparedStatement pst;
public static ResultSet rs = null;
private static String sqlQuery = null;
static int numRowsChanged = 0;
public static Connection setDBConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/test";
// Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
if (connection != null) {
// System.out.println("Connected to the Database...");
}
return connection;
}
catch (SQLException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
// The UserObject.java file is
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "userObject")
public class UserObject {
private int userid;
private String username;
private String password;
public UserObject(){}
public UserObject(int userid, String username, String password){
this.userid = userid;
this.username = username;
this.password = password;
}
public String getPassword() {
return password;
}
public int getUserid() {
return userid;
}
public String getUsername() {
return username;
}
#XmlElement
public void setPassword(String password) {
this.password = password;
}
#XmlElement
public void setUserid(int userid) {
this.userid = userid;
}
#XmlElement
public void setUsername(String username) {
this.username = username;
}
}
When I give the following command in Postman: http://localhost:8080/iAdjuster/restapi/dbuser/postuser1/?username=John&password=Michael
it shows the following Console output:
UserName null Password :null
Query executed : INSERT INTO user (username, password) values ('username','password')
numRowsChanged : 1
The POST operation with username = null, password null has been completed
However, the MySQL database shows a successful INSERtion with values 'username' and 'password' in the username and password fields with an auto increment userid.
How can I fix this problem?
There are few problems in your code -
You are using POST method, but your logic is not related to POST data processing. So, Identify and decide whether you want to send GET request or POST request. If you want to send all data in request URI, there is no point of using POST method, instead you should use GET method.
In your calling command, you are passing 'username' and 'password' as query parameter and in the REST API, you are receiving them as Path parameters. There is a difference between path parameters and query parameters. Also, you haven't defined 'username' and 'password' in #Path annotation. That is why, they are null.
Your method declaration should look like below -
#POST
#Path("/{userid}/{username}/{password}")
#Transactional
public Response userPOSTOperation( #PathParam("userid") int userid,#PathParam("username") String username,
#PathParam("password") String password) throws SQLException{
And you should be able to send POST request with URI -
http://localhost:8080/iAdjuster/restapi/dbuser/userId/John/Michael
Also, your SQL query is wrong. SQL query should be -
String sqlQuery = "INSERT INTO user (username, password) values ('" +username +"','"+ password +"')";

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.