How to debug “Error: Error: java.util.NoSuchElementException” in Java? - java

Code :
int i = MobStackHandler.this.getInstance().getConfigHandler().getMobStackingRadius();
List localList = MobStackHandler.this.mobList;
Iterator localIterator2;
for (Iterator localIterator1 = Bukkit.getServer().getWorlds().iterator(); localIterator1.hasNext(); localIterator2.hasNext())
{
World localWorld = (World)localIterator1.next();
localIterator2 = localWorld.getLivingEntities().iterator();
LivingEntity localLivingEntity = (LivingEntity)localIterator2.next();
if ((localList.contains(localLivingEntity.getType())) && (localLivingEntity.isValid())) {
for (Entity localEntity : localLivingEntity.getNearbyEntities(i, i, i)) {
if (((localEntity instanceof LivingEntity)) && (localEntity.isValid()) && (localList.contains(localEntity.getType()))) {
MobStackHandler.this.stackOne(localLivingEntity, (LivingEntity)localEntity, ChatColor.valueOf(MobStackHandler.this.getInstance().getConfigHandler().getMobStackColor()));
}
}
}
}
}
}.runTaskTimer(getInstance(), 40L, 40L);
}
Error: at com.obvious.handlers.MobStackHandler$1.run(MobStackHandler.java:87) ~[?:?]

As Oracle Doc
NoSuchElementException:
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
If you want to debug just debug your iteration.

Related

Spring Boot: #Transactional rollbackFor checked Exception

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.

How to reuse the variable used for for loop first level inside for loop second level in nested for loop

Someone can tell me how can I reuse rootOpt object inside of my forEach. Is there any way to reuse this variable? I have the following message "Can not resolve symbol rootOpt" when I write rootOpt.getChildOptions() inside my forEach. Please find below what I did:
I have tried to rewrite the for loop below by using stream. Thank you
opts.stream()
.flatMap(rootOpt -> rootOpt.getChildOptions().stream())
.forEach(subOpt -> {
if (subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant())) {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
for (String ch : oldCHs) {
Option chRootOpt = childOptCodeToParentOptMap.get(ch.toUpperCase());
if (chRootOpt != null) {
if (!DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions())) {
List<OptionList> tmp = new ArrayList<OptionList>();
tmp.add(samePriceSibs);
tmp.add(chRootOpt.getChildOptions());
optionsPairsToRemoveCHs.add(tmp);
}
}
}
}
});
for (Option rootOpt : opts) {
for (Option subOpt : rootOpt.getChildOptions()) {
if (subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant())) {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
for (String ch : oldCHs) {
Option chRootOpt = childOptCodeToParentOptMap.get(ch.toUpperCase());
if (chRootOpt != null) {
if (!DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions())) {
List<OptionList> tmp = new ArrayList<OptionList>();
tmp.add(samePriceSibs);
tmp.add(chRootOpt.getChildOptions());
optionsPairsToRemoveCHs.add(tmp);
}
}
}
}
}
}
The scope of rootOpt ends at the closing parenthesis.
You could write it like this instead
opts.stream().forEach(rootOpt ->
rootOpt.getChildOptions().stream().forEach(subOpt -> {
...
});
);
However streams were not really intended to simply replace for loops. A more canonical way of using them would be something like this.
Stream<List<OptionList>> optionsPairsToRemoveCHs = opts.stream()
.flatMap(rootOpt ->
rootOpt.getChildOptions().stream()
.filter(subOpt -> subOpt.getOptLogic() != null && subOpt.getOptLogic().getCant() != null && !"".equals(subOpt.getOptLogic().getCant()))
.flatMap(subOpt -> {
String[] oldCHs = subOpt.getOptLogic().getCant().split("( )");
OptionList samePriceSibs = getSamePriceS(rootOpt.getChildOptions(), subOpt);
return Stream.of(oldCHs)
.map(ch -> childOptCodeToParentOptMap.get(ch.toUpperCase()))
.filter(chRootOpt -> chRootOpt != null && !DoesVariableOptionsCompletelyExcludeOther(samePriceSibs, chRootOpt.getChildOptions()))
.map(chRootOpt -> Arrays.asList(samePriceSibs, chRootOpt.getChildOptions()));
})
);
I didn't test that code though. Also refactoring it into several methods as mike suggested would help making it easier to read.

