How to get class from list by value therein? - java

I have class that stores groups' permissions for single element. In it, I've also class for single group's permissions set. The solution is simple, looks that.
But I have no idea how can I get single permissions set using value in it (in group_id). How can I do that?
public class PermissionsData {
private List<PermissionsDataSingle> permissionsData;
PermissionsData(List<PermissionsDataSingle> permissionsData) {
this.permissionsData = permissionsData;
}
public PermissionsDataSingle getPermissionsByGroupID(int group_id) {
// ToDo
}
public class PermissionsDataSingle {
public int group_id;
public boolean canView;
public boolean canRead;
public boolean canReply;
public boolean canStart;
public boolean canUpload;
public boolean canDownload;
PermissionsDataSingle(int group_id, boolean canView, boolean canRead, boolean canReply, boolean canStart, boolean canUpload, boolean canDownload) {
this.group_id = group_id;
this.canView = canView;
this.canRead = canRead;
this.canReply = canReply;
this.canStart = canStart;
this.canUpload = canUpload;
this.canDownload = canDownload;
}
}
}

If the list is always very short, you can simply iterate through it and check the group_id for each entry. Otherwise it's better to use a map.
for (PermissionsDataSingle pds : permissionsData) {
if (pds.group_id == group_id) {
return pds;
}
}
// Not found

Related

How to enable a JButton on a condition?

