Operators in a table - java

There are 7 rows of output for table, how can I modify this so row 6 displays either of the three providers.
I tried something like this :
template.getProvider2() != null || template.getProvider3() != null ||
template.getProvider1() != null ?
template.getProvider2().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "",
which gives me an error of StringBuilder not accepting the OR operator,
I'd appreciate any help on this.
Thanks
Here is my code:
public GetEmailTemplatesResponse getEmailTemplates() throws Exception {
StringBuilder stringBuilder = new StringBuilder();
String tableRow = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
Map<String, EmailTemplate> templates = templateRedisCacheReader.getTemplatesByCacheType(CacheType.EMAIL_TEMPLATE);
templates.values()
.forEach(template -> stringBuilder.append(String.format(tableRow,
template.getTemplateId(),
template.getProvider1() != null ? template.getProvider1().getId() : "",
template.getProvider2() != null ? template.getProvider2().getId() : "",
template.getProvider3() != null ? template.getProvider3().getId() : "",
template.getEnv(),
template.getProvider2() != null ? template.getProvider2().getBusinessUnit(): "", // <--
template.getPriority()))
);
I tried to check if all the providers are null and if one of them is not null , then display bussiness unit for that provider

There's a function commonly used in SQL that returns the first non-null parameter called "coalesce". You could write a Java equivalent of that.
Object coalesce(Object... objects) {
for (Object obj : objects) {
if(obj != null) return obj;
}
return null;
}
...
Provider firstNonNullTemplate=(Provider) coalesce(template.getProvider1(), template.getProvider2(), template.getProvider3());

Related

How to get null and filled values from database using hibernate

I am using hibernate to get data from oracle.I have Criterion object to make filter for hibernate select like this
Criterion cr6=null;
if(reqrrn != null)
{
cr6=Restrictions.eq("rrn", reqrrn);//o
}
else{
cr6=Restrictions.like("rrn", "",MatchMode.ANYWHERE);
}
Criterion cr20=null;
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
}
criteria.add(Restrictions.and(cr6, cr20));
i have filters like this, but it is usseless when value is null, for example
cardPrefix value is null in database i want to get all values for cardPrefix ,which are filled and null too, how can i do this ?
i solved it. it will be for all parameters like
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
cr1=Restrictions.isNull("prefix");
cr20=Restrictions.or(cr20, cr1);
}

How to remove Cyclomatic complexcity

I am getting Cyclomatic complexity (The Cyclomatic Complexity of this method "mapRow" is 13 which is greater than 10 authorized) from below code :
public RedemptionReport mapRow(ResultSet rs, int row) throws SQLException {
RedemptionReport redemptionReport = new RedemptionReport();
redemptionReport.setRedeemDate(rs.getString(1));
redemptionReport.setCashierID(rs.getString(2) != null? rs.getString(2) : "");
redemptionReport.setTillNo(rs.getString(3) != null? rs.getString(3) : "");
redemptionReport.setReferenceNumber(rs.getString(4) != null? rs.getString(4) : "");
redemptionReport.setTransactionNumber(rs.getString(5) != null? rs.getString(5) : "");
redemptionReport.setRedemptionAmount(rs.getString(6) != null? rs.getString(6) : "0");
redemptionReport.setNetBillValues(rs.getString(7) != null? rs.getString(7) : "0");
redemptionReport.setStoreCode(rs.getString(8) != null? rs.getString(8) : "");
redemptionReport.setCardNumber(rs.getString(9) != null? rs.getString(9) : "");
redemptionReport.setCardType(rs.getString(10) != null? rs.getString(10) : "");
redemptionReport.setStoreDesc(rs.getString(11) != null? rs.getString(11) : "");
redemptionReport.setZoneDesc(rs.getString(12) != null? rs.getString(12) : "");
redemptionReport.setMobileNo(rs.getString(13) != null? rs.getString(13) : "");
redemptionReport.setSchemeName(rs.getString(14));
return redemptionReport;
}
How to remove this complexity from the above code?
Create a method that will encapsulate the ternary operator, e.g.:
private String get(String val, String def) {
return val != null ? val : def
}
Or even simpler:
private String get(String val) {
return val != null ? val : ""
}
override RedemptionReport's setters. This should belong to domain class as the default values makes sense only in RedemptionReport class.
Pass "rs.getString(x)" value to the setter method.
public RedemptionReport mapRow(ResultSet rs) throws SQLException {
RedemptionReport redemptionReport = new RedemptionReport();
redemptionReport.setRedeemDate(this.getResultFromResultSet(rs.getString(1)));
redemptionReport.setCashierID(this.getResultFromResultSet(rs.getString(2)));
redemptionReport.setTillNo(this.getResultFromResultSet(rs.getString(3)));
redemptionReport.setReferenceNumber(this.getResultFromResultSet(rs.getString(4)));
redemptionReport.setTransactionNumber(this.getResultFromResultSet(rs.getString(5)));
redemptionReport.setRedemptionAmount(this.getResultFromResultSet(rs.getString(6)));
redemptionReport.setNetBillValues(this.getResultFromResultSet(rs.getString(7)));
redemptionReport.setStoreCode(this.getResultFromResultSet(rs.getString(8)));
redemptionReport.setCardNumber(this.getResultFromResultSet(rs.getString(9)));
redemptionReport.setCardType(this.getResultFromResultSet(rs.getString(10)));
redemptionReport.setStoreDesc(this.getResultFromResultSet(rs.getString(11)));
redemptionReport.setZoneDesc(this.getResultFromResultSet(rs.getString(12)));
redemptionReport.setMobileNo(this.getResultFromResultSet(rs.getString(13)));
redemptionReport.setSchemeName(this.getResultFromResultSet(rs.getString(14)));
return redemptionReport;
}
define another private message to do such work(Null Check and return default value).
private String getResultFromResultSet(String val){
return val != null ? val : "";
}

