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);
}
}
}
});
}
}
Related
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)
Having trouble creating only one model ,created a photo model and payee model but want to add photo model to payee model but wont accept the binary part of photo . Keep getting binary error when trying to post off of postman ,aware that need to change controller but a bit stuck ,any links or advise for a begginner would be gratefull
//Payee model
public class Payee {
#Id
private String id;
private Contact contact;
private String notes;
private String project;
private String member;
private Integer staffMember;
private Photo photo;
private BankAccount userBankAccount;
private PayeeBankAccount payeeBankAccountList;
//Payee constructor
public Payee(Contact contact, String notes, String project, String member, Integer staffMember,
Photo photo, BankAccount userBankAccount, PayeeBankAccount payeeBankAccountList) {
this.contact = contact;
this.notes = notes;
this.project = project;
this.member = member;
this.staffMember = staffMember;
this.photo = photo;
this.userBankAccount = userBankAccount;
this.payeeBankAccountList = payeeBankAccountList;
}
// Getters and Setters
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public Contact getContact() { return contact; }
public void setContact(Contact contact) { this.contact = contact; }
public String getNotes() { return notes; }
public void setNotes(String notes) { this.notes = notes; }
public String getProject() { return project; }
public void setProject(String project) { this.project = project; }
public String getMember() { return member; }
public void setMember(String member) { this.member = member; }
public Integer getStaffMember() { return staffMember; }
public void setStaffMember(Integer staffMember) { this.staffMember = staffMember; }
public Photo getPhoto() {return photo;}
public void setPhoto(Photo photo) {this.photo = photo;}
public BankAccount getUserBankAccount() { return userBankAccount; }
public void setUserBankAccount(BankAccount userBankAccount) { this.userBankAccount = userBankAccount}
public PayeeBankAccount getPayeeBankAccountList() { return payeeBankAccountList; }
public void setPayeeBankAccountList(PayeeBankAccount payeeBankAccountList){this.payeeBankAccountList= payeeBankAccountList; }
}
//photo model
public class Photo {
#Id
private String id;
private String title;
private Binary image;
//Photo constructor
public Photo(String id, String title, Binary image) {
this.id = id;
this.title = title;
this.image = image;
}
public Photo(String title) {
super();
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
#Override
public String toString() {
return "Photo \[id=" + id + ", title=" + title + ", image=" + image + "\]";
}
}
//photo service
#Service
public class PhotoService {
#Autowired
private PhotoRepository photoRepo;
public Photo getPhoto(String id) {
return photoRepo.findById(id).get();
}
public String addPhoto(String title, MultipartFile file) throws IOException {
Photo photo = new Photo(title);
photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes()));
photo = photoRepo.insert(photo);
return photo.getId();
}
}
Photo and payee PostMapping should be in one ,dont know where to go with this part
//add payee
#PostMapping('/addPayee')
public void insert(#RequestBody Payee payee){
this.payeeRepository.save(payee);
}
//add photo
#PostMapping('/photos/add')
public String addPhoto(#RequestBody Payee payee , #RequestParam("title") String title, #RequestParam("image") MultipartFile image, Model model)
throws IOException {
String id = photoService.addPhoto(title,image);
return id;
}][1]][1]
[1]: https://i.stack.imgur.com/lF6KZ.png
Figured it out in you model have image as binary and in youre controller have some like
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity update(#RequestPart("payee") #Valid Payee payee, #RequestPart("file") #Valid MultipartFile image) throws IOException
{
// routine to update a payee including image
if (image != null)
payee.setImage(new Binary(BsonBinarySubType.BINARY, image.getBytes()));
Payee result = payeeRepository.save(payee);
return ResponseEntity.ok().body(result);
}
I am trying to call a STORED PROCEDURE(with a out refcursor parameter) in postgresql through JPA2.1 like this:
public class JpaINParam {
public static void main(String[] args) throws Exception {
EntityManagerFactory emfactory = Persistence
.createEntityManagerFactory("JPA2");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
StoredProcedureQuery q = entitymanager.createNamedStoredProcedureQuery("get_hibernate_dtl");
q.setParameter("modeval", "1");
q.execute();
#SuppressWarnings("unchecked")
List<Student> students = (List<Student>) q.getOutputParameterValue("resultset");
for (Student student : students) {
System.out.println(student.getFname());
}
entitymanager.getTransaction().commit();
entitymanager.close();
try {
// storedProcedure.executeUpdate();
System.out.println("444444444444");
} catch (Exception e) {
e.printStackTrace();
}
}
}
i get the following error:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: A CallableStatement function was executed and the out parameter 1 was of
type java.sql.Types=2001 however type java.sql.Types=1111 was
registered.
Error Code: 0
Call: {?= CALL get_hibernate_dtl(?)}
bind => [2 parameters bound]
Query: ResultSetMappingQuery(name="get_hibernate_dtl" )
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:316)
at com.javacodegeeks.examples.jpa.service.JpaINParam.main(JpaINParam.java:36)
the following is my entity class:
#NamedStoredProcedureQuery(name="get_hibernate_dtl", procedureName="get_hibernate_dtl", resultClasses={Student.class}, returnsResultSet = true, parameters={
#StoredProcedureParameter(queryParameter="resultset", name="resultset", mode=ParameterMode.REF_CURSOR,type=Class.class),
#StoredProcedureParameter(queryParameter="modeval", name="modeval", mode=ParameterMode.IN,type=String.class)
})
#Entity
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int sid;
private String fname;
private String lname;
private String dept;
private int year;
private String email;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(int sid, String fname, String lname, String dept, int year,
String email) {
super();
this.sid = sid;
this.fname = fname;
this.lname = lname;
this.dept = dept;
this.year = year;
this.email = email;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [sid=" + sid + ", fname=" + fname + ", lname=" + lname
+ ", dept=" + dept + ", year=" + year + ", email=" + email
+ "]";
}
}
this is my procedure in postgresql:
CREATE OR REPLACE PROCEDURE dwh.get_hibernate_dtl(resultset OUT ahis_type.refcursor, modeval IN character varying DEFAULT '1'::character varying) AS
query VARCHAR2 (6000);
v_type NUMERIC(3,0);
v_dwh_type_id VARCHAR2(100);
BEGIN
IF (modeval = 1) THEN
QUERY := ' SELECT sid,fname FROM STUDENT ';
END IF;
INSERT INTO tmp_table values ( 'get_hibernate_dtl----Modeval-->'||modeval||'query--->'||QUERY );
OPEN resultset FOR QUERY;
END
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.
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