Common method for null check - java

I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts

Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);

Related

InApp Billing version 3 to version 5. BillingClient.ProductType.SUBS. codes not working

I tried all the answers on the internet, but nothing works, if anyone has a solution for this, will be really helpful for my application. I'm having a problem while updating the InApp billing from Version 3 to 5. First of all, I'm not really good with in-app billing. some of the codes are depreciated and not working anymore. some answers from the internet are confusing
I'm getting errors when I add
if (purchase.getProducts().equals(sku)) {
return true;
} else {
return false;
}
it says "Cannot return a value from a method with void result type"
Then (V3.0.3, worked first).
public boolean isSubscribedToSubscriptionItem(String sku) {
if (skuListSubscriptionsList != null) {
Purchase.PurchasesResult result = billingClient.queryPurchases(BillingClient.SkuType.SUBS);
if (result.getResponseCode() == BillingClient.BillingResponseCode.OK && result.getPurchasesList() != null) {
for (Purchase purchase :
result.getPurchasesList()) {
if (purchase.getSku().equals(sku)) {
return true;
} else {
return false;
}
}
}
}
return false;
}
Now (V5.1.0, Some errors).
public boolean isSubscribedToSubscriptionItem(String sku) {
if (skuListSubscriptionsList != null) {
billingClient.queryPurchasesAsync(
QueryPurchasesParams.newBuilder()
.setProductType(BillingClient.ProductType.SUBS)
.build(),
new PurchasesResponseListener() {
#Override
public void onQueryPurchasesResponse(BillingResult billingResult, List<Purchase> purchases) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK&&purchases != null) {
for (Purchase purchase : purchases) {
// ERROR : Cannot return a value from a method with void result type. What to write here ?
if (purchase.getProducts().equals(sku)) {
return true;
} else {
return false;
}
}
}
}
});
}
return false;
}
These codes are in my splash activity (kt)
override fun displayErrorMessage(message: String?) {
when {
message.equals("done") -> {
AppSettings.isUserPaid =
billingClass!!.isSubscribedToSubscriptionItem(AppSettings.one_month_subscription_id) ||
billingClass!!.isSubscribedToSubscriptionItem(AppSettings.three_month_subscription_id) ||
billingClass!!.isSubscribedToSubscriptionItem(AppSettings.one_year_subscription_id)
startMainActivity()
}
message.equals("error") -> {
AppSettings.isUserPaid = false;
startMainActivity()
}
else -> {
AppSettings.isUserPaid = false;
startMainActivity()
}
}
}
I'm assuming you are trying to get the ProductId from the Purchase object returned from google play when the user has done purchasing your product.
Please note that This getSku() method is deprecated. Use getProducts() instead.
read more: https://developer.android.com/reference/com/android/billingclient/api/Purchase
getProducts() - Returns the product Ids.
The trick is to use .get(index) on the list.
Check the example
void verifySubPurchase(Purchase purchases) {
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(purchases.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams, billingResult -> {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
String productId = purchases.getProducts().get(0); /// this one gets the product Id
String purchaseToken = purchases.getPurchaseToken(); /// this one gets the purchase token
}
});
}

How to shorten the condition code ? (JAV, Check null)