Java String appending with comma as a separator

I have a requirement where I need to append multiple values from multiple web service calls into one final string with comma as a separator.
Some of the values might be null, in that case I need to check for not null and then append it as empty string.
If there is no value for one of the string, comma should not get appended.
Please help me resolving this. here is the code what I did.
StringBuilder sb = new StringBuilder();
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
logger.info("usersList.totalCount ----->"
+ usersList.totalCount);
for (KalturaUser user : usersList.objects) {
if (user.id != null) {
sb.append(userId);
}
if (user.firstName != null) {
sb.append(",").append(userFirstName);
}
if (user.lastName != null) {
sb.append(",").append(user.lastName);
}
if (user.email != null) {
sb.append(",").append(user.email);
}
if (user.roleNames != null) {
sb.append(",").append(user.roleNames);
}
if (user.partnerData != null) {
sb.append(",").append(user.partnerData);
}
}
System.out.println(sb);
}
Thanks,
Raji
I think you are looking for something like this:
public static String asString(Object value) {
return value == null ? "" : value.toString();
}
for (KalturaUser user : usersList.objects) {
sb.append(asString(user.id));
sb.append(",").append(asString(user.firstName));
sb.append(",").append(asString(user.lastName));
sb.append(",").append(asString(user.email));
sb.append(",").append(asString(user.roleNames));
sb.append(",").append(asString(user.partnerData));
}
Well, in your tests like
if (user.id != null) {
sb.append(userId);
}
you are checking user.id but appending userId. These are two different variables.
You should probably change it into
if (user.id != null) {
sb.append(user.id); //instead of sb.append(userId);
}
It is not clear what your problem is, but if you are looking for a better or different approach, I found that it is best to append to a List<String> and then use StringUtils.join to produce the final string.
You can use a class from a google library called Joiner.
String concatenedString = Joiner.on(",").skipNulls().join(itemToAdd);
You can find this class on google-collections-1.0.jar
I would do something like that. It's based on Java8 streams, but here you don't need to do the non-null check on every property(.filter does this for you). I assumed that users.object is an array list, if it's not you might need to convert it into stream in other way
if (userList.totalCount > 0) {
logger.info("usersList.totalCount ----->" + usersList.totalCount);
String result = userList
.objects
.stream()
.map(user -> {
return Stream.of(user.firstName, user.id, user.lastName, user.email, user.roleNames, user.partnerData) //get the properties you need into the stream
.filter(property -> property != null) // filter out null properties
.collect(Collector.joining(",")); //join them by comma
})
.collect(Collector.joining(",")); //join user strings with comma
System.out.println(result);
}

if (specialmarkId != null) {.....} got ignored

I am using auto generated JPAController of Netbeans 8 using Java 1.8.
public void create(Physical physical) {
if (physical.getTalentCollection() == null) {
physical.setTalentCollection(new ArrayList<Talent>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Specialmark specialmarkId = physical.getSpecialmarkId();
System.out.println(specialmarkId+ "...nullValue");
if (specialmarkId != null) {
System.out.println(specialmarkId+ "...ain't right");
specialmarkId = em.getReference(specialmarkId.getClass(), specialmarkId.getId());
physical.setSpecialmarkId(specialmarkId);
}
.....
}
During physical object creation, Specialmark (part of physical object) is an optional.
It can have a value or be null.
Specialmark in the table physical allows you to have null values.
When Specialmark is null, the if (specialmarkId != null) {...} should skipped. Instead, it got ignored and proceed.
the error message is
"... An instance of a null PK has been incorrectly provided for this find operation.
at db.jpa.PhysicalJpaController.create(PhysicalJpaController.java:57)"
System.out.println(specialmarkId+ "...nullValue");
output "null...nullValue" it shows specialmarkId value is null
System.out.println(specialmarkId+ "...ain't right");
Output "null...ain't right" shows if (specialmarkId != null) {...} has been ignored even specialmarkId is null.
Why does (specialmarkId != null) {...} not work?
I guess specialmarkId is not really null, but specialmarkId.toString() is overwriten for it to return the string "null".
Instead of
System.out.println(specialmarkId+ "...nullValue");
try something like
System.out.println((specialmarkId != null?
specialmarkId.toString() + "(not null)": "(this IS REALLY NULL)")
+ "...nullValue");

java.lang.NullPointerException ERROR

I'm getting this null error on this line but I'm doing an if check and setting an empty string if null. Am I doing this wrong?
java.lang.NullPointerException
at form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM
Code:
public int show(Action action) throws Exception
{
HttpServletRequest request = action.getRequest();
String[] params;
if (!isEmpty(params[0]))
{
String teamNumber= params[0];
TeamBean teamBean = DAO.getTeamDAO().getTeamByNumber(Long.parseLong(teamNumber));
Fake form = new fakeForm();
form.setMoor(teamBean.getHeader().getMoor());
form.setDoor(Double.toString(teamBean .getDoors()));
form.setURC(Double.toString(teamBean.getURCS()));
form.setUMC(Double.toString(teamBean.getUMCSt()));
form.setWeek(Long.toString(teamBean.getHead().getWeek().getnow())); //WEEK
ERROR HERE -->> form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM
For clarity, this is the expression that gives you the NullPointerException:
teamBean.getHead().getNone().getCode()
You aren't checking if getNone returns null.
You get it because teamBean.getHead().getNone() is null. And since you're calling getCode() on this null value, you get a NullPointerException.
Note that
form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : "");
could be rewritten as
form.setSac("");
(except you wouldn't have the NullPointerException)

Categories