I'm trying to create a JButton that enables when certain conditions are met. The program sets setEnabled(false) as initial value, but after an update, it should be setEnabled(true).
I tried several things. Here some code:
public class SwimAction extends AbstractAction {
private final PoolModel poolModel;
private final Swimmer swimmer;
public SwimAction(PoolModel poolModel, Swimmer swimmer) {
super("GO!");
this.poolModel = poolModel;
this.swimmer = swimmer;
// default
setEnabled(false);
}
I tried the following:
// Replaced the setEnabled(false) by setEnabled(checkGo())
public boolean checkGo(){
return(pool.isNotOccupied());
}
// Overwrite setEnabled
#Overwrite
public void setEnabled(boolean bool){
boolean oldBool = this.enabled;
if (oldBool != bool && pool.isNotOccupied()) {
this.enabled = bool;
this.firePropertyChange("enabled", oldBool, bool);
}
}
However, none of them worked. Anyone knows how to enable the button when a certain condition (pool.isNotOccupied()) is met?
Seems like you need to listener for a change in the state of the pool object's occupied property, and the best way to do this is to give it a listener of some sort. This could be as simple as a ChangeListener or perhaps better, a PropertyChangeListener. The details of the best solution would likely depend much on the structure of your program, of the rest of the code that we can't see, but, if PoolModel is what you're listening to, what if you gave it...
public class PoolModel {
public static final String OCCUPIED = "occupied";
private PropertyChangeSupport propChangeSupport = new PropertyChangeSupport(this);
private boolean occupied;
public void addPropertyChangeListener(PropertyChangeListener l) {
propChangeSupport.addPropertyChangeListener(l);
}
// also have a remove listener
public boolean isOccupied() {
return occupied;
}
public void setOccupied(boolean occupied) {
boolean oldValue = this.occupied;
boolean newValue = occupied;
this.occupied = occupied;
propChangeSupport.firePropertyChange(OCCUPIED, oldValue, newValue);
}
// ......
And then in the code that uses it:
poolModel.addPropertyChangeListener(pcEvent -> {
if (pcEvent.getPropertyName().equals(OCCUPIED)) {
setEnabled((boolean) pcEvent.getNewValue());
}
});

Java - how to call a method of corresponding class based on string using enum/factory pattern

Yes, I read many examples in web, but I didn't find a way how to call a method based on string value. May be I am not searching in right way... I wrote all code, but don't know how to call the method.
fyi: I don't want to use if else or switch case
Here is what I want:
I get the card reader type as String from database. I have to call the corresponding class' method.
My code:
LoginPanel.java
public class LoginPanel {
public static void main(String args[]) {
String readerType = "Omnikey5427-CK"; // I get this ("Omnikey5427-CK" or "Omnikey5427-G2") from a database as String
// I WANT TO CALL getCardNumber() method of respective class
}
}
ISmartCardReader.java
public interface ISmartCardReader {
public Integer getCardNumber();
}
Omnikey5427G2.java
public class Omnikey5427G2 implements ISmartCardReader {
public Omnikey5427G2() {
System.out.println("G222222222222222...");
}
public Integer getCardNumber() {
return 222;
}
}
Omnikey5427CK.java
public class Omnikey5427CK implements ISmartCardReader {
public Omnikey5427CK() {
System.out.println("CKKKKKKKKKKKKKKK...");
}
public Integer getCardNumber() {
return 111;
}
}
SmacrtCardEnumFactory.java
public enum SmacrtCardEnumFactory {
OMNIKEY5427CK("Omnikey5427-CK") {
public ISmartCardReader geInstance() {
return new Omnikey5427CK();
}
},
OMNIKEY5427G2("Omnikey5427-G2") {
public ISmartCardReader geInstance() {
return new Omnikey5427G2();
}
};
private String cardReaderName;
private SmacrtCardEnumFactory(String cardReaderName) {
this.cardReaderName = cardReaderName;
}
public String cardReaderName() {
return cardReaderName;
}
}
You can use valueOf() function of enum provided your enum sonstant names match strings used to lookup (you may use cardName.toUpper()). You may also create objects for all the card types and store them in a hash map and then lookup them. You can also write some fatory method, but this will be if-then-else or switch inside
You could iterate over the factory's values() and get the one that matches the string:
public enum SmacrtCardEnumFactory {
// current code omitted for brevity
public static getSmartCardReader(String name) {
return Arrays.stream(values())
.filter(r -> r.cardReaderName().equals(name))
.map(SmacrtCardEnumFactory::getInstance();
.orElse(null);
}
}

How to get enum value from property

I have an enum with values VALID and INVALID, which have a boolean property associated with them. I would like to get the enum value based on a boolean value I provide.
If it is true I should get VALID, if it is false I should get INVALID. I would like to do so in a getter method like the below, based on the value of the member variable
public boolean getCardValidityStatus() {
return CardValidationStatus status = CardValidationStatus(this.mCardValidityStatus));
}
My code:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
private boolean isValid;
CardValidationStatus(boolean isValid) {
this.isValid = isValid;
}
public boolean getValidityStatus() {
return this.isValid;
}
}
You're able to achieve that using a static lookup method in the enum itself:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public static CardValidationStatus forBoolean(boolean status) {
//this is simplistic given that it's a boolean-based lookup
//but it can get complex, such as using a loop...
return status ? VALID : INVALID;
}
}
And the appropriate status can be retrieved using:
public CardValidationStatus getCardValidityStatus() {
return CardValidationStatus.forBoolean(this.mCardValidityStatus));
}
I would add a parse method to your enum, which takes the boolean, iterates over all the values and returns the one that matches, for example:
public CardValidationStatus parse(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
#ernest_k solution made this work, but I think that's not reliable solution.
You should always do code which is independent.
Because his solution is hardcoded. What if values of VALID & INVALID are changed. Will you change your forBoolean logics also?
Because he did not check what the Enum fields are holding inside it.
Reliable solution will be #DaveyDaveDave answer. This will also work when you have many status with VALID & INVAlID.
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public CardValidationStatus forBoolean(boolean isValid) {
for (CardValidationStatus cardValidationStatus : CardValidationStatus.values()) {
if (cardValidationStatus.getValidityStatus() == isValid) {
return cardValidationStatus;
}
}
throw new IllegalArgumentException();
}
}
Suggestion (Easiest way I think)
Why are you making Enum just for storing 2 boolean values?
Just make static boolean named by VALID & INVALID.
public static final boolean CARD_STATUS_VALID = true;
public static final boolean CARD_STATUS_INVALID = false;
if(cardStatus == CARD_STATUS_VALID){
// todo
}

How do I override a method in a subclass in Java?

