I am trying to convert the below code in java 8, but not sure where I am going wrong. I have 2 code snippets which I want to convert. This is the first one:
for (WebElement value :values) {
WebElement dateElement = SharedWebDriver.getInstance()
.findOptionalElement(By.className("text"), value);
WebElement groupElement =
SharedWebDriver.getInstance().findOptionalElement(By.id("label"),
value);
WebElement typeElement =
SharedWebDriver.getInstance().findOptionalElement(By.id("type"),
value);
if (dateElement != null) {
dateValue = dateElement.getText().trim();
}
if (groupElement != null) {
groupValue = groupElement.getText().trim();
}
if(typeElement!= null){
typeValue = typeElement.getText().trim();
}
}
And here I want to set value using java 8. I tried it with using the filter option, but it's not working.
for (WebElement header : headers) {
if (header != null) {
if (header.getText().equals("A")) {
entry.setDate(dateValue);
} else if (header.getText().equals("B")) {
entry.setGroup(groupValue);
} else if (header.getText().equals("C")) {
entry.setType(typeValue);
}
}
}
Can anyone help me?
The problem with those code snippets is that they modifiy variables defined outside of the loop (dateValue, groupValue and typeValue for the first one, and entry for the second one).
But lambda expressions are not really supposed to alter variables that are not defined in their scope event though you can achieve that throught methods.
For example, inside a lambda expression :
word = "hello" will not work whereas website.setTitle("title") will
I converted your code snippets in Java 8, I didn't take the time to test it but if I am if i am not mistaken, the first one will not work whereas the second one will, for the reason explained above.
values.stream()
.map(value -> new WebElement[] {
SharedWebDriver.getInstance().findOptionalElement(By.className("text"), value),
SharedWebDriver.getInstance().findOptionalElement(By.id("label"), value)),
SharedWebDriver.getInstance().findOptionalElement(By.id("type"), value) })
.forEach(webElements[] -> {
if (webElements[0] != null) {
dateValue = webElements[0].getText().trim();
}
if (webElements[1] != null) {
groupValue = webElements[1].getText().trim();
}
if(webElements[2] != null){
typeValue = webElements[2].getText().trim();
}
});
headers.stream()
.filter(Objects::nonNull)
.forEach(header -> {
if (header.getText().equals("A")) {
entry.setDate(dateValue);
} else if (header.getText().equals("B")) {
entry.setGroup(groupValue);
} else if (header.getText().equals("C")) {
entry.setType(typeValue);
}
});
Related
I have a directory of three files in the body of a Camel exchange, and I'm going to iterate through those 3 files using a Split. What I would like to do, is for each iteration, update a property with the total of all files (3 for this example) minus the current iteration. So at the some point, the goal is to have a property set to 1, so on another part of the code I can do logic based on this. I've tried a couple of different approaches but failed, and here I am. Here's a snippet of something I tried (simplified):
`private void test() {
from("timer:test?fixedRate=true&period=10000")
.process(exchange -> {
Path pathD = FileSystems.getDefault().getPath("Lmao").toAbsolutePath();
File folder = new File(pathD.toString());
String[] fileList = folder.list();
if (fileList != null) {
exchange.setProperty("PROPERTY", fileList.length);
}
exchange.getIn().setBody(fileList);
})
.split(body(), new AggregationStrategy() {
#Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
Integer iterationsLeft = newExchange.getProperty("PROPERTY", Integer.class);
Integer iterationsLeftMinusOne = iterationsLeft - 1;
newExchange.setProperty("PROPERTY", iterationsLeftMinusOne);
return newExchange;
} else {
Integer iterationsLeft = oldExchange.getProperty("PROPERTY", Integer.class);
oldExchange.setProperty("PROPERTY", iterationsLeft - 1);
return oldExchange;
}
}
})
.process(exchange -> {
Integer test = exchange.getProperty("PROPERTY", Integer.class);
System.out.println(test);
})
.end();
}
`
This code keeps printing 3 all the time and I wanted 3,2,1
I am having a hard time writing a couple of lines of code. All my current codes are in: https://github.com/anabeen/MeetingJava
The problem that I have is, finding a suitable way to go through the hashmap and get the meetings that have overlapping times and replace them.
Map<LocalDate, Set<Meeting>> meetings = new HashMap<LocalDate, Set<Meeting>>();
Let's say we have a HashMap of
[{2011-03-21=[objectMeeting1, objectMeeting2]}]
and we need to add objectMeeting3 to that hashMap. How do I select the key "2011-03-21" to look at the objects in that hashmap and compare the set of objects in there with a new objectMeeting3's time (part of the data from object) and then replace that object?
In GitHub, I am trying to pass the MeetingSchedulerTest (). This is where I am stuck at:
Meeting meeting = extractMeeting(employeeId, requestLines[i],
officeStartTime, officeFinishTime, meetingSlotRequest1);
if(meetings.containsKey(meetingDate)){
// if the order overlaps
for (Map.Entry<LocalDate, Set<Meeting>> meetingEntry : meetings.entrySet()) {
if (meetingDate == meetingEntry.getKey())
{
Set<Meeting> setOfMeeting = meetingEntry.getValue();
for (Meeting m : setOfMeeting) {
}
}
}
// if the order doesn't
if (meetings.get(meetingDate) != null)
//shouldNotHaveOverlappingMeetings
{
System.out.println("HERES?");
meetings.remove(meetingDate);
Set<Meeting> meetingsForDay = new HashSet<Meeting>();
meetingsForDay.add(meeting);
meetings.put(meetingDate, meetingsForDay);
} else
{
System.out.println("HERES2?");
meetings.get(meetingDate).add(meeting);
}
}else if (meeting != null){
// if meeting doens't have meetingDate then create a new HashMap with date & Meeting
System.out.println("HERES3?");
Set<Meeting> meetingsForDay = new HashSet<Meeting>();
meetingsForDay.add(meeting);
meetings.put(meetingDate, meetingsForDay);
}
}
I figured out the answer by using this:
for (Map.Entry<LocalDate, Set<Meeting>> meetingEntry : meetings.entrySet()) {
if (meetingDate.equals(meetingEntry.getKey()))
{
System.out.println("HERES1? ");
Set<Meeting> setOfMeeting = meetingEntry.getValue();
for (Meeting m : setOfMeeting) {
System.out.println("comparing time? " + m.getStartTime().getHourOfDay() + " TO "
+ meeting.getStartTime().getHourOfDay());
if (m.compareTo(meeting) == 0) {
continue;
} else {
setToPut.add(m);
}
}
}
}
I need to convert the code below from java 7 to java 8.
I tried using the class 'Optional' to simplify it but haven't succeeded implementing it.
if(replacementResponse.getGroupResponse() != null)
{
for(GroupCommand groupCommand : replacementResponse.getGroupResponse().getValues())
{
String groupQuery = groupCommand.getName();
for(Group group : groupCommand.getValues())
{
if(!group.getResult().isEmpty())
{
SolrDocumentList solrDocuments = group.getResult();
List<SolrDocument> documentList = null;
if(result.get(groupQuery) != null)
documentList = result.get(groupQuery);
else
documentList = new LinkedList<>();
for(SolrDocument solrDocument : solrDocuments)
{
documentList.add(solrDocument);
}
result.put(groupQuery, documentList);
}
}
}
return result;
}
return null;
I tried splitting the method into 2 methods but I don't know how to implement 'Optional' inside streaming.
return Optional.ofNullable(replacementResponse.getGroupResponse())
.map(replacementGroupResponse -> getGroupResponse(replacementGroupResponse.getValues())).orElse(null);
documentList = Optional.ofNullable(result.get(groupCommand.getName())).orElse(new LinkedList<>());
replacementGroupResponse.stream()
.map(groupCommand -> groupCommand.getValues().stream()
.filter(group -> !group.getResult().isEmpty()).
You can try as following to migrate your java 7 code to java 8. There might be few issues because I don't know about the implementation of many classes like SolrDocumentList,GroupCommand,Group, etc..
return Optional.ofNullable(replacementResponse.getGroupResponse()).map(a -> a.getValues().stream()
.collect(Collectors.toMap(GroupCommand::getName,groupCommand -> groupCommand.getValues().stream()
.flatMap(group -> group.getResult().stream()).collect(Collectors.toCollection(LinkedList::new))))).orElse(null);
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.
I am trying to set session values as follows :
if (request.getParameter("page") != null) {
page = Integer.parseInt(request.getParameter("page").toString());
}
if (request.getParameter("se_tempcardnumber") != null) {
tempcardnumber = request.getParameter("se_tempcardnumber").toString();
session.setAttribute("session_tempcardnumber", tempcardnumber);
}
if (request.getParameter("se_empid") != null) {
empid = request.getParameter("se_empid").toString();
session.setAttribute("session_empid", empid);
}
if (request.getParameter("se_issuedate") != null) {
issuedate = request.getParameter("se_issuedate").toString();
session.setAttribute("session_issuedate",issuedate);
}
if (request.getParameter("se_cardstatus") != null) {
cardstatus = request.getParameter("se_cardstatus").toString();
session.setAttribute("session_cardstatus", cardstatus);
}
and i try to access the session values as follows :
if(session.getAttribute("session_empid")!=null) {
session_empid =(String)session.getAttribute("session_empid");
}
if(session.getAttribute("session_tempcardnumber")!=null) {
session_tempcardnumber =(String)session.getAttribute("session_tempcardnumber");
}
if(session.getAttribute("session_issuedate")!=null) {
session_issuedate =(String)session.getAttribute("session_issuedate");
}
if(session.getAttribute("session_cardstatus")!=null) {
session_cardstatus =(String)session.getAttribute("session_cardstatus");
System.out.println("session_cardstatus : "+session_cardstatus);
}
for testing purpose i set values for System.out.println("session_cardstatus : "+session_cardstatus); alone and i printed the same thing.
it is getting printed for the first time but when it comes to second time the value is empty though i don't remove anywhere those set variables in session.
Please advise me how to go about;
thanks and regards
check the session id which is generated before setting values in to session
request.getRequestedSessionId() or session.getId()