Handle null string in java - java

I am reading CSV file and inserting into table.but when I get completdate as null I want to insert default date.i checked this
if(COMPLETEDATE == null){
css.setString(24, "2013-06-12 00:00:00.0");
}else{
css.setString(24, COMPLETEDATE);
}
Here is the whole function.
public void ImportCSV() {
String csvFile = "C:\\seema\\CSV Files\\2013\\August\\15.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String PRODLINE,EMPID,EMPFNAME,SHIFT,STATIONID,CURWKDATE,OPCODE,OPDESC,STARTWORKTIME,ENDWORKTIME,PIECECNT,
BUNDLECNT,PIECERATE,SAM,SKILLLEVEL,DAILYBONUS,NORMALRATE,OVERTIMERATE,WORKDURATION,MONO,DESIGNCODE,
DESIGNCOLOR,DESIGNSIZE,COMPLETEDATE;
int i=0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
try {
PreparedStatement css = null;
css= conn.prepareStatement("exec uspInsertEWLProduction ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?");
String[] country = line.split(",");
PRODLINE=country[0];
EMPID=country[1];
EMPFNAME =country[2];
SHIFT=country[3];
STATIONID=country[4];
CURWKDATE =country[5];
OPCODE=country[6];
OPDESC=country[7];
STARTWORKTIME =country[8];
ENDWORKTIME=country[9];
PIECECNT=country[10];
BUNDLECNT =country[11];
PIECERATE=country[12];
SAM=country[13];
SKILLLEVEL =country[14];
DAILYBONUS=country[15];
NORMALRATE=country[16];
OVERTIMERATE =country[17];
WORKDURATION=country[18];
MONO=country[19];
DESIGNCODE =country[20];
DESIGNCOLOR=country[21];
DESIGNSIZE=country[22];
COMPLETEDATE =country[23];
if(i!=0) {
css.setString(1, PRODLINE);
css.setString(2, EMPID);
css.setString(3, EMPFNAME);
css.setString(4, SHIFT);
css.setString(5, STATIONID);
css.setString(6, CURWKDATE);
css.setString(7, OPCODE);
css.setString(8, OPDESC);
css.setString(9, STARTWORKTIME);
css.setString(10, ENDWORKTIME);
css.setString(11, PIECECNT);
css.setString(12, BUNDLECNT);
css.setString(13, PIECERATE);
css.setString(14, SAM);
css.setString(15, SKILLLEVEL);
css.setString(16, DAILYBONUS);
css.setString(17, NORMALRATE);
css.setString(18, OVERTIMERATE);
css.setString(19, WORKDURATION);
css.setString(20, MONO);
css.setString(21, DESIGNCODE);
css.setString(22, DESIGNCOLOR);
css.setString(23, DESIGNSIZE);
if(COMPLETEDATE == null) {
css.setString(24, "2013-06-12 00:00:00.0");
} else {
css.setString(24, COMPLETEDATE);
}
}
css.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
JOptionPane.showMessageDialog(null, "Data Imported Successfully");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The problem is else part is never get executed eventhough copmletedate is null. Any solution?

You can use Apache Commons Utility StringUtils.isEmpty(CharSequence) to check for null or empty string. BTW, why are you storing dates as string, and not as date?
if (StringUtils.isEmpty(COMPLETEDATE)) {
// set default date
} else {
// set COMPLETEDATE
}

try changing if statement to:
if(COMPLETEDATE.equals(""))

You may need to check for null and empty string. Something like this:
if(COMPLETEDATE != null && !("".equals(COMPLETEDATE.trim)))
{
css.setString(24, COMPLETEDATE);
}
else
{
css.setString(24, "2013-06-12 00:00:00.0");
}

Use StringUtils.isBlank() which checks for null or empty string.
visit http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

U can do one thing that Compare both thing
if(COMPLETEDATE != null || !("".equals(COMPLETEDATE.trim())))
{
css.setString(intlength, xyz);
}
else
{
css.setString(intlength, "Stringdate");
}
May this will help.
and if u Taking loop then try this.
if(country[23] != null && !(country[23].equals(""))){
// set your date code
}else{
// set String date
}

Related

Checking which parameter is missing from file content

I have a TransferReader class which reads a file containing transfer data from bank account to another using the following form:
SenderAccountID,ReceiverAccountID,Amount,TransferDate
"473728292,474728298,1500.00,2019-10-17 12:34:12" (unmodified string)
Suppose that the file has been modified before being read so that one of the above mentioned paramaters are missing, and I want to check which of those are missing.
"474728298,1500.00,2019-10-17 12:34:12" (modified string)
I am using a BufferedReader to read each line, and then splitting each element into a String[] using String.split(",") as delimeter.
As already realized, because the Sender Account ID and Receiver Account ID are right next to one another within a record there is no real way of knowing which ID might be missing unless a delimiter remains in its' place indicating a Null value. There are however mechanisms available to determine that it is indeed one of the two that is missing, which one will need to be carried out through User scrutiny and even then, that may not be good enough. The other record column fields like Amount and Transfer Date can be easily validated or if missing can be implicated within a specific File Data Status Log.
Below is some code that will read a data file (named Data.csv) and log potential data line (record) errors into a List Interface object which is iterated through and displayed within the Console Window when the read is complete. There are also some small helper methods. Here is the code:
private void checkDataFile(String filePath) {
String ls = System.lineSeparator();
List<String> validationFailures = new ArrayList<>();
StringBuilder sb = new StringBuilder();
// 'Try With Resources' used here to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int lineCount = 0;
// Read the file line-by-line.
while ((line = reader.readLine()) != null) {
line = line.trim();
lineCount++;
if (lineCount == 1 || line.equals("")) {
continue;
}
sb.delete(0, sb.capacity()); // Clear the StringBuilder object
// Start the Status Log
sb.append("File Line Number: ").append(lineCount)
.append(" (\"").append(line).append("\")").append(ls);
// Split line into an Array based on a comma delimiter
// reguardless of the delimiter's spacing situation.
String[] lineParts = line.split("\\s{0,},\\s{0,}");
/* Validate each file line. Log any line that fails
any validation for any record column data into a
List Interface object named: validationFailures
*/
// Are there 4 Columns of data in each line...
if (lineParts.length < 4) {
sb.append("\t- Invalid Column Count!").append(ls);
// Which column is missing...
// *** You may need to add more conditions to suit your needs. ***
if (checkAccountIDs(lineParts[0]) && lineParts.length >= 2 && !checkAccountIDs(lineParts[1])) {
sb.append("\t- Either the 'Sender Account ID' or the "
+ "'ReceiverAccountID' is missing!").append(ls);
}
else if (lineParts.length >= 3 && !checkAmount(lineParts[2])) {
sb.append("\t- The 'Amount' value is missing!").append(ls);
}
else if (lineParts.length < 4) {
sb.append("\t- The 'Transfer Date' is missing!").append(ls);
}
}
else {
// Is SenderAccountID data valid...
if (!checkAccountIDs(lineParts[0])) {
sb.append("\t- Invalid Sender Account ID in column 1! (")
.append(lineParts[0].equals("") ? "Null" :
lineParts[0]).append(")");
if (lineParts[0].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[0].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is ReceiverAccountID data valid...
if (!checkAccountIDs(lineParts[1])) {
sb.append("\t- Invalid Receiver Account ID in coloun 2! (")
.append(lineParts[1].equals("") ? "Null" :
lineParts[1]).append(")");
if (lineParts[1].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[1].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is Amount data valid...
if (!checkAmount(lineParts[2])) {
sb.append("\t- Invalid Amount Value in column 3! (")
.append(lineParts[2].equals("") ? "Null" :
lineParts[2]).append(")").append(ls);
}
// Is TransferDate data valid...
if (!checkTransferDate(lineParts[3], "yyyy-MM-dd HH:mm:ss")) {
sb.append("\t- Invalid Transfer Date Timestamp in column 4! (")
.append(lineParts[3].equals("") ? "Null" :
lineParts[3]).append(")").append(ls);
}
}
if (!sb.toString().equals("")) {
validationFailures.add(sb.toString());
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
// Display the Log...
String timeStamp = new SimpleDateFormat("yyyy/MM/dd - hh:mm:ssa").
format(new Timestamp(System.currentTimeMillis()));
String dispTitle = "File Data Status at " + timeStamp.toLowerCase()
+ " <:-:> (" + filePath + "):";
System.out.println(dispTitle + ls + String.join("",
Collections.nCopies(dispTitle.length(), "=")) + ls);
if (validationFailures.size() > 0) {
for (String str : validationFailures) {
if (str.split(ls).length > 1) {
System.out.println(str);
System.out.println(String.join("", Collections.nCopies(80, "-")) + ls);
}
}
}
else {
System.out.println("No Issues Detected!" + ls);
}
}
private boolean checkAccountIDs(String accountID) {
return (accountID.matches("\\d+") && accountID.length() == 9);
}
private boolean checkAmount(String amount) {
return amount.matches("-?\\d+(\\.\\d+)?");
}
private boolean checkTransferDate(String transferDate, String format) {
return isValidDateString(transferDate, format);
}
private boolean isValidDateString(String dateToValidate, String dateFromat) {
if (dateToValidate == null || dateToValidate.equals("")) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
// If not valid, it will throw a ParseException
Date date = sdf.parse(dateToValidate);
return true;
}
catch (ParseException e) {
return false;
}
}
I'm not exactly sure what your particular application process will ultimately entail but if other processes are accessing the file and making modifications to it then it may be wise utilize a locking mechanism to Lock the file during your particular process and Unlock the file when it is done. This however will most likely require you to utilize a different reading algorithm since locking a file must be done through a writable channel. Using the FileChannel and FileLock classes from the java.nio package could possibly assist you here. There would be examples of how to utilize these classes within the StackOverflow forum.

XPages: how to recycle Domino objects when using a ViewEntryCollection several times?

I tried to find a similar question, but I didn't succeed.
In a bean, I'm looping through a ViewEntryCollection several times, adding or deleting entries. Could someone tell me exactly when these objects should be recycled? I want to be able to reuse the whole collection so I don't want to destroy any objects I might still need.
My code:
public static int FTSearchAll(ViewEntryCollection vec, View vw, String cat, String query) throws NotesException {
...
for (ViewEntry ve = nav.getFirst(); ve != null; ) {
ViewEntry next = nav.getNext(ve);
Document doc = ve.getDocument();
if (doc == null)
continue;
try {
Vector v = session.evaluate(query, doc);
if (v != null && v.size() > 0 && (Double) v.elementAt(0) != 0) {
vec.addEntry(ve, false);
} else {
for (ViewEntry dce = vec.getFirstEntry(); dce != null;) {
ViewEntry dcnext = vec.getNextEntry(dce);
if (dce.getNoteID().equals(ve.getNoteID())) {
vec.deleteEntry(dce);
incinerate(dce);
break;
}
dce = dcnext;
}
}
} catch (NotesException ne) {
} finally {
incinerate(ve, doc);
}
ve= next;
}
As always: thanks!
The rule is quite simple: when a Java object pointing to a Notes C object is about to go onto the garbage heap, .recycle() must have been called.
So you need to do that for all entries inside the loop.
My little rule of thumb: the block (think { ... } ) that created a Notes Java object must call its .recycle() function at the end.
Saves you lot of headaches
I see this, but not completely sure whether I miss something or the code keeps its functionality... :S
for (ViewEntry ve = nav.getFirst(); ve != null; ) {
ViewEntry next = nav.getNext(ve);
Document doc = ve.getDocument();
if (doc == null) {
incinerate(ve); // << new
ve = next; // << new
continue;
}
try {
Vector v = session.evaluate(query, doc);
if (v != null && v.size() > 0 && (Double) v.elementAt(0) != 0) {
vec.addEntry(ve, false);
} else {
for (ViewEntry dce = vec.getFirstEntry(); dce != null;) {
ViewEntry dcnext = vec.getNextEntry(dce);
if (dce.getNoteID().equals(ve.getNoteID())) {
vec.deleteEntry(dce);
incinerate(dce, dcnext); // << new
break;
}
incinerate(dce); // << new
dce = dcnext;
}
}
} catch (NotesException ne) {
} finally {
incinerate(ve, doc);
}
ve = next;
}
Maybe it would be better to check another implementation.
Anyway, I recommend you to use the OpenNTF Domino API and get rid of recycle, and you will get also a proper iteration over entries:
http://www.openntf.org/main.nsf/project.xsp?r=project/OpenNTF%20Domino%20API

Splitting a List<string> on the basis of comman ( ,) delimiter and handling NUmberformat exception

I have the following method applyIncentives which takes ListlstIds
public void applyIncentives(List<String> lstIds) throws Exception {
Session session = null;
Transaction tx = null;
String pricingTierId = null;
if (lstIds != null && lstIds.size() > 0) {
for (String lstpricingTierIds : lstIds) {
pricingTierId = lstpricingTierIds.trim();
}
}
try {
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from customer.apply_incentives(:pricingTierId)");
query.setString("pricingTierId", pricingTierId);
query.list();
tx.commit();
approveFlag = true;
}
catch (Exception ex) {
log.error("Exception", ex);
}
finally {
if (session != null)
session.close();
}
return approveFlag;
}
I'm passing the pricingTierId from lstIds and passing to the stored proc which accepts an Integer.
While debugging the value of lstIds is "52512,85822" two pricingTierId's separated by comma (,).
Before passing the pricingTierId to the stored Proc I have written the following:
String pricingTierId = null ;
if (lstIds != null && lstIds.size() > 0) {
for (String lstpricingTierIds : lstIds) {
pricingTierId = lstpricingTierIds.trim();
}
}
My questions:
How to split the pricingTierId by delimited comma (,)?
Since I'm passing List List<String> lstIds I can't use pricingTierId = lstpricingTierIds.trim().split(",") directly.
If I change String pricingTierId = null to String[] pricingTierId then
I have error at query.setString("pricingTierId", pricingTierId);
If I use query.setInteger("pricingTierId", Integer.parseInt(pricingTierId)); then I get Numberformat Exception since comma(,) gets passed to the stored proc.
Added the code as suggested
List<String> pricingTierId = null;
if (lstIds != null && lstIds.size() > 0) {
for(String lstpricingTierIds : lstIds) {
pricingTierId = Arrays.asList(lstpricingTierIds.trim().split(","));
}
}
However I'm getting the error at:
query.setString("pricingTierId", pricingTierId);
setString cannot be used for String[]
and I cannot use query.setInteger("pricingTierId", Integer.parseInt(pricingTierId));
as it says change the type of pricingTierId to String.
How about getting it out of the array created from a split and then loop around:
String[] pricingTierIdArray = lstpricingTierIds.trim().split(",");
for(String s : pricingTierIdArray ) {
query.setInteger("pricingTierId", Integer.parseInt(s));
}
The setInteger() method would overwrite the previous value. Unless you change the query only one id can be set.
Or simply just:
String pricingTierIdArray = lstpricingTierIds.trim().split(",")[0]; //This depends on whether you need both values or not.

Unreachable statement return in java

I have a method what return a list, but when i run the code, appears Unreachable statement
this method come from a aidl file and generate a map with the return.
code bellow:
List<String> list = new ArrayList<String>();
Public List<String> setMethod(Map map) {
ContentValues cv = null;
Iterator i = map.keySet().iterator();
Iterator j = map.values().iterator();
if(map.isEmpty() || map == null) {
return null;
} else {
try {
while(i.hasNext()) {
String str = (String) i.next();
Long l = (Long) j.next();
list.add(str);
cv.put(Storage.STR, str);
if(Provider.insert(Storage.Table, cv) < 0) {
return null;
}
}
if(list.isEmpty() || list == null) {
return null;
} else {
return mPathList;
}
} catch (Exception e) {
return null;
}
return list;
}
Anybody can give me a light what i can make for dolve it?
You are returning from try block as well as catch, so the last return statement will never be reached.
Your code has multiple return paths. You are returning from first if statement if your condition is met, in else part you have try block. In try you are returning based on if as well as else, so if no exception occurs you are guaranteed to return from try block, in case of exception you have a catch statement and you are returning from there as well. So there is no possibility that your code will continue further. Hence the last return statement is unreachable.
Just follow through your code. The last return statement will never be run because every other branch before that leads to an other return statement.

android java code error

I am creating a keyboard but there is some error in local variable usage.
private void updateCandidateText(){
try{
ExtractedText r= getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(),InputConnection.GET_EXTRACTED_TEXT_MONITOR);
String strbeforeCursor="";
String strafterCursor ="";
strbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(1000000000, 0).toString();
strafterCursor = getCurrentInputConnection().getTextAfterCursor(1000000000, 0).toString();
String str = strbeforeCursor + "|"+strafterCursor;
if(mTamilPreviewView != null)
mTamilPreviewView.update(str, strbeforeCursor.length());
mTamilPreviewView.update(r.text.toString() , 0);
}
catch (Exception e) {
Log.e("t", "errr", e);
}
}
You test if mTamilPreviewView != null to call
mTamilPreviewView.update(str, strbeforeCursor.length());
but even if it's null, you'll do
mTamilPreviewView.update(r.text.toString() , 0);
and you'll get a NullPointerException. Is it really what you want to do? Don't you mean
if (mTamilPreviewView != null) {
mTamilPreviewView.update(str, strbeforeCursor.length());
mTamilPreviewView.update(r.text.toString() , 0);
}
Moreover, you initialize strbeforeCursor and strafterCursor with an empty string, and you give them other values at the next lines. You could simply remove
String strbeforeCursor="";
String strafterCursor ="";
and do
String strbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(1000000000, 0).toString();
String strafterCursor = getCurrentInputConnection().getTextAfterCursor(1000000000, 0).toString();

Categories