I use it to check for null.DataSet has a structure of both String Integer and Bigdecimal data types.
How to shorten the condition code? Is there any way? To shorten my code. Thank you.
public void ConfrimData(DataSet data) {
if (StringUtils.isEmpty(data.getA())
|| StringUtils.isEmpty(data.getB())
|| StringUtils.isEmpty(data.getC())
|| StringUtils.isEmpty(data.getD())
|| StringUtils.isEmpty(data.getE())
|| StringUtils.isEmpty(data.getF())
){
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
return;
}
_DataSet
private String A = null;
private Integer B = null;
private String C= null;
private String D = null;
private BigDecimal E= null;
private String F= null;
Well, you could make it slightly less repeaty using streams, but it won't make it necessarily better, let alone faster:
LinkedHashMap<Supplier, String> map = new LinkedHashMap<>();
map.put(data::getA, Var.VALUE_A);
map.put(data::getB, Var.VALUE_B);
map.put(data::getC, Var.VALUE_C);
map.put(data::getD, Var.VALUE_D);
map.put(data::getE, Var.VALUE_E);
map.put(data::getF, Var.VALUE_F);
List<String> logMessages = map.entrySet().stream()
.filter(entry -> StringUtils.isEmpty(entry.getKey().get()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
if (!logMessages.isEmpty()) {
logMessages.forEach(loggerTransaction::info);
}
else {
// Remaining code
}
In your first if statement you check all the parameters to see if any of them are empty.
Then, in the inner if statements, you check them again. The first check is redundant. The return statement is also not necessary since it does not end the method early or returns any data.
Here is a shorter version that should give the same result:
public void confirmData(DataSet data) {
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
}
EDIT
Here is a slightly prettier solution with less code repetition:
public void confirmData(DataSet data) {
logIfEmpty(data.getA(), Var.VALUE_A);
logIfEmpty(data.getB(), Var.VALUE_B);
logIfEmpty(data.getC(), Var.VALUE_C);
logIfEmpty(data.getD(), Var.VALUE_D);
logIfEmpty(data.getE(), Var.VALUE_E);
logIfEmpty(data.getF(), Var.VALUE_F);
}
private void logIfEmpty(Object check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
}
}
EDIT #2
And if you have other code you want to execute if you did not find any empty values, you can do this:
public void confirmData(DataSet data) {
boolean foundEmpty;
foundEmpty = logIfEmpty(data.getA(), Var.VALUE_A);
foundEmpty = logIfEmpty(data.getB(), Var.VALUE_B) || foundEmpty;
foundEmpty = logIfEmpty(data.getC(), Var.VALUE_C) || foundEmpty;
foundEmpty = logIfEmpty(data.getD(), Var.VALUE_D) || foundEmpty;
foundEmpty = logIfEmpty(data.getE(), Var.VALUE_E) || foundEmpty;
foundEmpty = logIfEmpty(data.getF(), Var.VALUE_F) || foundEmpty;
if(foundEmpty) {
return;
}
}
private boolean logIfEmpty(String check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
return true;
}
return false;
}
Maybe assigning a flag...
public void ConfrimData(DataSet data) {
boolean flag;
if (flag = StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (flag = StringUtils.isEmpty(data.getB()) || flag) {
loggerTransaction.info(Var.VALUE_B);
}
if (flag = StringUtils.isEmpty(data.getC()) || flag) {
loggerTransaction.info(Var.VALUE_C);
}
if (flag = StringUtils.isEmpty(data.getD()) || flag) {
loggerTransaction.info(Var.VALUE_D);
}
if (flag = StringUtils.isEmpty(data.getE()) || flag) {
loggerTransaction.info(Var.VALUE_E);
}
if (flag = StringUtils.isEmpty(data.getF()) || flag) {
loggerTransaction.info(Var.VALUE_F);
}
if (flag) return;

javafx Caused by: java.lang.UnsupportedOperationException

when i try to add an "object" to database and then show it to TableView it shows me UnsupportedOperationException . Everything was fine until i add this code to "public void initialize()" to make textfields as "SearchBoxes":
FilteredList <Paisjet> filteredData = new FilteredList<>(data,e -> true);
paisjaSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getPaisja().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
kategoriaSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getKategoria().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
prodhuesiSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getProdhuesi().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
modeliSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getModeli().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
SortedList <Paisjet> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedData);
OUTPUT:
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractList.removeRange(AbstractList.java:571)
at java.util.AbstractList.clear(AbstractList.java:234)
at main.MainWindowController.clearTable(MainWindowController.java:315)
at main.MainWindowController.addToTableFromDatabase(MainWindowController.java:320)
at main.MainWindowController.addToDatabase(MainWindowController.java:309)
... 61 more
clearTable():
public void clearTable()
{
tableView.getItems().clear(); // line 315 at OUTPUT ERROR
}
addToTableFromDatabase():
public void addToTableFromDatabase() throws ClassNotFoundException, SQLException
{
clearTable(); //line 320 at OUTPUT ERROR
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://***.***.**.*:****/*********";
String uname="*****";
String pass="*********";
connect = (Connection) DriverManager.getConnection(url,uname,pass);
Statement statement;
String query = "SELECT * FROM paisjettable" ;
statement = connect.createStatement();
ResultSet rs = statement.executeQuery(query);
while(rs.next())
{
int id = rs.getInt("id");
String prodhuesi = rs.getString("prodhuesi");
String modeli = rs.getString("modeli");
String paisja = rs.getString("paisja");
String pjesa = rs.getString("pjesa");
String infoshtese = rs.getString("infoshtese");
double qmimi = rs.getDouble("qmimi");
double punedore = rs.getDouble("punedore");
double pagesa = rs.getDouble("pagesa");
int sasia = rs.getInt("sasia");
paisjet = new Paisjet(id,prodhuesi,modeli,paisja,pjesa,qmimi,punedore,pagesa,sasia,infoshtese);
data.add(paisjet);
tableView.setItems(data);
}
rs.close();
connect.close();
}
addToDatabase():
public void addToDatabase() throws ClassNotFoundException, SQLException
{
addToDatabaseMethod(count,prodhuesiField.getText(),modeliField.getText(),paisjaField.getText(),pjesaField.getText(),Double.parseDouble(qmimiField.getText()),Double.parseDouble(puneDoreField.getText()),Integer.parseInt(sasiaField.getText()),infoArea.getText());
count++;
prodhuesiField.clear();
modeliField.clear();
paisjaField.clear();
pjesaField.clear();
qmimiField.clear();
puneDoreField.clear();
sasiaField.clear();
infoArea.clear();
addToTableFromDatabase(); // line 309 from OUTPUT ERROR
}
You have set the table view's backing list (items) to a sorted list, which cannot be directly modified (because it is always supposed to be a sorted version of its underlying list). So table.getItems() returns the SortedList and table.getItems().clear() attempts to modify it and throws the exception.
You should modify the underlying list, which you call data in your very first code block. You haven't shown any context for the blocks of code, so it's not clear what the scope of that variable is, but you essentially need data.clear() instead of table.getItems().clear().
(Also, you do not want to call table.setItems(data) in your loop in addToTableFromDatabase, as this will remove the filtering and sorting.)

decision making in java

private Object artikanID(String string) {
try {
DAOTerjemah dao = new DAOTerjemah(ConnectionDB.getConnection()) {};
List<Kata> terjemahan1 = new ArrayList<Kata>();
List<Kata> terjemahan2 = new ArrayList<Kata>();
List<Kata> terjemahan3 = new ArrayList<Kata>();
terjemahan1 = dao.getByIndo(string);
terjemahan2 = dao.getByIndo(string.substring(0,string.length()-1));
terjemahan3 = dao.getByIndo(string.substring(0,string.length()-2));
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else {
return terjemahan2.get(0).getDayak();
}
}catch(Exception e){
return string ;
}
}
there are 3 conditions(terjemahan1,terjemahan2 & terjemahan 3),
how to create the conditions to be executed terjemahan3 ?
With an else, but I'm not entirely sure I understand your logic.
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 == null) {
return terjemahan2.get(0).getDayak();
}
else {
return terjemahan3.get(0).getDayak();
}
I think you probably want the opposite though, so you only call this on variables that are not null. In this case you have to decide which one you want to call in preference if they are all not null. Also you have to decide what to do if all of them are null.
if (terjemahan1 != null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 != null) {
return terjemahan2.get(0).getDayak();
}
else if (terjemahan3 != null) {
return terjemahan3.get(0).getDayak();
}
else
{
// decide what to do in this condition
}

validation function problem

Hello
I am not able to get the correct validation.I think there is some error in this code so can anyone please help me solving this problem.
public static boolean validateFee(String value) {
boolean isvalid = true;
try {
int fee = 0;
if (value != null && !value.isEmpty()) {
fee = Integer.parseInt(value);
}
} catch (NumberFormatException ne) {
// ne.printStackTrace();
isvalid = false;
return isvalid;
}
return isvalid;
}
}
I am actaully using this code for validation of fee in which i m using a regex as [0-9]+.
This code i m using it in a common function.Actually validation call is done in the servlet as follows:
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
Boolean isvalid = true;
HashMap hashMap = new LinkedHashMap();
number = ApplicationConstants.FEE_PATTERN;
if (!Validation.validateFee(number)) {
isvalid = false;
hashMap.put("time", props.getText("error.fee.invalid.type"));
}
session.setAttribute("errorMessage", hashMap);
System.out.println("Map size " + hashMap.size());
logger.info("Exit validateTIme"); return isvalid;
}
I think there is no error in that but i have a doubt in this function.I am facing a problem like if i give number to the fee also its taking validation.please help me out
Currently it allows value of null or "" to count as being valid - is that deliberate?
Note that your current code can be rewritten more simply:
public static boolean validateFee(String value) {
try {
if (value != null && !value.isEmpty()) {
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException ne) {
return false;
}
}
Now if you want null/empty to count as invalid, I'd rewrite it as:
public static boolean validateFee(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException ne) {
return false;
}
}
trim your string and then pass it to.
StringUtils.isNumeric(StringUtils.trimToNull(fees));
You can directly use StringUtils.isNumeric()
I recommend you use commons-lang StringUtils class, your validate method is re-written
public static boolean validateFee(String value) {
return StringUtils.isNumeric(StringUtils.trimToNull(value));
}
And you remove ApplicationConstants.FEE_PATTERN completely. The problem you are currently facing is that your servlet overwrites its input value with ApplicationConstants.FEE_PATTERN. Your servlet method is re-written
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
final Boolean valid = Validation.validateFee(number);
if (!valid) {
final HashMap hashMap = new LinkedHashMap();
hashMap.put("time", props.getText("error.fee.invalid.type"));
session.setAttribute("errorMessage", hashMap);
}
}

Categories

Resources