limit to display 50 from all the data - java

hello there i'm a little bit confuse with this code....sorry for my bad grammar..still new in this java.
private void loadSessionEvents() {
ArgumentBuilder arg = new ArgumentBuilder();
arg.addArg(getSessionLogId());
DBResult result = DBOperator.getInstance().doOperation(
FileOperation.class, "loadSessionLogEvents", arg.getTypeInfo());
// ArrayList<MsmLogIveScreenshots> logEvent =
// (ArrayList<MsmLogIveScreenshots>) result
// .getValue("RETURN");
// setSessionLogEvents(logEvent);
ArrayList<Object> logList = (ArrayList<Object>) result
.getValue("RETURN");
ArrayList<SessionLogEventModel> windowLogs = null;
if (ValidationUtils.nonNullAndNotEmpty(logList)) {
windowLogs = new ArrayList<SessionLogEventModel>();
for (int i = 0; i < logList.size(); i++) {
Object obj = logList.get(i);
if (obj instanceof MsmLogIveScreenshots) {
SessionLogEventModel log = convertSessionLogToModel((MsmLogIveScreenshots) obj);
windowLogs.add(log);
} else if (obj instanceof MsmDbAuditOracle) {
SessionLogEventModel log = convertOracleLogToModel((MsmDbAuditOracle) obj);
windowLogs.add(log);
}
}
setSessionLogEventModel(windowLogs);
}
i understand that for loop will eventually load all the data..but what i want is it will still load all the data but only choose 50 list of data to show in jsp..sorry again for my grammar..

The most common practise here is to take the 50 most recent values. So what I would do is check the length, and use subList.
Example
if(logList.size() > 50)
{
// you've got more than 50 objects here.
logList = logList.subList(logList.size() - 50, logList.size());
}
If you have less than or equal to 50 elements in your List, then there's no need to cut it.

Related

How to Iterate over too big ArrayList<String>?

I have two ArrayList sourceMessageList and TargetMessageList. I need to compare both the message list data.
Now lets say List1 - 100 Records. List2 - 1000 records
From List1- 1st record is compared with each record in list2 and then List1- 2nd record is compared with each record in list2.
But list2 is getting the value hasNext() to true for 1st source data in list1.
private void compareMessageList(ArrayList<String> source_messageList, ArrayList<String> target_messageList)
throws Exception {
// TODO Auto-generated method stub
Iterator<String> sourceMessageIterator = source_messageList.iterator();
Iterator<String> targetMessageIterator = null;
while (sourceMessageIterator.hasNext()) {
String sourceMessage = (String) sourceMessageIterator.next();
targetMessageIterator = target_messageList.iterator();
while (targetMessageIterator.hasNext()) {
String targetMessage = (String) targetMessageIterator.next();
if (getCorpValue(sourceMessage).equalsIgnoreCase(getCorpValue(targetMessage))) {
assertXMLEquals(convertSwiftMessageToXML(sourceMessage), convertSwiftMessageToXML(targetMessage));
}
}
}
if (buffer.toString().length() > 0) {
writeDifferenceTofile(buffer.toString());
buffer.delete(0, buffer.length());
throw new CatsException("There are some differences in the files.");
}
System.out.println("Exiting now ...");
}
The above code is taking too much time to execute.
To speed things up:
HashMap<String, String> lowers = new HashMap<String, String>();
for (String source : source_messageList) {
lowers.put(getCorpValue(source).toLowerCase(), source);
}
for (String target : target_messageList) {
final String corpTarget = getCorpValue(target).toLowerCase();
if(lowers.containsKey(corpTarget)) {
assertXMLEquals(
convertSwiftMessageToXML(lowers.get(corpTarget)),
convertSwiftMessageToXML(target)
);
}
}

how to improve code quality (mostly duplicates)

I have a set of variables that was passed in by a mega method in an ancient legacy code.....
public List<type> check (String required, String sales, String report,
Long passId, Long seatId, String capName, String vCapName,
String attName, Long vid) {
if(required != null) {
goodA = method(required);
goodB = methodTwo(required);
goodC = methodThree(required);
}
if(sales != null) {
goodA = method(sales);
goodB = methodTwo(sales);
goodC = methodThree(sales);
}
if(report != null) {
goodA = method(report);
goodB = methodTwo(report);
goodC = methodThree(report);
if(passId != null)
... you got the point....
}
The variables that passed into check can only be 1 valid value all other variables will become null.
For example
check("Yes",null,null,null,null,null...)
or
check(null,null,null,13212L,null,null,null,null)
right now I am trying to rewrite this into something less repetitive and clean I was wondering if anyone can provide some ideas on how to do this.
How about something like this?
List<Object> items = Lists.newArrayList(required, sales, report,
capName, vCapName, attName);
for(Object item : items) {
if(item != null){
methodOne(item);
methodTwo(item);
methodThree(item);
}
}

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

Storing the details in list and then on inspecting storing in different list

I have a pojo like this..
public class abcObject {
private long id;
private long version;
private DateTime created ;
private String status;
}
and its corresponding hbm as internally it data is being stored in the table through hibernate now please advise as the status can have values like pass or failNow i have to filter the value whether it is pass or fail as rite now i can check its value by inspecting and depending upon that I have to put them into the seprate list, I have done through this way
List<abcObject> successful = new ArrayList <abcObject>();
List<abcObject> exception = new ArrayList <abcObject>();
List<abcObject> failure = new ArrayList <abcObject>();
//getting the list from the database into the parameter allabcObjects
List<abcdObject> allabcObjects = abcHome.getabcObjects(fileIdentifier);
if (abcObjects !=null && abcObjects.size() > 0) {
for (abcObject f : allabcObjects) {
}
Now please advise as I am using the for loop to iterate over each object then how by inspecting that is f.getstatus() method and if it is fail then it should stote all the details in fail list and if it it is success then it should store in successful list , please advise how to achieve this
Just compare object with your strings
List<abcObject> successful = new ArrayList <abcObject>();
List<abcObject> exception = new ArrayList <abcObject>();
List<abcObject> failure = new ArrayList <abcObject>();
//getting the list from the database into the parameter allabcObjects
List<abcdObject> allabcObjects = abcHome.getabcObjects(fileIdentifier);
if (abcObjects !=null && abcObjects.size()>0)
{
for (abcObject f : allabcObjects) {
if( "pass".equalsIgnoreCase(f.getStatus()) ) {
successful.add( f );
} else if ( "failNow".equalsIgnoreCase(f.getStatus()) {
failure.add( f );
}
}
}
Just to point out some things. Even better would be to create static final string, for your success / fail string like this:
private static final String SUCCESS = "success";
private static final String FAIL = "failNow";
....
if( SUCCESS.equalsIgnoreCase(f.getStatus()) ) {
successful.add( f );
} else if ( FAIL.equalsIgnoreCase(f.getStatus()) {
failure.add( f );
}
Comparing SUCCESS with f.getStatus(), instead of inverse, gives us certainty that there won't be NullPointerException if somehow f would be null
Your for loop would read:
for (abcObject f : allabcObjects) {
String status = f.getstatus();
if(status.equals("fail")){
failure.add(f);
}
else{
otherList.add(f);
}
}
You'll also need to declare the otherList, i.e.
List<abcObject> otherList = new ArrayList<abcObject>();
This assumes that your getstatus() method returns a String "fail" if it fails.

Searching in an Array that is parsed from a XML in Android

I have this XML file which I parse into an ArrayList
In this ArrayList I have countries and the alarmnumbers for the countries in it.
I want to search to a country and get it's police, ambulance or firedep. number.
Here is the code to help you out.
Parsing XML into ArrayList:
protected ArrayList<Alarmdiensten> getAlarmdiensten() {
ArrayList<Alarmdiensten> lijst = new ArrayList<Alarmdiensten>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
land.politie = Xml.innerHtml(Xml.getChildByTagName(node, "politie"));
land.ambulance = Xml.innerHtml(Xml.getChildByTagName(node, "ambulance"));
land.brandweer = Xml.innerHtml(Xml.getChildByTagName(node, "brandweer"));
land.telamba = Xml.innerHtml(Xml.getChildByTagName(node, "telamba"));
land.adresamba = Xml.innerHtml(Xml.getChildByTagName(node, "adresamba"));
lijst.add(land);
}
} catch (Exception e) {;
}
return lijst;
}
The method that will use the alarmnumbers:
public void AlarmMenu(){
String landcode;
ArrayList<Alarmdiensten> diensten = getAlarmdiensten();
if(fakelocation = true) {
landcode = sfakelocation;
}
else {
try {
landcode = getAddressForLocation(this, locationNow).getCountryCode();
} catch (IOException e) {
e.printStackTrace();
}
}
So I have the landcode, and I want to search in the ArrayList diensten for the numbers that belong with the landcode.
How can I do this?
Well at the moment you've got an ArrayList of Alarmdiensten objects. I would suggest you might want to change that to a Map so that you are storing a Map of land codes vs your Alarmdiensten objects.
That way you get the Alarmdiensten out of the Map using the landcode and then simply call the getPolitie() etc methods on your Alarmdiensten object.
I would make sure that you encapsulate your Alarmdiensten object BTW, accessing it's private members directly is a bit of a no-no :)
So something like:
protected Map<String, Alarmdiensten> getAlarmdiensten()
{
Map<String, Alarmdiensten> alarmNumbersForCountries
= new HashMap<String, Alarmdiensten>();
try
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i = 0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.setLand(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
land.setLandcode(Xml.innerHtml(Xml.getChildByTagName(node, "code")));
land.setPolitie(Xml.innerHtml(Xml.getChildByTagName(node, "politie")));
land.setAmbulance(Xml.innerHtml(Xml.getChildByTagName(node, "ambulance")));
land.setBrandweer(Xml.innerHtml(Xml.getChildByTagName(node, "brandweer")));
land.setTelamba(Xml.innerHtml(Xml.getChildByTagName(node, "telamba")));
land.setAdresamba(Xml.innerHtml(Xml.getChildByTagName(node, "adresamba")));
alarmNumbersForCountries.put(land.getLandCode(), land);
}
}
catch (Exception e)
{
// Handle Exception
}
return alarmNumbersForCountries;
}
To get the entry out of the Map
Alarmdiensten land = alarmNumbersForCountries.get(landcode);
Another YMMV point is that you might want to split out the part of your method that builds Alarmdiensten objects from the XML parsing. "Each method should do one thing and one thign well."
Use a for loop and search for it
for(Alarmdiensten land :diensten){
if(land.landcode.equals(landcode) ){
// yes i got it, The current land.
break;
}
}
Just iterate over the list:
String landcode = getLandCode();
for (Alarmdiensten dienst:diensten) {
if (dienst.landcode.equals(landcode)) {
// do what has to be done
}
}
Consider using a map instead of a list, if you have to lookup the values more frequently:
Map<String, List<Alarmdiensten>> servicesInCountry
= new HashMap<String, List<Alarmdiensten>>();
for (Alarmdiensten dienst:diensten) {
List<Alarmdiensten> list = servicesInCountry.get(dienst.landcode);
if (list == null) {
list = new ArrayList<Alarmdiensten>();
servicesInCountry.put(dienst.landcode, list);
}
list.add(dienst);
}
// ... and later on
List<Alarmdiensten> servicesInSweden = servicesInCountry.get("SWE");

Categories

Resources