validation function problem - java

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);
}
}

Related

Common method for null check

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);

Fetch HTML part in java

I have some troubles understanding how can I download only part of html page. I tryed traditional way through URL::openStream method and BufferedReader but I'm not quite sure if this way pushes me to download whole page.
The problem is: I have quite big HTML page and I need to parse 2 numbers from it, which updating at least once a second. Way above helps to detect changes once in 2-3 seconds and I wonder if there is way to make it faster. So I thought if fetching page partly can help me.
Wrote helper to read url content. Parser for elements in another class.
public class HTMLReaderHelper {
private final URL currentURL;
HTMLReaderHelper(URL url){
currentURL = url;
}
public CharIterator charIterator(){
CharIterator iterator;
try {
iterator = new CharIterator();
} catch(IOException ex){
return null;
}
return iterator;
}
public StringIterator stringIterator(){
return new StringIterator();
}
class CharIterator implements java.util.Iterator<Character>{
private InputStream urlStream;
private boolean isValid;
private Queue<Character> buffer;
private CharIterator() throws IOException {
urlStream = currentURL.openStream();
isValid = true;
buffer = new ArrayDeque<>();
}
#Override
public boolean hasNext() {
char c;
try {
c = (char)urlStream.read();
buffer.add(c);
} catch (IOException ex) {
markInvalid();
return false;
}
return c != (char) -1;
}
#Override
public Character next() {
if(!isValid){
return null;
}
char c;
try {
if(buffer.size() > 0){
return buffer.remove();
}
c = (char)urlStream.read();
} catch (IOException ex) {
markInvalid();
return null;
}
return (c != (char)-1) ? c : null;
}
private void markInvalid(){
isValid = false;
}
}
class StringIterator implements java.util.Iterator<String>{
private CharIterator charPointer;
private Queue<String> buffer;
private boolean isValid;
private StringIterator(){
charPointer = charIterator();
isValid = true;
buffer = new ArrayDeque<>();
}
#Override
public boolean hasNext() {
String value = next();
try {
buffer.add(value);
} catch (NullPointerException ex){
markInvalid();
return false;
}
return isValid;
}
#Override
public String next() {
if(buffer.size() > 0){
return buffer.remove();
}
if(!isValid){
return null;
}
StringBuilder sb = new StringBuilder();
Character currentChar = charPointer.next();
if(currentChar == null){
return null;
}
while (currentChar.equals('\n') || currentChar.equals('\r')){
currentChar = charPointer.next();
if(currentChar == null){
return null;
}
}
while (currentChar != Character.valueOf('\n') && currentChar != Character.valueOf('\r')){
sb.append(currentChar);
currentChar = charPointer.next();
}
return sb.toString();
}
private void markInvalid(){
isValid = false;
}
}
}
I think you should see how the data is fetched (SSE or WebSocket) and just try to subscribe to that service. If that is impossible try more efficient XML parser. I recommend https://vtd-xml.sourceforge.io/ it can be ~10x faster then DOM parser that comes with JDK.
Also be careful with the BufferedReader.readLine() as there is a hidden cost of allocation (this is pretty advanced stuff as you have to think about CPU memory bandwidth, L1 cache misses etc..) for the strings that you don't really need.
Example using the library I mentioned:
byte[] pageInBytes = readAllBytesFromTheURL();
VTDGen vg = new VTDGen();
vg.setDoc(pageInBytes);
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
//Jump to the section that we want to process
ap.selectXPath("/html/body/div");
String fileId = vn.toString(vu.getElementFragment());

Possible logic issue adding an object to an arraylist

My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {

Recursive function not working for to get innermost exception message

I have written this method
private string FindInnerExceptionMessage(Exception ex)
{
string exceptionMsg = string.Empty;
if (ex.InnerException == null)
{
exceptionMsg = ex.Message;
}
else
{
ex = ex.InnerException;
FindInnerExceptionMessage(ex);
}
return exceptionMsg;
}
However, after that FindInnerExceptionMessage it is stepping to return exceptionMsg and not logging the exact exception message
You don't actually assign the return value of your recursive call to anything. As a result, your first call will return String.Empty because the value of FindInnerExceptionMessage(ex.InnerException) is never assigned as the return value (unless the exception passed to the first call has no inner exception, in which case it will work). Try something like this:
private string FindInnerExceptionMessage(Exception ex)
{
string exceptionMsg = string.Empty;
if (ex.InnerException == null)
{
exceptionMsg = ex.Message;
}
else
{
exceptionMsg = FindInnerExceptionMessage(ex.InnerException);
}
return exceptionMsg;
}

Junit: unexpected invocation after upgrading MyBatis to 3.1.1

Scenario:
final CatalogRuleExample example = new CatalogRuleExample();
example.createCriteria().andCatalogIdEqualTo(catalogId);
example.setOrderByClause("position ASC");
final List<CatalogRuleRecord> records = new ArrayList<CatalogRuleRecord>();
final CatalogRuleRecord firstRecord = new CatalogRuleRecord();
final CatalogRuleRecord secondRecord = new CatalogRuleRecord();
records.add(firstRecord);
records.add(secondRecord);
mockery.checking(new Expectations() {
{
oneOf(catalogRuleDAO).selectByExample(example);
will(returnValue(records));
...
Problem:
The final example of CatalogRuleExample is not the same in my mockery.checking by selectByExample. If i override the equals() it will work. But i wanted to know, if there is a better solution for this case. Thanks in advance
PS: this same code worked bevor i migrate from Ibatis to Mybtis
final CatalogRuleExample example = new CatalogRuleExample() {
#Override
public boolean equals(Object that) {
if (that instanceof CatalogRuleExample) {
CatalogRuleExample other = (CatalogRuleExample) that;
if (other.getOredCriteria().size() != 1) {
return false;
}
if (other.getOredCriteria().get(0).getCriteria().size() != 1) {
return false;
}
if (!other.getOredCriteria().get(0).getCriteria().get(0).getValue().equals(catalogId)) {
return false;
}
if (!other.getOrderByClause().equals("position ASC")) {
return false;
}
return true;
}
return false;
}
};
ERROR:
unexpected invocation: catalogRuleDAO.selectByExample(<com.protogo.persistence.dao.CatalogRuleExample#a6ca0ea9>)
expectations:
expected once, never invoked: catalogRuleDAO.selectByExample(<com.protogo.persistence.dao.CatalogRuleExample#66e1beb1>); returns <[com.protogo.persistence.data.CatalogRuleRecord#4f7d02c2, com.protogo.persistence.data.CatalogRuleRecord#4f7d02c2]>

Categories

Resources