First off, I need to override the method:
public boolean recordBid(int bidPrice, String sellerID)
so it manages the recording of a bid.
To begin with, if the bidPrice is greater than the buyNowprice then this bidPrice should reset to the buyNowPrice. After the bid price has been reset (if required) the method should invoke the superclass version of the recordBid() method, passing along the bid price and seller ID as parameters, and trap the result that it returns (ie. store it in a variable), so that it can be checked to determine if the bid price has been recorded successfully.
Im a little confused on how I need to trap the result and also not sure if Im doing it the right way here?.
My original recordBid() method:
public boolean recordBid(int bidPrice, String bidderID)
{
if (saleEnded == true)
{
return false;
}
else if (bidPrice <= this.highestBid)
{
return false;
}
else
{
this.highestBid = bidPrice;
this.bidderID = bidderID;
return true;
}
}
My subclass, where I need to overwrite recordBid()
public class BuyItNowSale extends ItemSale {
//instance variables
private double buyNowPrice;
private boolean acceptingNearestOffer;
public BuyItNowSale(String itemNumber, String itemDescription, String itemCondition,
String sellerID, boolean acceptingNearestOffer) {
super(itemNumber, itemDescription, itemCondition, sellerID);
this.acceptingNearestOffer = false;
//overidden recordBid() method
public boolean recordBid(int bidPrice, String bidderID) {
if(bidPrice > buyNowPrice) {
bidPrice = 0;
super.recordBid(bidPrice, sellerID);
}
}
With your requirement
if the bidPrice is greater than the buyNowprice then this bidPrice should reset to the buyNowPrice
Your method should be:
#Override
public boolean recordBid(int bidPrice, String bidderID) {
if(bidPrice > buyNowPrice) {
bidPrice = (int) buyNowPrice;
}
return super.recordBid(bidPrice, sellerID);
}

Comparing dynamic fields of objects using equals and hashCode methods

To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
Map<LocationData, List<LocationData>>
The following is the class I used (its been shown to you so that it can be referred for my problem statement):
LocationData class
package com.astreait.bulkloader;
public class LocationData {
String locId, deptId, jobTitleId, classificationId;
#Override
public boolean equals(Object obj) {
LocationData ld = (LocationData)obj;
return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
this.locId.equals(ld.locId);
}
#Override
public int hashCode() {
return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();
}
}
Problem:
I'm already known to which all fields of this object I need to make the comparison.
i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
Need:
I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
I'm thinking what if I override the same two methods equals() & hashCode();
such that the same can be achieved.
TableClass class #1
class TableClass{
List<ColWithData> cwdList;
#Override
public boolean equals(Object obj) {
boolean returnVal = false;
// I need to have the logic to be defined such that
// all of the dynamic fields can be compared
return returnVal;
}
#Override
public int hashCode() {
int returnVal = 0;
// I need to have the logic to be defined such that
// all of the dynamic fields can be found for their individual hashCodes
return returnVal;
}
}
ColWithData class #2
class ColWithData{
String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
}
Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
Map<TableClass, List<TableClass>> finalMap;
EDIT I have been down voted. So, I made some modifications for my requirements again. (Please help me out solving this)
Using this class ColWithData is kind of ugly. You should be using a Map<String,String> :
package mypack;
import java.util.*;
public class TableClass {
/* HashMap containing your values:
map.put("locId", [data]);
...
*/
public Map<String,String> cwdMap;
public Map<String,String> getCwdMap() {
return cwdMap;
}
public void setCwdMap(Map<String,String> cwdMap) {
this.cwdMap = cwdMap;
}
#Override
public boolean equals(Object obj) {
TableClass tClass = (TableClass) obj;
for(String col: this.cwdMap.keyset()){
if (! tClass.cwdMap.get(col).equals(this.cwdMap.get(col)){
return false;
}
}
return true;
}
#Override
public int hashCode() {
int hCode = 0;
for(String col: this.cwdMap.keyset()){
hCode = hCode+cwdMap.get(col).hashCode();
}
return hCode;
}
}
In this code I never check for null values but your probably should.
There is another thing that confuse me in your code:
why use getter/setter if your property (cwdList) is public?
I think I have found the solution and its working for me.
Please let me know if there could be the simple or any other way out finding the solution for this problem.
The code snippet is:
package mypack;
import java.util.*;
public class TableClass {
public List<ColWithData> cwdList;
public List<ColWithData> getCwdList() {
return cwdList;
}
public void setCwdList(List<ColWithData> cwdList) {
this.cwdList = cwdList;
}
#Override
public boolean equals(Object obj) {
TableClass tClass = (TableClass) obj;
boolean returnVal = true;
for(ColWithData cwd: this.getCwdList()){
for(ColWithData innerCwd: tClass.getCwdList()){
if(cwd.getCol().equalsIgnoreCase(innerCwd.getCol())){
if(!cwd.getData().equalsIgnoreCase(innerCwd.getData()))
returnVal = false;
}
}
}
return returnVal;
}
#Override
public int hashCode() {
int hCode = 0;
for(ColWithData cwd: this.getCwdList()){
hCode = hCode+cwd.getData().hashCode();
}
return hCode;
}
}
And finally made a map as said:
Map<TableClass, List<TableClass>> map = new LinkedHashMap<TableClass, List<TableClass>>();
displaying the things as desired.

Categories