Java error Concurrent modification Exception

I need help for this case below :
I have 2 method :
private void calculateTime(Map.Entry<List<String>, List<LogRecord>> entry, List<LogProcess> processList) {
List<List<LogRecord>> processSpentTime = new ArrayList<List<LogRecord>>();
processSpentTime = subListProcess(entry, processSpentTime);
for (List<LogRecord> item : processSpentTime) {
processList = parse(item, DEFAULT_START_LEVEL);
}
}
and the second method
private List<LogProcess> parse(List<LogRecord> recordList, int level) {
List<LogProcess> processList = new ArrayList<LogProcess>();
if(!recordList.isEmpty()) {
LogProcess process = findProcess(recordList, level);
if(!(process instanceof NullLogProcess)) {
if(!(process instanceof IncompleteLogProcess)) {
processList.add(process);
}
int fromIndex = recordList.indexOf(process.returnStartIndexOfNextProcess()) + 1;
processList.addAll(parse(recordList.subList(fromIndex, recordList.size()), level));
}
}
return processList;
}
public LogProcess findProcess(List<LogRecord> recordList, int level) {
LogRecord endRecord = null;
LogRecord startRecord = findStartRecord(recordList);
if(startRecord instanceof NullLogRecord) {
return new NullLogProcess();
}
List<LogRecord> startEndRecord = findStartEndRecord(startRecord, recordList);
startRecord = startEndRecord.get(0);
endRecord = startEndRecord.get(1);
LogProcess process = returnLogProcess(startRecord, endRecord);
process.setLevel(level);
process.setChildren(findChildProcess(recordList, startRecord, endRecord, level + 1));
return process;
}
private List<LogProcess> findChildProcess(List<LogRecord> recordList, LogRecord startRecord, LogRecord endRecord, int level) {
int fromIndex = recordList.indexOf(startRecord) + 1;
int toIndex = recordList.indexOf(endRecord);
if(toIndex > fromIndex) {
List<LogRecord> recordSubList = recordList.subList(fromIndex, toIndex);
return parse(recordSubList, level);
} else {
return new ArrayList<LogProcess>();
}
}
private List<LogRecord> findStartEndRecord(LogRecord startRecord, List<LogRecord> recordList) {
List<LogRecord> startEndRecord = new ArrayList<LogRecord>();
if (!recordList.isEmpty()) {
startEndRecord.add(startRecord);
for (LogRecord record : recordList) {
boolean isStartRecord = record.isStartPoint() && record.hasSameActionName(startRecord);
if(isStartRecord){
startEndRecord = new ArrayList<LogRecord>();;
startEndRecord.add(record);
continue;
}
boolean isEndRecord = record.isEndPoint() && record.hasSameActionName(startRecord);
if (isEndRecord) {
startEndRecord.add(record);
return startEndRecord;
}
}
return startEndRecord;
}
return startEndRecord;
}
private LogRecord findStartRecord(List<LogRecord> recordList) {
for (LogRecord record : recordList) {
if (record.isStartPoint()){
recordList.remove(record);
return record;
}
}
return new NullLogRecord();
}
at the method calculatime in the for loop I just get the result for the first item, and after that I got error the same the title . please help me and explain me more for this case .
The name of this exception is a bit confusing, because it isn't related to multi threading.
What happens is that you are iterating over a collection which is being modified while you are iterating over it.
If performance is not your highest concern, a simple way out would be to copy the list and iterate over that copy and add items to the original list.
My guess is it's related to recordList.subList():
Returns a view of the portion of this list. [..] The returned list is backed by this list. [..] The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. [..] All methods first check to see if the actual modCount of the backing list is equal to its expected value, and throw a ConcurrentModificationException if it is not.
I don't see any modification, so it probably happens in findProcess(). Consider creating a copy of that list:
new ArrayList(recordList.subList())
You are getting the exception because of this :
for (LogRecord record : recordList) {
if (record.isStartPoint()){
recordList.remove(record); <--- This is the cause
return record;
}
}
Use an Iterator Instead
Iterator<LogRecord> iterator = recordList.iterator();
while(iterator.hasNext()){
LogRecord logRecord = iterator.next();
if(record.isStartPoint()){
iterator.remove();
return logRecord;
}
Check if this works

userobjs cannot be resolved to a variable

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.

Why doesn't the Sort method of my Linked List work? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to implement a sort method for a Singly Linked List. The method is suppose to go through the list, compare a pair of nodes, and place one of these at the front if needed. It uses two other methods: - Remove() (removes a specific node from list)
- InsertFront() (Insert a new node at the front of the list.
Both of these methods work by themselves and everything compiles.
public Link remove(String lastName)
{
Link current_ = first_;
Link prior_ = null;
Link found_ = null;
while (current_ != null && current_.lastName.compareTo(lastName) != 0)
{
prior_ = current_;
current_ = current_.next;
}
if(current_ != null)
{
if(prior_ == null)
{
found_ = first_;
System.out.println(current_.next.lastName);
first_ = current_.next;
}
else if(current_ == last_)
{
found_ = last_;
Link hold_ = first_;
first_ = prior_;
first_.next = current_.next;
first_ = hold_;
}
else
{
found_ = current_;
Link hold_ = first_;
first_ = prior_;
first_.next = current_.next;
first_ = hold_;
}
}
return found_;
}
public void insertFront(String f, String m, String l)
{
Link name = new Link(f, m, l);
if (isEmpty())
{
System.out.println("Adding first name");
first_ = name;
last_ = name;
}
else
{
System.out.println("Adding another name");
Link hold_ = first_;
first_ = last_;
first_.next = name;
last_ = first_.next;
first_ = hold_;
}
}
I have tried to fix it but I always run into two different problems:
It works but does not insert the link back in.
public void Sort()
{
Link temp_;
boolean swapped_ = true;
while (swapped_ == true)
{
swapped_ = false;
Link current_ = first_;
String comp_ = current_.lastName;
while (current_ != null && current_.lastName.compareTo(comp_) >= 0)
{
current_ = current_.next;
}
if (current_ != null)
{
temp_ = remove(current_.lastName);
insertFront(temp_.firstName, temp_.middleName, temp_.lastName);
swapped_ = true;
}
}
}
I receive a Null Pointer Exception.
Exception in thread "main" java. lang. NullPointerException
at List $ Link . access $000(List . java : 25)
at List . Sort ( List . java:165)
at main( java :79)
Java Result: 1
DeBugging results in:
Listening on javadebug
Not able to submit breakpoint LineBreakpoint LinearGenericSearch.java : 28, reason: The breakpoint is set outside of any class.
Invalid LineBreakpoint LinearGenericSearch.java : 28
User program running
Debugger stopped on uncompilable source code.
User program finished
public void Sort()
Link temp_;
boolean swapped_ = true;
while (swapped_ == true)
{
Link current_ = first_;
swapped_ = false;
while (current_.next != null)
{
if((current_.lastName.compareTo(current_.next.lastName)) > 0)
{
temp_ = remove(current_.next.lastName);
insertFront(temp_.firstName, temp_.middleName, temp_.lastName);
swapped_ = true;
}
current_ = current_.next;
}
}
}
My question is: What am I doing wrong? Any advice on how to avoid this next time?
In java you don't have to do all this manually!! Just use LinkedList, code for the
compareTo()
by implementing
Comparable Interface
(http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html) and call
Collections.sort(List list, Comparator c)
(http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html)
to sort the way how ever you want to.

Categories

Resources