I have the following model:
public class HoverDescriptor {
private String id;
private String label;
private boolean enabled;
private String description;
private int stateMask;
private String modifierString;
public HoverDescriptor(String id, String label, boolean isEnabled, String description,
...
}
public class HoverViewModel {
Set<HoverDescriptor> mHovers;
private HoverViewModel() {
mHovers = new HashSet<HoverDescriptor>();
mHovers.add(new HoverDescriptor("Mock1", "Label1", true, "Desc1", SWT.DEFAULT, ""));
mHovers.add(new HoverDescriptor("Mock2", "Label2", false, "Desc2",SWT.DEFAULT, ""));
mHovers.add(new HoverDescriptor("Mock3", "Label3", false, "Desc3", SWT.DEFAULT, ""));
}
public static HoverViewModel newInstance() {
return new HoverViewModel();
}
public Set<HoverDescriptor> getHovers() {
return mHovers;
}
I would like to bind:
final IObservableSet checkedElements = ViewersObservables.observeCheckedElements(viewer, HoverDescriptor.class);
to the following ObservableMap:
IBeanSetProperty descriptors = PojoProperties.set("hovers", HoverDescriptor.class);
IObservableMap observeMap = PojoObservables.observeMap(descriptors.observe(fViewModel), HoverDescriptor.class, "enabled");
But, except from the deprecated MappedSet and DataBindingContext.bindSet(?) I couldn't find any idiomatic way.
How can I effectively do it?
Related
#Convert(converter = MsisdnEncryptor.class,disableConversion=true)
I have used this converter in my spring boot entity class.
package com.example.demo.entity;
This is the entity class:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name="employee")
public class Employee {
#Id
#Column(name = "emp_id")
#SequenceGenerator(
name = "employee_sequence",
sequenceName = "employee_sequence",
allocationSize = 1
)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "employee_sequence")
private Long EmpId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "mobile_number")
**#Convert(converter = MsisdnEncryptor.class,disableConversion=true)**
**here I want to put values from application.properties in disableConversion**
private String mobileNumber;
#Column(name= "date_time")
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy HH:mm:ss", timezone="GMT+5:30")
private Timestamp dateTime;
}
This is the Encryptor class:
#Component
public class MsisdnEncryptor implements AttributeConverter<String, String> {
private static final Logger logger = LoggerFactory.getLogger(MsisdnEncryptor.class);
#Value("${is.enabled:true}")
private boolean isEnabled;
private static final String AES = "AES";
private static final String SECRET = "secret-key-12345";
private final Key key;
private final Cipher cipher;
public MsisdnEncryptor() throws Exception {
key = new SecretKeySpec(SECRET.getBytes(), AES);
cipher = Cipher.getInstance(AES);
}
#Override
public String convertToDatabaseColumn(String attribute) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
return Base64.getEncoder().encodeToString(cipher.doFinal(attribute.getBytes()));
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
#Override
public String convertToEntityAttribute(String dbData) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.getDecoder().decode(dbData)));
} catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
throw new IllegalStateException(e);
}
}
}
I know we can use #Value for taking the values , but it doesn't work here as it says attribute value must be constant.
Or if there is any other way of doing the encryption and enabling/disabling it from config , I would be more than happy to go through it.
I'm using a Thymeleaf HTML registration form and simple save/update method to save/update a 'dish' object to a mySQL database. Restaurant Id is a foreign key for the 'dish' but using the below methods it saves as 'null',
I would like to make it so that the Restaurant id of the currently logged in restaurant owner saves automatically when they add a dish.
Is there an uncomplicated way to do this? The closest tutorial I've found on Youtube involves using JSON requests in Postman and I've had issue adapting that to a HTML registration form in the past.
I'm quite new to all of this so any help would be very much appreciated!
See Dish class:
package com.bron.demoJPA.appuser;
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#ToString(exclude = "reqlist")
public class Dish {
#Id
#SequenceGenerator(name = "dish_sequence", sequenceName = "dish_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_sequence")
#Column(name = "dish_Id")
private Long dishId;
#Column(name = "dish_name")
private String dname;
#Column(name = "dish_description")
private String description;
#Column(name = "dish_price")
private double price;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "Rest_ID", referencedColumnName = "Rest_ID")
private AppUser app;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "dish_requirment_mapping", joinColumns = #JoinColumn(name = "dish_Id", referencedColumnName = "dish_Id"), inverseJoinColumns = #JoinColumn(name = "Require_ID", referencedColumnName = "Require_ID"))
private List<Requirments> reqlist;
public void addRequirments(Requirments req) {
if (reqlist == null)
reqlist = new ArrayList<>();
reqlist.add(req);
}
}
See AppUser(restaurant owner) Class
#Column(name = "Rest_Password")
private String password;
#Column(name = "Rest_Email_Address")
private String email;
#Enumerated(EnumType.STRING)
private AppUserRole appUserRole;
private Boolean locked = false;
// don't enable user until email verification
private Boolean enabled = false;
public AppUser(String restname, String email, String pass, AppUserRole app) {
this.restaurantName = restname;
this.email = email;
this.password = pass;
this.appUserRole = app;
}
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name());
return Collections.singletonList(authority);
}
#Override
public String getUsername() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)
#JoinColumn(name = "openingHourID", referencedColumnName = "OpeningHour_ID")
private OpeningHour opening;
}
See Controller class:
package com.bron.demoJPA.conroller;
#Controller
public class DishController {
//display list of employees
#Autowired
private DishService dishService;
#GetMapping("/dish")
public String viewHomePage(Model model) {
model.addAttribute("listDish", dishService.getAllDish());
return "index";
}
#GetMapping("/showNewDishForm")
public String showNewDishForm(Model model) {
// Create model attribute to bind form data
Dish dish = new Dish();
model.addAttribute("dish", dish);
return "new_dish";
}
#PostMapping("/saveDish")
public String saveDish(#ModelAttribute("dish") Dish dish) {
// save dish to database
dishService.saveDish(dish);
return "redirect:/dish";
}
#GetMapping("/showFormForUpdate/{dishId}")
public String showFormForUpdate(#PathVariable(value = "dishId") long dishId, Model model) {
// get dish from service
Dish dish = dishService.getDishByDishId(dishId);
// set dish as model to pre-populate the form data
model.addAttribute("dish", dish);
return "update_dish";
}
}
See Service implementation
package com.bron.demoJPA.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bron.demoJPA.appuser.Dish;
import com.bron.demoJPA.repository.DishRepository;
#Service
public class DishServiceImpl implements DishService {
#Autowired
private DishRepository dishRepository;
#Override
public List<Dish> getAllDish() {
return dishRepository.findAll();
}
#Override
public void saveDish(Dish dish) {
this.dishRepository.save(dish);
}
#Override
public Dish getDishByDishId(long dishId) {
Optional<Dish> optional = dishRepository.findById(dishId);
Dish dish = null;
if (optional.isPresent()) {
dish = optional.get();
} else {
throw new RuntimeException("Dish not found for: " + dishId);
}
return dish;
}
}
See Service class
public interface DishService {
List<Dish> getAllDish();
void saveDish(Dish dish);
Dish getDishByDishId(long dishId);
}
Can you make sure Dish's "app" attribute is being set correctly before trying to save it?
If it's null or it's a brand new instance of AppUser class it makes sense that when trying to match and persist it ends up on null.
Greetings!
//Database is Sucessfully Connected
I am trying to Create a table in which I want to display the contents of my 'student' table in tableView of Javafx but I could not get the desired output.
ObservableList<Student> list = FXCollections.observableArrayList();
#FXML
//Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO
initCol();
loadTable();
}
//A view Table has been made with fx:id-table
//Variable name for 2 columns are 'fx:id-rollnoColand' & 'fx:id-nameCol'
#FXML
private TableView<Student> table;
#FXML
private TableColumn<Student,String> rollnoCol;
#FXML
private TableColumn<Student,String> nameCol;
private void initCol()
{
rollnoCol.setCellValueFactory(new PropertyValueFactory<>("s_rollno"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("s_name"));
}
//Name of the Table is 'student' with Columns 'rollno' and 'name'
private void loadTable()
{
String selectAll = "select * from student";
try
{
Statement stmt = connectdb.createStatement();
ResultSet rs = stmt.executeQuery(selectAll);
while(rs.next())
{
String getrollno = rs.getString("rollno");
String getname = rs.getString("name");
list.add(new Student(getrollno,getname));
}
}
catch(SQLException exp)
{
System.out.println(exp);
}
table.getItems().setAll(list);
}
public static class Student
{
private final String s_rollno;
private final String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
}
PropertyValueFactory works with getters or property methods. In your case you need to add getters for your properties in the Student class to enable PropertyValueFactory to retrieve the values:
public static class Student {
private final String s_rollno;
private final String s_name;
Student(String rollno, String name) {
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public String getS_name() {
return s_name;
}
}
I had this problem before,and it has many reason.First ,you may remove final keyword from your model,because your variables are changing.Second, TableView shows empty cells because you make your variables private in class Student and you can not access them from init method in parent class.So you need add getter and setter methods for access to these variables.
public static class Student
{
private String s_rollno;
private String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public void setS_rollno(String s_rollno) {
this.s_rollno = s_rollno;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
}
I hade a strange happening today with my Firebase project.
Suddenly the
AddressChatMessage chatMessage = snapshot.getValue(AddressChatMessage.class);
parsed everything ok for the AddressChatMessage except for one int.
Took me 2 hour until i tried this, setting the field to public
public int type;
Note I use this code for weeks without problem and today Android studio made some core updated to 2.3.2 and maybe that trigger this strange event.
Here´s the AddressChatMessage.java nothing strange except that the public int type cannot be private, if it is, it will be zero, that too is strange, usually Firebase give out a logcat warning when pojo parsing fails. I have 10 other modell classes like this with plenty of int´s
#IgnoreExtraProperties
public class AddressChatMessage {
// [START Firebase keys inside AddressChatMessage ]
#Exclude
public static final String TYPE = "type";
#Exclude
public static final String SENDER_ID = "senderId";
#Exclude
public static final String MESSAGE = "message";
#Exclude
public static final String FILENAME = "fileName";
#Exclude
public static final String DOWNLOAD_URI = "downloadUri";
#Exclude
public static final String TIME = "time";
// [STOP Firebase keys inside AddressChatMessage ]
public int type;
private String senderId;
private String message;
private String fileName;
private String downloadUri;
#Exclude
private long time;
#Exclude
private String messageId;
public AddressChatMessage() {
}
public AddressChatMessage(int type, String senderUid) {
this.senderId = senderUid;
this.type = type;
}
public AddressChatMessage(int type, String senderUid, String message) {
this.type = type;
this.senderId = senderUid;
this.message = message;
}
private int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDownloadUri() {
return downloadUri;
}
public void setDownloadUri(String downloadUri) {
this.downloadUri = downloadUri;
}
public long getTime() {
return time;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put(TYPE, type);
result.put(SENDER_ID, senderId);
result.put(MESSAGE, message);
result.put(FILENAME, fileName);
result.put(DOWNLOAD_URI, downloadUri);
result.put(TIME, time);
return result;
}
#Exclude
public boolean isTypeNormal() {
return getType() == ChatAdapter.MessageType.NORMAL.ordinal();
}
#Exclude
public boolean isTypeImage() {
return getType() == ChatAdapter.MessageType.IMAGE.ordinal();
}
}
When cleaning the code using Lint. Lint suggested changes like "This can be private instead of public" - I accidentally set the getType() to private access.
I have the following class:
#PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class TclRequest implements Comparable<TclRequest> {
#PrimaryKey
private String id;
#Persistent(types = { DNSTestData.class, POP3TestData.class, PPPoETestData.class, RADIUSTestData.class }, defaultFetchGroup = "true")
#Columns({ #Column(name = "dnstestdata_fk"), #Column(name = "pop3testdata_fk"), #Column(name = "pppoetestdata_fk"), #Column(name = "radiustestdata_fk") })
private TestData testData;
public String getId() {
return id;
}
public TestData getTestData() {
return testData;
}
public void setId(String id) {
this.id = id;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
The TestData interface looks like this:
#PersistenceCapable(detachable = "true")
public interface TestData {
#PrimaryKey
public String getId();
public void setId(String id);
}
Which is implemented by many classed including this one:
#PersistenceCapable(detachable = "true")
public class RADIUSTestData implements TestData {
#PrimaryKey
private String id;
private String password;
private String username;
public RADIUSTestData() {
}
public RADIUSTestData(String password, String username) {
super();
this.password = password;
this.username = username;
}
#Override
public String getId() {
return id;
}
#Override
public void setId(String id) {
this.id = id;
}
}
When I try to persiste the TclRequest class, after constructing it of course and using the RADIUSTestData:
//'o' is the constructed TclRequest object.
PersistenceManager pm = null;
Transaction t = null;
try {
pm = getPM();
t = pm.currentTransaction();
t.begin();
pm.makePersistent(o);
t.commit();
} catch (Exception e) {
e.printStackTrace();
if (t != null && t.isActive()) {
t.rollback();
}
} finally {
closePM(pm);
}
The interface field isn't persisted. And the column is not created in the table ! I enabled the debug mode and found 2 catchy things:
1)
-Class com.skycomm.cth.beans.ixload.radius.TestData specified to use "application identity" but no "objectid-class" was specified. Reverting to javax.jdo.identity.StringIdentity
2)
-Performing reachability on PC field "com.skycomm.cth.beans.TclRequest.testData"
-Could not find StateManager for PC object "" at field "com.skycomm.cth.beans.TclRequest.testData" - ignoring for reachability
What could this mean ?
Thanks in advance.
I have figured out how to do it. It's not very much scalable but it works for now.
These are the annotations for the interface member variable. Note that the order of declared types, columns and class names in the extension value is important to be maintaned:
#Persistent(types = { RADIUSTestData.class, POP3TestData.class, PPPoETestData.class, DNSTestData.class }, defaultFetchGroup = "true")
#Columns({ #Column(name = "radiustestdata_fk"), #Column(name = "pop3testdata_fk"), #Column(name = "pppoetestdata_fk"),
#Column(name = "dnstestdata_fk") })
#Extension(vendorName = "datanucleus", key = "implementation-classes", value = "com.skycomm.cth.tcl.beans.radius.RADIUSTestData, com.skycomm.cth.tcl.beans.pop3.POP3TestData, com.skycomm.cth.tcl.beans.pppoe.PPPoETestData, com.skycomm.cth.tcl.beans.dns.DNSTestData")
A sample class implementing one of the interfaces (Just it's "header"):
#PersistenceCapable(detachable = "true")
public class RADIUSTestData implements TestData {
So it's pretty normal here.