I have an error in the SonarQube of Nullcheck of call when assigning a value to a stored procedure.
call.setBigDecimal(ONE, bank != null ? bank : BigDecimal.ZERO);
Exactly in this excerpt above. He makes the same mistake if he removes the ternary. I did an IF before the function and the same error occurred.
enter image description here
public CarrierReturnDTO getMobileCarriers(BigDecimal bank) throws SQLException {
CarrierReturnDTO carrierReturnListDTO = new CarrierReturnDTO();
List<CarrierDTO> mobileCarrierList = new ArrayList<CarrierDTO>();
DataSource dataSource = jdbcTemplate.getDataSource();
if (dataSource != null) {
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
try (CallableStatement call = connection.prepareCall(Constants.COMBO_OPERCEL)) {
call.setBigDecimal(ONE, bank != null ? bank : BigDecimal.ZERO);
call.registerOutParameter(TWO, OracleTypes.CURSOR);
call.execute();
ResultSet rs = (ResultSet) call.getObject(TWO);
while (rs.next()) {
CarrierDTO mobileCarrier = new CarrierDTO();
mobileCarrier.setMobileCarrierCode(rs.getBigDecimal(Constants.COD_EMP_OPER));
mobileCarrier.setMobileCarrier(rs.getString(Constants.NOM_EMP_OPER));
mobileCarrier.setAmountDigitChecked(rs.getBigDecimal(Constants.QTD_DIG_VERIFIC));
mobileCarrier.setFlagDoubleDigit(rs.getString(Constants.FLG_DUP_DIGIT));
mobileCarrier.setBankCode(rs.getString(Constants.BCO_CNV_ALTAIR));
mobileCarrier.setBranchCode(rs.getString(Constants.AGE_CNV_ALTAIR));
mobileCarrier.setAccountCode(rs.getString(Constants.CTA_CNV_ALTAIR));
mobileCarrierList.add(mobileCarrier);
}
rs.close();
}
}
}
}
carrierReturnListDTO.setCarriers(mobileCarrierList);
return carrierReturnListDTO;
}
You have SonarQube's NullCheck enabled. This will give you an error for using a null check in places where a variable cannot be null. Following documentation, this would mean that you are never passing a null into getMobileCarriers(). For robustness of your code, having that null check is a good idea (as you might be using that method from elsewhere, or even externally at some point). Therefore, I would recommend looking into SonarQube's setup and either turning this check off or modifying it such that it won't perform this analysis cross-method calls.
Related
We have to implement a logic to write the unique code generation in Java. The concept is when we generate the code the system will check if the code is already generate or not. If already generate the system create new code and check again. But this logic fails in some case and we cannot able to identify what is the issue is
Here is the code to create the unique code
Integer code = null;
try {
int max = 999999;
int min = 100000;
code = (int) Math.round(Math.random() * (max - min + 1) + min);
PreOrders preObj = null;
preObj = WebServiceDao.getInstance().preOrderObj(code.toString());
if (preObj != null) {
createCode();
}
} catch (Exception e) {
exceptionCaught();
e.printStackTrace();
log.error("Exception in method createCode() - " + e.toString());
}
return code;
}
The function preOrderObj is calling a function to check the code exists in the database if exists return the object. We are using Hibernate to map the database functions and Mysql on the backend.
Here is the function preOrderObj
PreOrders preOrderObj = null;
List<PreOrders> preOrderList = null;
SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext().getAttribute(HibernateListener.KEY_NAME);
Session Hibernatesession = sessionFactory.openSession();
try {
Hibernatesession.beginTransaction();
preOrderList = Hibernatesession.createCriteria(PreOrders.class).add(Restrictions.eq("code", code)).list(); // removed .add(Restrictions.eq("status", true))
if (!preOrderList.isEmpty()) {
preOrderObj = (PreOrders) preOrderList.iterator().next();
}
Hibernatesession.getTransaction().commit();
Hibernatesession.flush();
} catch (Exception e) {
Hibernatesession.getTransaction().rollback();
log.debug("This is my debug message.");
log.info("This is my info message.");
log.warn("This is my warn message.");
log.error("This is my error message.");
log.fatal("Fatal error " + e.getStackTrace().toString());
} finally {
Hibernatesession.close();
}
return preOrderObj;
}
Please guide us to identify the issue.
In createCode method, when the random code generated already exist in database, you try to call createCode again. However, the return value from the recursive call is not updated to the code variable, hence the colliding code is still returned and cause error.
To fix the problem, update the method as
...
if (preObj != null) {
//createCode();
code = createCode();
}
...
Such that the code is updated.
By the way, using random number to generate unique value and test uniqueness through query is a bit strange. You may try Auto Increment if you want unique value.
I am using below code,i have checked pathname and sheet name is all fine.
I am using fillo version fillo-1.15.
public class T_Test {
public static void main(String[] args) throws Exception{
try {
com.codoid.products.fillo.Fillo fil_res = new com.codoid.products.fillo.Fillo();
com.codoid.products.fillo.Connection con_res = fil_res
.getConnection("C:\\Users\\admin\\workspace\\Good Connect\\Test_Data/Result\\LifePlanner_Result.xlsx");
String sql_res = "update Result_Data SET Product_ID = 'Sampoorna Raksha' Where TestCase_ID = 'TC1_SIS' ";
System.out.println(sql_res);
com.codoid.products.fillo.Recordset recordset_rec = con_res.executeQuery(sql_res);
con_res.close();
} catch (Exception e) {
System.out.println("Exception result set:" + e.toString());
}
}
}
Error is below:
java.lang.NullPointerException
Exception result set:java.lang.NullPointerException
at com.codoid.products.parser.SelectQueryParser.isWherePresent(SelectQueryParser.java:66)
at com.codoid.products.fillo.Select.getRecordset(Select.java:47)
at com.codoid.products.fillo.Connection.executeQuery(Connection.java:56)
at GoodSolutionAgence.T_Test.main(T_Test.java:89)
I believe the error is here:
com.codoid.products.fillo.Recordset recordset_rec = con_res.executeQuery(sql_res);
You are executing an UPDATE statement, not a SELECT query. An UPDATE statement won't return a record set, just the number of rows it updated. You therefore want to use executeUpdate in place of executeQuery:
int numberOfRowsUpdated = con_res.executeUpdate(sql_res);
However, the Fillo library could at least have warned you that you were using the wrong method. The fact that it threw a NullPointerException is in my opinion a bug in this library: it should handle this error condition better.
Null Pointer Exception occurs when you try to reference a variable that has not been initialized
com.codoid.products.fillo.Connection con_res = fil_res
.getConnection("C:\\Users\\admin\\workspace\\Good Connect\\Test_Data/Result\\LifePlanner_Result.xlsx");
In this case the con_res might be null since getConnection method is not functioning properly.
Now when you try to execute
con_res.executeQuery(sql_res);
It results in Null Pointer Exception.
Check whether con_res gets initialized properly and check the path specified in getConnection method
Hi I created a jni jar and i call the jar using applet in java script. I use the following applet tag to create a object to call jar functions through java script. when i call the function i got the following error Object doesn't support this method or property.
Here is my code.
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
function GetTemplateAccurate (sUserID,iFingerID)
{
document.getElementsByName("Enroll")[0].value = "";
document.getElementsByName("Image")[0].value = "";
var lsFeature = null;
var lsImage = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SaveImage(1);
Obj.SessionID("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde");
Obj.GetFeatureAccrual(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null && lsImage != null )
{
document.getElementsByName("Enroll")[0].value = lsFeature;
document.getElementsByName("Image")[0].value = lsImage;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
function GetTemplate(sUserID,iFingerID)
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SessionID("abcde");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
as exception itself is describing:
Object doesn't support this method or property error
the property or method you are trying to access with an object is not supported by that object. Please debug or see on error console the object throwing exception and find whether it support that property you are trying to access.
I'm new to Birt.
I'm trying to pass the connection to the report from my java application, but I get an error:
The following items have errors:
ReportDesign (id = 1):
+ There are errors evaluating script "importPackage(Packages.it.lfiammetta.birt); var conn = new
ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection",
conn);": Fail to execute script in function __bm_beforeOpen(). Source:
" + importPackage(Packages.it.lfiammetta.birt); var conn = new
ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection",
conn); + "
A BIRT exception occurred. See next exception for more information.
Error evaluating Javascript expression. Script engine error:
ReferenceError: "ReportRenderer" is not defined.
(/report/data-sources/oda-data-source[#id="43"]/method[#name="beforeOpen"]#2)
Script source:
/report/data-sources/oda-data-source[#id="43"]/method[#name="beforeOpen"],
line: 0, text:
__bm_beforeOpen(). (Element ID:1)
This is my java code that creates and launches report:
package it.lfiammetta.birt;
public class ReportRenderer {
public void executeReport() {
code...
Map<String, Object> appContext = task.getAppContext();
appContext.put("OdaJDBCDriverPassInConnection", myConnection);
appContext.put("OdaJDBCDriverPassInConnectionCloseAfterUse", false);
task.setAppContext(appContext);
task.run();
code...
}
}
This is the code I wrote in the script 'beforeOpen' the datasource:
importPackage(Packages.it.lfiammetta.birt);
var conn = new ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection", conn);
I set the classpath.
Birt version I'm using is 4.2.1.
Thanks in advance for your help and I apologize for my English.
I'm doing that from Java code (IJDBCParameters - actually parameters for JDBC connections, I'm looking connection by name - OdaDataSourceHandle.getName()):
#SuppressWarnings("rawtypes")
private static void substituteJDBCConnections(IReportRunnable pReportRunnable) {
final Map<String, IJDBCParameters> jdbcConnections = reportParameters.getJdbcConnections();
if (jdbcConnections != null ){
for (Iterator iter = pReportRunnable.getDesignHandle().getModuleHandle().getDataSources().iterator(); iter.hasNext();){
// http://wiki.eclipse.org/Java_-_Execute_Modified_Report_(BIRT)
Object element = iter.next();
if (element instanceof OdaDataSourceHandle){
OdaDataSourceHandle dsHandle = (OdaDataSourceHandle) element;
String key = dsHandle.getName();
if (key == null){
continue;
}
IJDBCParameters jdbcParams = jdbcConnections.get(key);
if (jdbcParams == null){
continue;
}
try {
dsHandle.setProperty( "odaDriverClass", jdbcParams.getDriverName());
dsHandle.setProperty( "odaURL", jdbcParams.getConnectionString());
dsHandle.setProperty( "odaUser", jdbcParams.getUserName());
dsHandle.setProperty( "odaPassword", jdbcParams.getPassword());
} catch (SemanticException e) {
throw new UncheckedException(e);
}
}
}
}
Probably you fixed your issue already, but maybe someone will be looking for this in the future. First of all 4.2.x versions had problems with passed connections. I did not observed the same errors in 4.4.2.
Other thing, I do not get why you are trying to pass ReportRenderer as a connection in lines:
var conn = new ReportRenderer();
reportContext.getAppContext().put("OdaJDBCDriverPassInConnection", conn);
The passed object in here should be a java.sql.Connection object.
Therefore,
Map<String, Object> appContext = task.getAppContext();
appContext.put("OdaJDBCDriverPassInConnection", myConnection);
appContext.put("OdaJDBCDriverPassInConnectionCloseAfterUse", false);
task.setAppContext(appContext);
looks correct as long as myConnection is an implementation of java.sql.Connection
I am writing an own databse in scala. To verify my results are correct, I check with a MySQL inside of a specs2 specification. I get the right result and everything is just fine. But if I run the test again without any changes, I get a SQLException: No suitable driver found for jdbc:mysql://localhost:3306/DBNAME?user=DBUSER (null:-1). Why is the driver not loaded again?
Edit
import java.sql.{ Connection, DriverManager, ResultSet }
import org.specs2.mutable.Specification
// SDDB imports ...
class DBValidationSpec extends Specification {
"SDDB and MySQl" should {
// SDDB
// ...
// JDBC
val connectionString = "jdbc:mysql://localhost:3306/sddb_test?user=root"
val query = """SELECT content, SUM( duration ) duration
FROM test
WHERE times
BETWEEN '2011-12-08'
AND '2011-12-09'
GROUP BY content"""
classOf[com.mysql.jdbc.Driver]
"give the same result" in {
// ...
//sddbResult
lazy val conn = DriverManager.getConnection(connectionString)
try{
val rs = conn.createStatement().executeQuery(query)
var mysqlResult = Map[List[String], Int]()
while (rs.next) {
mysqlResult += (rs.getString("content") :: Nil) -> rs.getInt("duration")
}
sddbResult == mysqlResult && sddbResult.size == 478 must beTrue
} finally {
conn.close()
}
}
}
}
I left out some parts of my code because they don't belong to the question.
Edit #2
The problem became even weirder. I added a second testcase. The testcase uses the same connectionString. The Exception was only raised once. The second test succeeded. I added sequential to my test definition and saw that only the first executed test raises the Exception. Afterwards I traced the classLoader to check if it is the same one. It is.
I did the following workaround:
trait PreExecuting extends Before {
override def before {
var conn: Option[Connection] = None
try {
val connectionString = "jdbc:mysql://localhost:3306/sddb_test?user=root"
conn = Some(DriverManager.getConnection(connectionString))
} catch {
case _ =>
} finally {
conn map (_.close())
}
}
}
I don't get the Exception any more because I suppress it by using the PreExecution tait. But I still wonder what is going wrong here.
I cannot pin down the error, to the following, but at least better also close the result set and statement.
val stmt = conn.createStatement()
val rs = stmt.executeQuery(query)
var mysqlResult = Map[List[String], Int]()
while (rs.next) {
mysqlResult += (rs.getString("content") :: Nil) -> rs.getInt("duration")
}
sddbResult == mysqlResult && sddbResult.size == 478 must beTrue
rs.close()
stmt.close()
It's seems to be a problem with the Driver registration, the Driver has to be registered some like this...
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
or some like this...
DriverManager.registerDriver(new DriverWrapper((Driver) Class.forName(props.getProperty("dbg.driver"), true, gcloader).newInstance()));
before use getConnection. I hope this help.
The driver is only loaded once.
No suitable driver usually means that the connection URL syntax is incorrect.