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 : "";
}
Related
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());
JSONObject jsonObj = {"a":"1","b":null}
CASE 1 : jsonObj.getString("a") returns "1";
CASE 2 : jsonObj.getString("b") return nothing ;
CASE 3 : jsonObj.getString("c") throws error;
How to make case 2 and 3 return null and not "null"?
You can use get() instead of getString(). This way an Object is returned and JSONObject will guess the right type. Works even for null.
Note that there is a difference between Java null and org.json.JSONObject$Null.
CASE 3 does not return "nothing", it throws an Exception. So you have to check for the key to exist (has(key)) and return null instead.
public static Object tryToGet(JSONObject jsonObj, String key) {
if (jsonObj.has(key))
return jsonObj.opt(key);
return null;
}
EDIT
As you commented, you only want a String or null, which leads to optString(key, default) for fetching. See the modified code:
package test;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
// Does not work
// JSONObject jsonObj = {"a":"1","b":null};
JSONObject jsonObj = new JSONObject("{\"a\":\"1\",\"b\":null,\"d\":1}");
printValueAndType(getOrNull(jsonObj, "a"));
// >>> 1 -> class java.lang.String
printValueAndType(getOrNull(jsonObj, "b"));
// >>> null -> class org.json.JSONObject$Null
printValueAndType(getOrNull(jsonObj, "d"));
// >>> 1 -> class java.lang.Integer
printValueAndType(getOrNull(jsonObj, "c"));
// >>> null -> null
// throws org.json.JSONException: JSONObject["c"] not found. without a check
}
public static Object getOrNull(JSONObject jsonObj, String key) {
return jsonObj.optString(key, null);
}
public static void printValueAndType(Object obj){
System.out.println(obj + " -> " + ((obj != null) ? obj.getClass() : null));
}
}
you can use optString("c") or optString("c", null)
as stated in the documentation
private List<String> getSCFData(int trdCustomerKy, Date lastRunDate, Date currentDate) throws TradeException {
List<String> reportData = null;
String paymentDate = EMPTY_STRING;
String partyId = EMPTY_STRING;
YOWDAO hdDAO = new YOWDAO(mConnection);
List<YOWSCFExtractData> reportItems = hdDAO.getSCFData(trdCustomerKy, lastRunDate, currentDate);
if (null != reportItems && reportItems.size() > 0) {
reportData = new ArrayList<String>();
mTracer.log("Total records retrieved: " + reportItems.size());
for (YOWSCFExtractData data : reportItems) {
String Source = (null != data.getSource()) ? data.getSource() : BLANK_STRING;
String paymentCurrencyCd = (null != data.getPaymentCurrencyCd()) ? data.getPaymentCurrencyCd()
: BLANK_STRING;
String sellerName = (null != data.getSellerName()) ? data.getSellerName() : BLANK_STRING;
String paymentAmount = (null != data.getPaymentAmount()) ? data.getPaymentAmount() : BLANK_STRING;
if (null != data.getPaymentDate()) {
paymentDate = DateUtil.formatDate(data.getPaymentDate());
}
if (null != data.getapplCifId()) {
partyId = hdDAO.getPartyId(mConfiguration.getCustomerKy(), data.getapplCifId());
}
String dataRow = StringUtils.join(new String[] { Source, data.getBankRef(), partyId, sellerName,
data.getPartyId(), paymentAmount, paymentDate, paymentCurrencyCd}, COMMA);
reportData.add(dataRow);
}
}
return reportData;
}
I am extracting the data from oracle database. I want to update the record of a column once it is fetched to a string. for example when I had extracted data.getBanref() then I want to set it some string back in database. how would I do that? I am using hibernate........
What you can do is set the object data whatever values you want and then save it in the hibernate. If you want to update then use session.saveOrUpdate() or if you want to save a new record then use session.save(). Hope that helps!
You can write a hibernate query
Update table_Name column_Name and set it to whatever you want and call this query in your program. It will be easier i think so
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.
I need to be able to compare the value that is in an object to an int, but I can't seem to get the typecasting working. I have tried all the methods described here: Session attribute access and converting to int? but they all give me a null pointer exception. Here is the code I have that's not working.
Here is the code that puts values into the session.
<script>sessionStorage.clickcount=1;</script>
<input type ="hidden" name="ttmp" value="222" id="ttmp" />
<script>document.getElementById('ttmp').value = sessionStorage.clickcount;</script>
This was tried with the input line before and after the script.
<%
String value = request.getParameter("ttmp");
if (value != null) {
session.setAttribute("test", value);
}
Integer userid = Integer.parseInt(session.getAttribute("test").toString());
...
if (userid == 1) {
...
}
%>
try this Integer.parseInt((String)session.getAttribute("test"))
<%
String value = request.getParameter("ttmp");
if (value != null) {
session.setAttribute("test", value);
}
Integer userid = Integer.parseInt((String)session.getAttribute("test"));
...
if (userid == 1) {
...
}
%>
Try this now.
<%
String value = request.getParameter("ttmp");
if (value != null) {
session.setAttribute("test", value);
}
int userid=0;
if ((session.getAttribute("test") != null) && (session.getAttribute("test") != ""))
{
userid = Integer.parseInt(session.getAttribute("test").toString());
}
%>