parsed this xml in java code, but problem is that i want to calculate lost percentage will be calculated by adding the lostperc of both direction(upstream,downstream). Below is the Java Code So far What I have Done.
<RR cid="1460458819000" sid="92555" eod="0">
<RR1 direction="0" statStatus="1792" lostperc="1" />
<RR1 direction="1" statStatus="1792" lostperc="1" />
</RR>
InputStream inputStream = new FileInputStream(file);// here I put above Xml
List<AccedianWrapper> accedianWrappers =accedianResponse.getList();
for (AccedianWrapper accedianWrapper : accedianWrappers) {
String dir = accedianWrapper.getDirection();
if (dir.equals("0") || dir.equals("1")) {
System.out.println("direction " + dir);
lstPer = Integer.valueOf(accedianWrapper.getLostperc());
System.out.println(lstPer);
}
//
lstPer = Integer.valueOf(accedianWrapper.getLostperc());
//System.out.println(lstPer);
if (lstPer >= 1) {
if (!alrtCount.containsKey(lid)) {
alrtCount = Collections.singletonMap(lid, count);
} else {
int countn = alrtCount.get(lid);
alrtCount = Collections.singletonMap(lid, countn + 1);
if(countn > 4) {
System.out.println("get 5 times consecutive lost percentage");
alrtCount = Collections.singletonMap(lid, count);
}
}
System.out.println(alrtCount);
} else{
if (alrtCount.containsKey(lid)) {
alrtCount = Collections.singletonMap(lid, count);
}
}
}
From accedianResponse I get List Of accedianWrapper which Is POjo and Having Element of Xml,By Iterating Over AccedianWrapper i get LostPerc and Direction as well.But My Requirement is to Combine the Direction=0 and Direction=1 and Add the lostperc, currently i a getting Single row one by one in loop getting lostperc.
I am sorry if i written anything wrong .... please help me out.....
Related
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);
}
}
}
}
When the code is ran the nested loop causes it to create occasional duplicate entries to the system, i have spent a while looking through this but still cant find what is causing this, would greatly appreciate any help?
for(int i = 0; i < subWorkItemElement.getChildNodes().getLength(); i++) {
Boolean test = false;
WorkItemCommon existingChild = null;
String summary = null;
if(subWorkItemElement.getChildNodes().item(i).getNodeName().equals("workitem")) {
// We know it's a work item - but is it in the existing list?
Element childWorkItem = (Element) subWorkItemElement.getChildNodes().item(i);
for(int j = 0; j < subWorkItemElement.getChildNodes().getLength(); j++) {
if(childWorkItem.getChildNodes().item(j) instanceof Element) {
if(((Element)childWorkItem.getChildNodes().item(j)).getNodeName().equals("details")) {
summary = ((Element) childWorkItem.getChildNodes().item(j)).getElementsByTagName("summary")
.item(0).getTextContent();
for(String k : userInfoHashMap.keySet()) {
summary = summary.replace("${" + k + "}", userInfoHashMap.get(k));
}
if(childHashTable.containsKey(summary)) {
test = true;
existingChild = childHashTable.get(summary);
IWorkItem workItem = existingChild.getWorkItem();
System.out.println("INFO: The task with summary \"" + summary + "\" already exists. Skipping creation.");
System.out.println("this task is work item: " + workItem.getId());
//either check the tasks in the xml for updated details and then modify the existing workitem
//or just modify the work item without checking for updates
makeChildTask(childWorkItem, existingChild, childHashTable, userInfoHashMap, workItemHashMap, rtc, false);
break;
}
}
}
}
if(!test) {
System.out.println("INFO: The task with summary " + summary + " does not currently exist. Creating.");
makeChildTask(childWorkItem, thisItem, childHashTable, userInfoHashMap, workItemHashMap, rtc, true);
} else makeFromExistingChildTask(childWorkItem, existingChild, userInfoHashMap, workItemHashMap, rtc);
}
}
You are possibly (not sure what makeChildTask() does) changing an XML structure while iterating through the children list. While not necessarily incorrect, this can mean you get entries inserted while you process the list. Since you call the subWorkItemElement.getChildNodes().getLength() each time instead of cache'ing it, this might result in the length changing in between the loop iterations.
I need to parse a large XML file (probably going to use StAX in Java) and output it into a delimited text file and I have a couple of design questions. First here is an example of the XML
<demographic>
<value>001</value>
<question>Name?</question>
<value>Bob</value>
<question>Last Name?</question>
<value>Smith</value>
<followUpQuestions>
<question>Middle Init.</question>
<value>J</value>
</followUpQuestions>
</demographic>
this would need to be outputted (in the delimited output file) as
001~Bob~Smith~J
so here are my questions:
How can I distinguish between all the different "value" tags, since the tag names are not unique. Currently I tried to resolve this by having 'state' variables that turn on once they pass question-text such as "Name?", however this approach doesnt really work for the first value since I have to check to make sure the 'name' and 'lastName' states are off to ensure I'm getting the first value.
Everytime the client changes the text of the questions (which happens) I have to change the code and recompile it. Is there anyway to avoid this? Maybe save the questions-text in a text file that the program reads in?
Can this be scalable? I need to extract over 100 values and the XML files are usually about 2 gigs large.
Thank you, in advance, for your help (from a Java and XML newbie)!!
UPDATE: here is my attempt to code the solution, can someone please help to streamline? There has to be a less messy way to do this:
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;
class TestJavaForStackOverflow{
boolean nameState = false,
lastNameState = false,
middleInitState = false;
String name = "",
lastName = "",
middleInit = "",
value = "";
public void parse() throws IOException, XMLStreamException{
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(
new FileReader("/n04/data/revmgmt/anthony/scripts/Java_Programs/TestJavaForStackOverflow.xml"));
while(streamReader.hasNext()){
streamReader.next();
if(streamReader.getEventType() == XMLStreamReader.START_ELEMENT){
if("demographic".equals(streamReader.getLocalName())){
parseDemographicInformation(streamReader);
}
}
}
System.out.println(value + "~" + name + "~" + lastName + "~" + middleInit);
}
public void parseDemographicInformation(XMLStreamReader streamReader) throws XMLStreamException {
while(streamReader.hasNext()){
streamReader.next();
if(streamReader.getEventType() == XMLStreamReader.END_ELEMENT){
if("demographic".equals(streamReader.getLocalName())){
return;
}
}
else if(streamReader.getEventType() == XMLStreamReader.START_ELEMENT){
if("question".equals(streamReader.getLocalName())){
streamReader.next();
if("Name?".equals(streamReader.getText())){
nameState = true;
}
else if("Last Name?".equals(streamReader.getText())){
lastNameState = true;
}
else if("Middle Init.".equals(streamReader.getText())){
middleInitState = true;
}
}
else if("value".equals(streamReader.getLocalName())){
streamReader.next();
if(nameState){
name = streamReader.getText();
nameState = false;
}
else if (lastNameState){
lastName = streamReader.getText();
lastNameState = false;
}
else if (middleInitState){
middleInit = streamReader.getText();
middleInitState = false;
}
else {
value = streamReader.getText();
}
}
}
}
}
public static void main(String[] args){
TestJavaForStackOverflow t = new TestJavaForStackOverflow();
try{t.parse();}
catch(IOException e1){}
catch(XMLStreamException e2){}
}
}
I think the flags are not very scalable if you have a lot of different questions to parse, and neither are the global variables to hold the results... if you have 100 questions then you'll need 100 variables, and when they change over time it will be a bear to keep them up to date. I would use a map structure to hold the result, and another one to hold the correspondence between each question text and the corresponding field you are trying to capture (this is not actual Java, just an approximation):
public Map parseDemographicInformation(XmlStream xml, Map questionMap) {
Map record = new Map();
String field = "id";
while((elem = xml.getNextElement())) {
if(elem.tagName == "question") {
field = questionMap[elem.value];
} else if(elem.tagName == "value") {
record[field] = elem.value;
}
}
return record;
}
Then you have something like this to output the result:
String[] fieldsToOutput = { "id", "firstName", "lastName" }; // ideally read this from a file too so it can be changed dynamically
// ...
for(int i=0; i < fieldsToOutput.length; i++){
if(i > 0)
System.out.print("~");
System.out.print(record[fieldsToOutput[i]]);
}
System.out.println();
I am fetching the comments for a video using Youtube's Java API. I want to know can I find the number of up votes or down votes for all the comment. If yes then how. Currently I am using the code given below. I am getting totalRating for each comment to find upvotes but every-time it outputs 0. I know this is wrong but how do I get the vote up and down for comments.Any pointers in the right direction will be appreciated. Thanks.
private void AddComments(YouTubeVideo ytv,VideoEntry videoEntry,YouTubeService service)
{
try
{
//Get Comments
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
LinkedList<YouTubeComment> commentsLinkedList = new LinkedList<YouTubeComment>();
if(commentUrl!= null && commentUrl.length() > 0)
{
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
if(commentFeed != null)
{
for(CommentEntry comment : commentFeed.getEntries())
{
YouTubeComment youtubeComment = new YouTubeComment();
if(comment.getTotalRating()!=null)
**//comment.getTotalRating() is always equal to 0.**
youtubeComment.setLike(comment.getTotalRating());
else
youtubeComment.setLike(0);
youtubeComment.setSpamStatus(comment.hasSpamHint());
String commentinVideo = comment.getPlainTextContent();
if(commentinVideo != null)
youtubeComment.setComment(comment.getPlainTextContent());
else
youtubeComment.setComment(" ");
commentsLinkedList.add(youtubeComment);
}
ytv.setComments(commentsLinkedList);
}
else
ytv.setComments(commentsLinkedList);
}
else
{
ytv.setComments(commentsLinkedList);
}
}
catch(Exception ex)
{ // This means that "Comments are disabled for this video."
LinkedList<YouTubeComment> comments = new LinkedList<YouTubeComment>();
ytv.setComments(comments);
System.out.println("Could not add comments for video := " + videoUrl);
System.out.println("This happens when comments are disabled for the video");
System.out.println("Exception in function AddComments : " + ex.toString());
}
}
Unfortunately, those values are not exposed via the API, and there are no plans to add them.
i have a list of url's i need to filter specific domain and subdomain. say i have some domains like
http://www.example.com
http://test.example.com
http://test2.example.com
I need to extract urls which from domain example.com.
Working on project that required me to determine if two URLs are from the same sub domain (even when there are nested domains). I worked up a modification from the guide above. This holds out pretty well thus far:
public static boolean isOneSubdomainOfTheOther(String a, String b) {
try {
URL first = new URL(a);
String firstHost = first.getHost();
firstHost = firstHost.startsWith("www.") ? firstHost.substring(4) : firstHost;
URL second = new URL(b);
String secondHost = second.getHost();
secondHost = secondHost.startsWith("www.") ? secondHost.substring(4) : secondHost;
/*
Test if one is a substring of the other
*/
if (firstHost.contains(secondHost) || secondHost.contains(firstHost)) {
String[] firstPieces = firstHost.split("\\.");
String[] secondPieces = secondHost.split("\\.");
String[] longerHost = {""};
String[] shorterHost = {""};
if (firstPieces.length >= secondPieces.length) {
longerHost = firstPieces;
shorterHost = secondPieces;
} else {
longerHost = secondPieces;
shorterHost = firstPieces;
}
//int longLength = longURL.length;
int minLength = shorterHost.length;
int i = 1;
/*
Compare from the tail of both host and work backwards
*/
while (minLength > 0) {
String tail1 = longerHost[longerHost.length - i];
String tail2 = shorterHost[shorterHost.length - i];
if (tail1.equalsIgnoreCase(tail2)) {
//move up one place to the left
minLength--;
} else {
//domains do not match
return false;
}
i++;
}
if (minLength == 0) //shorter host exhausted. Is a sub domain
return true;
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
return false;
}
Figure I'd leave it here for future reference of a similar problem.
I understand you are probably looking for a fancy solution using URL class or something but it is not required. Simply think of a way to extract "example.com" from each of the urls.
Note: example.com is essentially a different domain than say example.net. Thus extracting just "example" is technically the wrong thing to do.
We can divide a sample url say:
http://sub.example.com/page1.html
Step 1: Split the url with delimiter " / " to extract the part containing the domain.
Each such part may be looked at in form of the following blocks (which may be empty)
[www][subdomain][basedomain]
Step 2: Discard "www" (if present). We are left with [subdomain][basedomain]
Step 3: Split the string with delimiter " . "
Step 4: Find the total number of strings generated from the split. If there are 2 strings, both of them are the target domain (example and com). If there are >=3 strings, get the last 3 strings. If the length of last string is 3, then the last 2 strings comprise the domain (example and com). If the length of last string is 2, then the last 3 strings comprise the domain (example and co and uk)
I think this should do the trick (I do hope this wasn't a homework :D )
//You may clean this method to make it more optimum / better
private String getRootDomain(String url){
String[] domainKeys = url.split("/")[2].split("\\.");
int length = domainKeys.length;
int dummy = domainKeys[0].equals("www")?1:0;
if(length-dummy == 2)
return domainKeys[length-2] + "." + domainKeys[length-1];
else{
if(domainKeys[length-1].length == 2) {
return domainKeys[length-3] + "." + domainKeys[length-2] + "." + domainKeys[length-1];
}
else{
return domainKeys[length-2] + "." + domainKeys[length-1];
}
}
}