I am having a LDAP Queue which process a object class.I cant find the exact location why it is giving the exception. The objclass is a concadenation string with pipe symbol. Any program coding to find the exact location in which concadination part is going to the Exception?.Please Assist.
try {
Attributes objClass = null;
try {
objClass = getObjClass(LdapInfo.PER_ID, person.perId);
} catch (NamingException e)
{
DCXError.myInstance().writeError("LdapUpdaterConnection: " + e.getMessage());
}
NamingEnumeration oc = objClass.get("objectclass").getAll();
String baseObjClass = null;
while (oc.hasMoreElements()) {
baseObjClass = (String) oc.nextElement();
if (baseObjClass.equalsIgnoreCase(LdapInfo.NON_EMPLOYEE_PERSON)
|| baseObjClass.equalsIgnoreCase("N/A")||
baseObjClass.equalsIgnoreCase(LdapInfo.EMPLOYEE_PERSON))
break;
}
} catch (SchemaViolationException e4) {
DCXError.myInstance().writeError(
"LdapUpdaterConnection:doUpdate SchemaViolationException "+ e4.getExplanation());
DCXError.myInstance().writeError("LdapUpdaterConnection:update persID = " + personId);
return (LdapUpdaterConnection.BAD_DATA);
}
You can't find the exact location only because you haven't logged the stack trace. You would also need to reformat your code so that each statement is on a separate line to make any use of that information. You should also use variable names that actually correspond to the content.
This is really terrible code.
It's also hard to see why you are doing all this in the first place. A decent query filter would do all that for you far more simply.
Related
I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.
However, Sonar is complaining that I should Either log or rethrow this exception.
What am I missing here? Am I not already logging the exception?
private boolean authenticate(User user) {
boolean validUser = false;
int validUserCount = 0;
try {
DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
validUserCount = new MasterDao(dataSource).getValidUserCount(user);
} catch (SQLException sqle) {
LOG.error("Exception while validating user credentials for user with username: " + user.getUsername() + " and pwd:" + user.getPwd());
LOG.error(sqle.getMessage());
}
if (validUserCount == 1) {
validUser = true;
}
return validUser;
}
You should do it this way :
try {
DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
validUserCount = new MasterDao(dataSource).getValidUserCount(user);
} catch (SQLException sqle) {
LOG.error("Exception while validating user credentials for user with username: " +
user.getUsername() + " and pwd:" + user.getPwd(), sqle);
}
Sonar shouldn't bother you anymore
What sonar is asking you to do, is to persist the entire exception object.
You can use something like:
try {
...
} catch (Exception e) {
logger.error("Error", e);
}
I stumbled across the same issue. I'm not 100% sure if I'm completely right at this point, but basically you should rethrow or log the complete Exception. Whereas e.getMessage() just gives you the detailed message but not the snapshot of the execution stack.
From the Oracle docs (Throwable):
A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another.
This means the solution provided by abarre works, because the whole exception object (sqle) is being passed to the logger.
Hope it helps.
Cheers.
If you believe that SQLException can be safely ignored, then you can add it to the list of exceptions for squid:S1166 rule.
Go to Rule-> Search squid:S1166.
Edit exceptions in Quality Profile.
Add SQLException to the list.
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.
My application uses https://app.bandwidth.com/ for receiving incoming calls. I have an api to handle the incoming calls which record the calls when the call is not answered(This recording is treated as a voice mail).
if (eventType.equalsIgnoreCase(EventType.ANSWER.toString())) {
Timestamp callStartTime = new Timestamp(TimeUtil.now().getTime());
incomingCall.setCallTime(callStartTime);
callStatus = transferCall(callId, incomingCall.getVoiceForwardNumber(), 1);
}
else if (eventType.equalsIgnoreCase(EventType.TIMEOUT.toString())) {
voiceMailIntro(callId);
}
else if (eventType.equalsIgnoreCase(EventType.SPEAK.toString()) && PLAYBACK_STOP.equalsIgnoreCase(callState)) {
recordVoiceMail(callId);
}
else if (eventType.equalsIgnoreCase(EventType.RECORDING.toString()) &&
state.equalsIgnoreCase(BandwidthCallStatus.COMPLETE.toString())) {
createTranscription(recordingId);
}
else if (eventType.equalsIgnoreCase(EventType.TRANSCRIPTION.toString()) && status.equalsIgnoreCase(BandwidthCallStatus.COMPLETED.toString())) {
incomingCall.setVoiceMail(text);
}
This is the code for recording call
private void recordVoiceMail(String callId) {
BandwidthClient client = BandwidthClient.getInstance();
client.setCredentials(bandwidthUserId, bandwidthApiToken, bandwidthApiSecret);
try {
Call call = Call.get(client, callId);
call.recordingOn();
} catch (Exception e) {
log.error("An exception occurred while recording voice mail : " +
e.getMessage(), e);
}
}
Now i need to transcribe these vocie mails.
From documentation i got methods in python, js, c#, ruby etc. to transcribe the recordings using the recordings.
For example in js,
client.Recording.createTranscription(recordingId, function(err, transcription){});
I searched every where, but i couldn't find any method in java for that.
Can any one help me if you know ?
Anyway, as I see, you need that link for java doc.
And here you can follow to java sdk located on Github.
And, also, you can find some more information about transcriptions API here which you are looking for.
First of all, why do you need that? Perhaps, you do not need that.
As I find, you can't do transcribe with POJO, but you can do something like that.
If you want to do that, you can make it with
public void transcribeOn() throws Exception {
final List<Recording> list = Recording.list(0, 5);
if (!list.isEmpty()) {
final Recording recording = Recording.get(list.get(0).getId());
System.out.println("\nRecording by Id");
System.out.println(recording);
final String recordingUri = mockClient.getUserResourceUri(BandwidthConstants.RECORDINGS_URI_PATH);
client.post(recordingUri + "/" + list.get(0).getId() + "/transcriptions", null);
final JSONObject jsonObject = call.toJSONObject(client.get(recordingUri, null));
call.updateProperties(jsonObject);
}
}
I'm not sure it works correctly, but I hope it put you on correct way
i want to put if else or switch statement which is more suitable for checking employee count before commit.where i put my if else or switch code . i want restriction on employee if count is 5 then its show message "reached maximum employee limites" otherwise allow commit.
i am new in java plz someone help me to solve this
public String cmdSave_action()
{
// my code before
{
DeptSet result;
try {
dbo.connect();
result =
dbo.execSQL("select count(*) from empmasterinfo where mainid='ORGElement' and designationid='?') "
(inputText_ORGElement.getValue() != null ?
""));
result = dbo.execSQL(sSQL);
catch (Exception e) {
System.out.println(e.getMessage());
finally
{
dbo.close();
}
return null;
}}}
// my code above
{
Global.PerformIteratorAction(this.bindings, "Commit");
AdfFacesContext afContext = AdfFacesContext.getCurrentInstance();
afContext.getProcessScope().put("EmployeeID",
Global.getCurrRowFieldValue("EmpmasterinfoViewIterator",
"Employeeid"));
if (afContext.getProcessScope().get("AddEdit").toString().equals("0"))
{
Global.PerformIteratorAction(this.bindings,
"EPR_TRANSFER_APPLICANT_INFO");
Global.PerformIteratorAction(this.bindings, "eprGenerateApPlan");
}
return null;
}}
My Error Log
Error(149,12): 'try' without 'catch' or 'finally'
Error(154,36): , expected
Error(157,34): field SQL not found in class hcm.view.backing.empprofile.EmployeeMasterInfo_Add
Error(159,11): illegal start of expression
Error(159,11): ; expected
E:\HCM\ViewController\src\hcm\view\backing\empprofile\dbo.java
Error(13,16): method does not return a value
Please close Your try catch block properly
try{
}catch(Exception e){
}finally{
}
And Read this
catch and finally are within try block
try {
//code
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
dbo.close();
}
Using an IDE will help you with indentation and proper formatting while writing code. e.g Eclipse.
For the first error close the try-catch blocks properly
And for the second error: Since your method is declared as public String cmdSave_action(), you should return a String value at the end of the method. The return statement is missing in your code.
I have the following Android code:
public final List<MyObj> getList() {
Cursor cursor = null;
try {
final String queryStr = GET_LIST_STATEMENT;
cursor = db.rawQuery(queryStr, new String[] {});
List<MyObj> list = null;
//here I get the data from de cursor.
return list ;
} catch (SQLiteFullException ex) {
//do something to treat the exception.
} finally {
if (cursor != null) {
cursor.close();
}
}
}
When I run PMD analysis over this code, I get the following issue: Found 'DD'-anomaly for variable 'cursor' (lines '182'-'185').
The line 182 is: Cursor cursor = null;.
The line 185 is: cursor = db.rawQuery(queryStr, new String[] {});
So, I understand that the problem is that I'm doing a Premature Initialization in the line 182 (I never read the variable between the lines 182 and 185), but if I don't do that, I can't have the code closing the cursor in the finally block.
What to do in this case? Just ignore this PMD issue? Can I configure PMD to don't rise up this specific kind of DD-anomaly (not all DD-anomaly)? Should PMD be smart enough to doesn't rise up this issue?
Another example of DD-anomaly that I think is not a real problem:
Date distributeDate;
try {
distributeDate = mDf.parse(someStringDate);
} catch (ParseException e) {
Log.e("Problem", "Problem parsing the date of the education. Apply default date.");
distributeDate = Calendar.getInstance().getTime();
}
In this case, the anomaly occurs with the distributeDate variable.
The documentation is pretty easy to understand:
Either you use annotations to suppress warnings:
// This will suppress UnusedLocalVariable warnings in this class
#SuppressWarnings("PMD.UnusedLocalVariable")
public class Bar {
void bar() {
int foo;
}
}
or you use a comment:
public class Bar {
// 'bar' is accessed by a native method, so we want to suppress warnings for it
private int bar; //NOPMD
}
When it comes to your specific code, I'd say that the easiest way to handle it is to not use a finally block even though this would look like the perfect place for it.