I am getting this error.Return type is mismatched
public List<EmpRecord> Empdata(String uname) throws Exception {
System.out.println("Inside into service class2");
try {
#SuppressWarnings("unchecked")
List<EmpRecord> userObjs = hibernateTemplate.find("from EmpRecord u where u.uname=? ",uname);
if(userObjs.size() != 0) {
System.out.println(" Employee Name : " + userObjs.get(0).getEmpName());
}
return userobjs;
Typing error. Thats all there is to it. Use a capital O in userObjs in the return statement
change return userobjs; to return return userObjs;
I would also change if(userObjs.size() != 0) to if(userObjs!=null && userObjs.size() != 0) for safety reason.
Related
I am trying to achieve transactional rollback when i will get checked exception from "invokeProcedureForLead" method(code mentioned below). I have tried multliple ways and some reference still
it is not working for me .
For more understanding please find below code
#Transactional(rollbackFor = Exception.class)
public LeadResponseDTO processDataInDB(LMCRAResponseData lmcraResponse,
Boolean crnPresentFlag, Map<Integer, Integer> craProcData,
Map<Integer, Integer> crnProcData,LeadResponseDTO leadResponseDTO,LMCRARequestData lmcraRequestData) throws CRAProcessDBException,SQLException, CRAProcessClientException {
try{
leadResponseDTO = extractDecision(lmcraResponse,crnPresentFlag);
decisionEngineResponseDao.invokeProceduresForLead(craProcData, crnProcData, lmcraResponse);
}catch(Exception e){
log.error("error in invokeProcCalls", e);
if (masterErrorCodes.getErrorDTO("6006") != null)
logException(lmcraResponse, masterErrorCodes.getErrorDTO("6006"));
leadResponseDTO=new LeadResponseDTO();
getLeadResponseDTO(lmcraRequestData,leadResponseDTO,e.getMessage());
}
return leadResponseDTO;
}
public void invokeProceduresForLead(Map<Integer, Integer> craProcData,
Map<Integer, Integer> crnProcData, LMCRAResponseData lmcraResponseData) throws Exception {
int noCRNFlag = 0;
String commonLogs = CommonUtil.printDECommonLogs(lmcraResponseData);
if (lmcraResponseData.isBureauMatch() && crnProcData.isEmpty())
noCRNFlag = 1;
if (lmcraResponseData.isBureauMatch()
&& invokeProcLeads(craProcData, DBConstants.CALL_PROC_PROCESS_CRA_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID())) != null) {
log.info("invokeProcLeads for Cra block - 1 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for CRA");
}
if (crnProcData != null
&& !crnProcData.isEmpty()
&& invokeProcLeads(crnProcData, DBConstants.CALL_PROC_PROCESS_CRN_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID())) != null) {
log.info("invokeProcLeads for crn block - 2 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for CRN");
}
if (((crnProcData == null || crnProcData.isEmpty()) || !lmcraResponseData.isBureauMatch())
&& invokeNoCrnForLeads(DBConstants.CALL_PROC_PROCESS_NO_CRN_DATA_LEAD,
Integer.parseInt(lmcraResponseData.getCaseID()), noCRNFlag) != null) {
log.info("invokeNoCrnForLeads block - 3 for runId {} " , commonLogs);
throw new CRAProcessDBException("error in invokeProcCalls for NOCRN");
}
I think the code needs to change like this -
log.error("error in invokeProcCalls", e);
if (masterErrorCodes.getErrorDTO("6006") != null)
logException(lmcraResponse, masterErrorCodes.getErrorDTO("6006"));
leadResponseDTO=new LeadResponseDTO(); getLeadResponseDTO(lmcraRequestData,leadResponseDTO,e.getMessage());
}
throw e;
Note that **throw e; ** line added..
The problem is you are throwing an exception from internal call, but then swallowing it in outer method. So the exception is never thrown from outer method, which results in no rollback happening.
I had a weird situation today while I was writing tests. Basically, I had a class with data. Let's say Toy for example, from which we can retrieve a name:
public class Toy {
private String name;
public Toy(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And I had an exception, which was working in a way similar to this (e.g. just displaying data about all the objects on which we were working before it went bad); I also included a main for test purpose:
public class ToyFactoryException extends Exception {
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? firstToy.getName() : null +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
public static void main(String[] args) {
try {
throw new ToyFactoryException(null, new Toy("hi"));
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
}
As I wrote in the first catch block, the exception should be caught in the ToyFactoryException.
However, in the exception, it's trying to read firstToy.getName() right here: firstToy != null ? firstToy.getName() : null
firstToy != null should evaluate to false, which means it shouldn't be trying to call firstToy.getName() in the first place. When you write it in the reverse order:
public ToyFactoryException(Toy firstToy, Toy secondToy) {
super("An error occurred when manufacturing: " +
"\nfirstToy: " + firstToy != null ? null : firstToy.getName() +
"\nsecondToy: " + secondToy != null ? secondToy.getName() : null);
}
You realise it reads null instead now, which means it's truly reading firstToy != null as true.
If you write the main this way instead (the null is the second parameter of the constructor):
public static void main(String[] args) {
try {
throw new ToyFactoryException(new Toy("hi"), null);
} catch (ToyFactoryException myException) {
System.out.println("It should be there.");
} catch (Exception exception) {
System.out.println("But it's there instead.");
}
}
It works properly, despite the secondToy ternary condition being written the same way as the firstToy ternary.
Why is the ternary condition on firstToy not evaluating null properly?
You should put parentheses around your conditional expression.
This:
"string " + firstToy != null ? firstToy.getName() : null
means this:
("string " + firstToy) != null ? firstToy.getName() : null
You need this:
"string " + (firstToy != null ? firstToy.getName() : null)
I am threading a time consuming for-loop and executing them inside N number of threads. A continue statement is throwing error
Getting the error "Continue cannot be used outside of a loop"
for (final Message m : messagelistholder.getMessage()) {
Callable<Void> tasksToExecute = new Callable<Void>() {
public Void call() {
if (guidanceonly1 == true && !QuoteUtil.isECPQuote(list.get(0))) {
String msg = "Message From " + m.getSource() + " when retrieving Guidance values: "
+ m.getDescription();
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()}, msg);
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
} else if ("Error".equalsIgnoreCase(m.getSeverity())) {
if (m.getCode().indexOf("_NF") > 0) {
continue; // price not found due to private sku
}
if ("Eclipse".equalsIgnoreCase(m.getSource())) {
String msg1 = "Please check Sold To customer data. ";
String lcladdStatusMessages1 = CommonUtil
.getLoclizedMsg("PRCE_LNE_ITM_PLS_CHK_SLDTO_CUST_DTA", null, msg1);
String msg2 = "Discount information may not be returned from Optimus due to "
+ m.getSeverity() + " From " + m.getSource() + " " + m.getDescription();
String lcladdStatusMessages2 = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_DSCNT_INFO_MNT_RTRND_FRM_OPTMS_DUETO_FRM",
new String[]{m.getSeverity(), m.getSource(), m.getDescription()}, msg2);
list.get(0).addStatusMessages(m.getSeverity(),
(m.getDescription().contains("MDCP") ? lcladdStatusMessages1 : "")
+ lcladdStatusMessages2);
} else {
if (response1.getItems() == null) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg("PRCE_LNE_ITM_OPTMS_ERR",
new String[]{m.getSource(), m.getDescription()}, m.getDescription());
list.get(0).addStatusMessages("Error", lcladdStatusMessages);
list.get(0).setOptimusError(true);
} else {
if (!QuoteUtil.isECPQuote(list.get(0))) {
String lcladdStatusMessages = CommonUtil.getLoclizedMsg(
"PRCE_LNE_ITM_MSG_FRM_WHN_RETRVNG_GUIDNCE_VAL",
new String[]{m.getSource(), m.getDescription()},
"Message From " + m.getSource() + " " + m.getDescription());
list.get(0).addStatusMessages("Info", lcladdStatusMessages);
list.get(0).setOptimusError(true);
}
}
}
}
if (list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER) != null) {
list.get(0).getFlags().get(QtFlagType.ESCALATIONFORPARTNER).setFlgVl(null);
}
if (m.getCode() != null) {
String pricingServiceMsgCode = m.getCode();
String pricingServiceSeverity = m.getSeverity();
Map<Integer, AutoEscalationScenario> categoryMap;
if (StringUtils.equals("ERROR", pricingServiceSeverity)) {
categoryMap = getScenario("SEVERITY", globalAccount1, null, true, null);
if (categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
if (partnerExclusivityAutoEscalation1) {
categoryMap = getScenario(pricingServiceMsgCode, globalAccount1, null, true, null);
if (categoryMap != null && categoryMap.size() != 0) {
finalCategorylist.get(0).putAll(categoryMap);
}
}
}
return null;
}
};
runnableTasks.add(tasksToExecute);
}
Can someone help me to skip the particular loop for the speicified condition but without using continue statement since it throws error.
What's happening is that you are actually calling continue outside of a loop because the call() function itself does not have a for loop, so it doesn't matter if are only calling call() from a loop.
What can you do to fix this is making the call function to return a boolean and replacing the continues with return true and return false if no return true has been reached.
Then replace the:
call()
on the loop(s) for
if(call()) continue
So the I'm not saying I fully understand you code, but it appears that you are using continue to break out of that thread. On a normal multi-threaded application, it looks like you are launching multiple threads from one one loop. The continue call is inside the new thread, not the loop. As soon as you start writing the call() method, you leave the loop to run it. Looking at the code, I would try replacing continue with return. Normally I would try running it myself before I suggest it, but without the rest of the code I cannot verify that it works.
I have the following method
public Message JavaMethod(String id1, String id2)
In which I need to call a Dao class's method to verify that an user with the provided Id exist, and if it does not, create a message detailing the Id that couldn't be found on the database with the following method:
createMessage("Message string",Enum.TYPE,IdofMissingUser);
At first I thought of doing it like this:
public Message JavaMethod(String id1, String id2) {
if(Dao.findUser(id1) == null || Dao.findUser(id2) == null){
return createMessage("Error",Enum.Error,id1);
}else{
//do some other stuff
}
}
But obviously this way I won't know which of the ids has not been found.
So I went ahead and created an ugly if else cycle:
public Message JavaMethod(String id1, String id2) {
if (Dao.findUser(id1) == null) {
return createMessage("Error", Enum.Error, id1);
} else if (Dao.findUser(id2) == null) {
return createMessage("Error", Enum.Error, id2);
} else {
// Do stuff after veryfing users exists
return createMessage("All OK", Enum.OK, messageData);
}
}
But I'm not feeling really confident that this is the best solution for this basic issue.
What would you guys recommend in this case?
You could wrap the ids in a list and use a for loop:
public Message someMethod(String id1, String id2) {
for (String id: Arrays.asList(id1, id2)) {
if (Dao.findUser(id) == null) {
return createMessage("Error", Enum.Error, id);
}
}
// Do stuff after verifying users exists
return createMessage("All OK", Enum.OK, messageData);
}
If you're only ever going to have two IDs, you could deal with a shorthand boolean. Question is whether that makes it less readable though. E.g.
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
This also doesn't deal with if both of the IDs were null, for that you could extend it:
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null && user2 == null? both : user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
You'd need to define what you would return for the both variable
More details on the shorthand boolean annotation can be found here
This is the sample data on which i was working:
Peter Wilkerson 27 M
James Owen 26 M
Matt Wo 30 M
Kenny Chen 28 M
I created a simple UDF for filtering the age like this:
public class IsApplicable extends FilterFunc {
#Override
public Boolean exec(Tuple tuple) throws IOException {
if(tuple == null || tuple.size() > 0){
return false;
}
try {
Object object = tuple.get(0);
if(object == null){
return false;
}
int age = (Integer)object;
return age > 28;
} catch (Exception e) {
throw new IOException(e);
}
}
}
This is the Script I used for using this UDF:
records = LOAD '~/Documents/data.txt' AS (firstname:chararray,lastname:chararray,age:int,gender:chararray);
filtered_records = FILTER records BY com.udf.IsApplicable(age);
dump filtered_records;
Dumping does not display any record. Please let me know where I missed.
tuple.size() > 0 condition is always true in the if stmt, so it will never go to the try block(ie filtering logic), that is the reason you are getting empty result. Can you change the if condition like this?
System.out.println("TupleSize="+tuple.size());
if(tuple == null || tuple.size() < 0){
return false;
}
Sample debug output in console:
2015-02-13 07:40:46,994 [Thread-2] INFO org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map - Aliases being processed per job phase (AliasName[line,offset]): M: records[3,10],records[-1,-1],filtered_records[4,19] C: R:
TupleSize=1
TupleSize=1
TupleSize=1
This is returning false for all of the rows:
if (tuple == null || tuple.size() > 0) {
return false;
}
This is fetching the userName and not age:
Object object = tuple.get(0);