Issue in loop getting the value - java

I am having an issue in getting the data in the below loop ,even though the size is not zero i am getting null in the sysout 'data is'.What is wrong there ?
List<Long> dd = domainItemMapper.getIsSearchable(34372);
System.out.println("the test is-" + dd.size());
for (int i = 0; i < dd.size(); i++) {
Long isSearch = dd.get(i);
System.out.println("data is"+dd.get(i));
if (isSearch.equals(0)) {
isSearchValue = false;
} else
isSearchValue = true;
}
The call to database is a mybatis call as below
interface
List<Long> getIsSearchable(#Param("parentFieldId") long parentFieldId);
impl
<mapper namespace="com.ge.dbt.common.persistence.IFormValidatorMapper">
<select id="getIsSearchable" statementType="CALLABLE"
resultType="Long">
select is_searchable from t_field where parent_field_id=#{parentFieldId}
</select>
</mapper>

I guess your whole code can be converted in to two lines.
if(dd!= null && !dd.isEmpty())
return dd.contains(0);//Contains Guard you in such cases because equals check
//happen on passed element ie *0*
Default value of Long in java is null. So you will need additional check for null in your case.

Enclose your isSearch.equals check in a null check
if(isSearch != null)
{
if (isSearch.equals(0))
{
isSearchValue = false;
}
else
{
isSearchValue = true;
}
}
However it'll be better to modify code for domainItemMapper.getIsSearchable(34372); method so that it doesn't fill the list with null at all.

Seems to be your list contains null literals. And List Supports null as a value.

based on your this comment
The data has null,0 and 1 data.I want to return data only for 0 and 1.
You need to fix your query like this
select is_searchable from t_field where parent_field_id=#{parentFieldId} and is_searchable is not NULL;

Related

Append Criteria query to previous query in Hibernate

I have a String array named andOrButtonFilter which stores and or filters selected by user.
Also two ArrayList named column and value storing column names and their values respectively.
I want the current query to append to the previous query and show the results
But my query is not being appended to the previous query, it is showing individual results.
For eg:
if name=xyz is first query and
age=26 is second query
It does not results with name=xyz and age=26 . It is only showing results for age=26 when executed for the second time.
Where am I going wrong?
This is the code I am using at the moment:
for (int i=0; i<andOrButtonFilter.length; i++)
{
if(andOrButtonFilter[i]=="and")
{
Conjunction conjunction =Restrictions.conjunction();
if ((column.get(i) != null) && (value.get(i)!=null))
{
conjunction.add(Restrictions.or(Restrictions.eq(column.get(i), value.get(i))));
criteriaQuery.add(conjunction);
}
}
else if(andOrButtonFilter[i]=="or")
{
Disjunction disjunction =Restrictions.disjunction();
if ((column.get(i) != null) && (value.get(i)!=null))
{
disjunction.add(Restrictions.or(Restrictions.eq(column.get(i), value.get(i))));
criteriaQuery.add(disjunction);
}
}
else
{
criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
I can find a few problems with you code.
1) You compare strings with == instead of equals. So your code always goes into the last section criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
2) In your conjunction/disjunction code you still use Restrictions.or which is kind of wrong. You don't even need Restrictions.or or Restrictions.and because Conjunction is adding the restrictions with AND anyway and Disjunction is adding with OR anyway.
3) On each iteration you add separate disjunction which is basically a single criterion and won't work as you expect.
I would try with something like:
Disjunction disjunction =Restrictions.disjunction();
Conjunction conjunction =Restrictions.conjunction();
for (int i=0; i<andOrButtonFilter.length; i++)
{
if("and".equals(andOrButtonFilter[i]))
{
if ((column.get(i) != null) && (value.get(i)!=null))
{
conjunction.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
else if("or".equals(andOrButtonFilter[i]))
{
if ((column.get(i) != null) && (value.get(i)!=null))
{
disjunction.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
else
{
criteriaQuery.add(Restrictions.eq(column.get(i), value.get(i)));
}
}
criteriaQuery.add(conjunction);
criteriaQuery.add(disjunction);
I am not saying that exact code will work because I haven't tested it ;) but you get the idea and you can debug from there.

Reduce the complexity from code

I am using below code and used two continue statement depending on some logic but sonar list showing this issue Reduce the total number of break and continue statements in this loop to use at most one.
How to resolve this issue?
for (HashMap<String, String> objRequestIdVO : pObjTicketId) {
List<TicketDetailsDO> objTicketDetailslist = storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId"));
if (null == objTicketDetailslist || objTicketDetailslist.isEmpty()) {
continue;
}
Integer iDesiredDsicount = objTicketDetailslist.get(0).getDesiredDiscount();
String iSubDept = objTicketDetailslist.get(0).getSubdeptTicket().getSubDeptId();
List<MCouponDO> objMCounponList = storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept);
if (null == objMCounponList || objMCounponList.isEmpty()) {
continue;
}
String strHeader = objMCounponList.get(0).getHeader();
objHeaderVO = new HeaderVO();
objHeaderVO.setHeader(strHeader);
objHeaderVO.setRequestId(objRequestIdVO.get("requestId"));
objHeaderVOList.add(objHeaderVO);
}
Change the null check continue, to not null check and proceed. The code will be executed only if the not null check passes, which is same as saying continue if null.
for (HashMap<String, String> objRequestIdVO : pObjTicketId) {
List<TicketDetailsDO> objTicketDetailslist = storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId"));
if (!(null == objTicketDetailslist || objTicketDetailslist.isEmpty())) {
Integer iDesiredDsicount = objTicketDetailslist.get(0).getDesiredDiscount();
String iSubDept = objTicketDetailslist.get(0).getSubdeptTicket().getSubDeptId();
List<MCouponDO> objMCounponList = storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept);
if (!(null == objMCounponList || objMCounponList.isEmpty()) {
String strHeader = objMCounponList.get(0).getHeader();
objHeaderVO = new HeaderVO();
objHeaderVO.setHeader(strHeader);
objHeaderVO.setRequestId(objRequestIdVO.get("requestId"));
objHeaderVOList.add(objHeaderVO);
}
}
}
You could use streams replacing the continues with filters.
pObjTicketId.stream()
.map(m-> m.get("requestId"))
.map(reqId ->
Optional.ofNullable(storeManagerDao.getTicketDetailsWithTicketId(reqId))
.filter(l->!l.isEmpty())
.map(l->l.get(0))
.map(ticketDetails->
storeManagerDao.getMcouponData(ticketDetails.getDesiredDiscount(),
ticketDetails.getSubdeptTicket().getSubDeptId())
)
.filter(Objects::nonNull)
.filter(l->!l.isEmpty())
.map(l->l.get(0))
.map(couponDo-> {
HeaderVO headerVO = new HeaderVO();
headerVO.setHeader(couponDo.getHeader());
headerVO.setRequestId(oreqId);
return headerVO;
})
)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
You have a bigger problem than fixing Sonar warning if calls - storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId")) & storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept) are about making DB calls.This is a big performance point and one should - Never ever make DB calls from within a loop, this is far more dangerous than multiple continue & break statements
So I would first restructure your DAO call - storeManagerDao.getTicketDetailsWithTicketId to run IN sql query for a bunch of objRequestIdVO.get("requestId") in one go , outside your main loop & produce a Map<String,List<TicketDetailsDO>> ...that will automatically get rid of your first if .
Next you repeat same process for constructing a Map<String,List<MCouponDO> objMCounponList> by iterating previous map Map<String,List<TicketDetailsDO>> where key of this map is something like - iDesiredDsicount|iSubDept .
This way you will have two disconnected loops and only two DB calls & your Sonar warning gets automatically solved on the way.

Using if statement to prevent "java.lang.IndexOutOfBoundsException"

I'm using a method that returns a list that is fetched from a web service. This list sometimes does not contain anything. Which results in "java.lang.IndexOutOfBoundsException"
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
I have used the if statement above to prevent the exception, but it does not work. Is there anyway I can prevent this Exception by using if statements so the program do something else in case the list is empty?
If you want to ensure the list is not null, and, contains at least two elements, do this:
if( placesList != null && placesList.size() >= 2)
The list could be defined, but have no strings in it (an empty list). You should also check the size of the list:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.size() > 1)
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
The list object is not null, but the contents inside can be zero
Use placeList.size() to check the number of contents inside.
If ArrayList == null returns true it doesn't mean that it's empty, it means that it hasn't been initialized and it points to null.
In order to check if your list is empty, you can use
if (!placesList.isEmpty()){
}
Just because the ArrayList object is not null, does not imply there are any elements in it.
You can call isEmpty() or size() methods to determine if there are any elements in the array.
Try this:
ArrayList<String> placesList = osm.getPlace(poi, listingCity, listingState);
if (placesList != null && placesList.isEmpty() == false )
{
poi = placesList.get(0);
poiStreet = placesList.get(1);
}
Javadoc reference
Check to make sure the ArrayList is not null, then add a second condition ensuring the size is equal to 2 to ensure it contains what you expect
if (placesList != null && placesList.size() == 2)
Try
if (placeList.size() > 1)
you should check length of the arraylist.
something like
if (placesList.size() > 0)
One way to approach this is by:
if(placesList.isEmpty())
{
//do something here when empty
}
else
{
poi = placesList.get(0);
}

Returning a null array string in java

I am having a java class where I am executing a query and assigning the query result to an string array, finally return the array.
Everything works fine. But I want to return "no data" if the db values are empty (not the whole array). what can I do for this?
Code:
query="select `t1`,`t2`,`t3` from test";
PreparedStatement pre = conn.prepareStatement(query);
ResultSet res = pre.executeQuery();
String val[][] = new String[res.getRow()][3];
while (res.next()) {
val[i][0] = res.getString(1);
val[i][1] = res.getString(2);
val[i][2] = res.getString(3);
i++;
}
res.close();
conn.close();
pre.close();
return (val);
(Where I want the val[1][1] to be "No Data" if res.getString(2) is null).
No Data seems to be a value you display more than a logical value.
So you should decide of a special value and display it in a special way. We usually call this a sentry value.
This value could be null or a string that can't be in your db. (maybe it doesn't apply here as everything is often possible in a db).
Also note that it could be attractive to use an exception instead of this special value but it is actually a very poor use of exceptions, mostly for performance issues and hence it is a design to avoid if possible except if this value can lead to problems for your clients classes.
try this way
val[i][0] = (res.getString(1)!=null & !res.getString(1).equals(""))?res.getString(1).equals(""):"No Data";
val[i][1] = (res.getString(1)!=null & !res.getString(2).equals(""))?res.getString(3).equals(""):"No Data";
val[i][2] = (res.getString(1)!=null & !res.getString(3).equals(""))?res.getString(3).equals(""):"No Data";
use the only one "&" what happen when you check the condition with && first it will check for the first i.e. rs.getString(1)!=null if this is null or not it will check for the another condition i.e. rs.getString(1).equal("") so if you check and it will null then in second condition it will cause the error for NullPointerException.
while if you use only one & then it will check first condition if that was true then only it go for check the another condition otherwise not.
Add small helper methods like this:
public static String getValue(String value) {
return getValue(value, "No Data");
}
public static String getValue(String value, String default) {
return value == null ? default : value;
}
Use it like this:
val[i][0] = getValue(res.getString(1)); // standard
val[i][0] = getValue(res.getString(1), "NULL"); // with custom default message

LinkedList Iteration Exception

I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null

Categories

Resources