How to display the first row of results from extracted data? - java

I used the following script to read a CSV file and extract suspicious data in descending order. I am trying to print out the result of the highest occurrence which is the first result showing. Should I specify it in the map script? Can I utilize println to show that?
public class Part2 {
public static void main(String[] args) {
try (Scanner csvData = new Scanner(
new File("C:\\Users\\amber\\Documents\\IN300_Dataset1.csv"))) {
List<String> list = new ArrayList<String>();
while (csvData.hasNext()) {
list.add(csvData.nextLine());
}
String[] tempArray = list.toArray(new String[1]);
String[][] csvArray = new String[tempArray.length][];
String combined_list[] = new String[tempArray.length];
String myData = null;
for(int i=0; i < tempArray.length; i++) {
if(i == 0) continue;
csvArray[i] = tempArray[i].split(",");
if(csvArray[i][4].matches("^\"[a-zA-Z].*\"")) {
continue;
}
else {
myData= csvArray[i][2] + " " +
csvArray[i][3] + " " +
csvArray[i][4] + " " +
csvArray[i][5] + " " +
csvArray[i][6];
combined_list[i] = myData;
}
}
getOccurences("Suspicious Result(s)", combined_list);
}
catch(Exception e) {
System.out.println(e);
}
}
private static void getOccurences(String message, String[] myArray) {
Map<String, Integer> map = new HashMap<>();
for (String key : myArray) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
Map<String, Integer> sortedMap =
map.entrySet().stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
printMap(message, sortedMap);
}
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
map.forEach((key, value) -> {
if(key != null && value > 100) {
System.out.println(key + "appeared " + value + " times(s).");
}
});
}
}
Here is a sample of my results (The bold text is the result that I only want to display):
PrintingSuspicious Result(s)
00:28:00:01:00:00 02:00:00:00:45:00 0x4006 44 Ethernet IIappeared 7536 times(s).
209.99.61.21 192.168.1.24 UDP 1359 17212 > 52797 Len=1309appeared 2990 times(s).
192.168.1.24 209.99.61.21 UDP 170 52797 > 17212 Len=128appeared 2905 times(s).
209.99.61.21 192.168.1.24 UDP 1351 17212 > 52797 Len=1309appeared 2851 times(s).

If you want to display only the first result, just quit the loop after displaying the first element (you'll have to use normal for loop instead of using forEach to be able to break):
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey() != null && entry.getValue() > 100) {
System.out.println(entry.getKey() + "appeared " + entry.getValue() + " times(s).");
break;
}
}
}

Related

If I have two keys with equal value, how do I return a Set<String> kinda (value + " - " + key ", " + key)?

This code works only when I have a pair like name(value) + number(key), but I'm stuck with situation like - name + number, number. It returns name + number1, name + number2
public Set<String> getAllContacts() {
TreeSet<String> contacts = new TreeSet<>();
if (phoneBook.isEmpty()) {
return new TreeSet<>();
} else {
for (Map.Entry<String, String> entry : phoneBook.entrySet()) {
contacts.add(entry.getValue() + " - " + entry.getKey());
}
}
return contacts;
}
Basically you want to invert key and value of your phoneBook map. Since one name can have multiple numbers according to your example the output structure should be Map<String, List<String>>. With this name oriented phone book you can easily create your contact collection. E.g.
Map<String, List<String>> phoneBookByName = new HashMap<>();
phoneBook.forEach((k, v) -> {
List<String> numbers = phoneBookByName.computeIfAbsent(k, s -> new ArrayList<>());
numbers.add(v);
});
TreeSet<String> contacts = new TreeSet<>();
phoneBookByName.forEach((k, v) -> contacts.add(k + " - " + String.join(", ", v)));
return contacts;
or using streams
Map<String, List<String>> phoneBookByName = phoneBook.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
return phoneBookByName.entrySet().stream()
.map(entry -> entry.getKey() + " - " + String.join(", ", entry.getValue()))
.collect(Collectors.toCollection(TreeSet::new));

Regex to get particular values from a string data

While executing a particular shell command am getting following output as follows and keeping this in a string variable
dat /var/france.log
exit
bluetooth_mac=45h6kuu
franceIP=testMarmiton
build_type=BFD
france_mac=F4:0E:83:35:E8:D1
seloger_mac=F4:0E:83:35:E8:D0
tdVersion=1.2
td_number=45G67j
france_mac=fjdjjjgj
logo_mac=tiuyiiy
logout
Connection to testMarmiton closed.
Disconnected channel and session
From this i have too fetch particular details like below and put htese values in a Map. How i can perform this using java.
bluetooth_mac=45h6kuu
build_type=BFD
tdVersion=1.2
seloger_mac=F4:0E:83:35:E8:D0
france_mac=fjdjjjgj
Map<String, String> details =new HashMap<String,String>();
details.put(bluetooth_mac, 45h6kuu);
details.put(build_type, BFD)
etc
etc
Solution 1
If you are using Java 8 you can use :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, String> result = stream
.filter(line -> line.matches("\\w+=\\w+"))
.map(line -> line.split("="))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
{franceIP=testMarmiton, bluetooth_mac=45h6kuu, logo_mac=tiuyiiy, td_number=45G67j, france_mac=fjdjjjgj, build_type=BFD}
Solution 2
It seems that you have multiple line which have the same name, in this case I would like to group by a Map<String, List<String>> :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> result = stream
.filter(line -> line.matches("[^=]+=[^=]+")) // filter only the lines which contain one = signe
.map(line -> line.split("=")) // split with = sign
.collect(Collectors.groupingBy(e -> e[0], Collectors.mapping(e -> e[1], Collectors.toList())));
result.forEach((k, v) -> System.out.println(k + " : " + v));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
franceIP : [testMarmiton]
bluetooth_mac : [45h6kuu]
logo_mac : [tiuyiiy]
td_number : [45G67j]
seloger_mac : [F4:0E:83:35:E8:D0]
france_mac : [F4:0E:83:35:E8:D1, fjdjjjgj]
tdVersion : [1.2]
build_type : [BFD]
public static void main(String[] args) {
String str="abc def \n"
+ "key=123 \n "
+ "pass=456 \n"
+ "not working";
String[] sarray=str.split("\\r?\\n");
for (String eachline : sarray) {
System.out.println("line " + " : " + eachline);
if(eachline.contains("="))
{
String[] sarray2=eachline.split("=");
System.out.println("key:" +sarray2[0] +":Value:"+ sarray2[1]);
}
}
System.out.println(""+sarray.length);
}
Use split("\r?\n") for new line splitting.
You could try:
Pattern re = Pattern.compile("^\\s*(.*)\\s*=(.*)$", Pattern.MULTILINE);
Matcher matcher = re.matcher(input);
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
Here's a complete example, extracting the value using regex-matching and building a HashMap (the appropriate map for key-value pairs). You can copy the whole program and run it yourself:
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class main {
public static void main(String[] args) {
String input = // Your input log
"dat /var/france.log\n" +
"\n" +
"exit\n" +
"\n" +
"root#france24:~# \n" +
"root#france24:~# dat /var/france.log\n" +
"bluetooth_mac=45h6kuu\n" +
"franceIP=testMarmiton\n" +
"build_type=BFD\n" +
"france_mac=F4:0E:83:35:E8:D1\n" +
"seloger_mac=F4:0E:83:35:E8:D0\n" +
"tdVersion=1.2\n" +
"td_number=45G67j\n" +
"france_mac=fjdjjjgj\n" +
"logo_mac=tiuyiiy\n" +
"root#france24:~# \n" +
"root#france24:~# exit\n" +
"logout\n" +
"Connection to testMarmiton closed.\n" +
"\n" +
"Disconnected channel and session";
String[] keys = {
"bluetooth_mac",
"build_type",
"tdVersion",
"seloger_mac",
"france_mac"
};
HashMap<String, String> map = new HashMap<>();
for(String key : keys){
String value = getValueOf(input, key);
if(value != null)
map.put(key, value);
}
for(String key : keys)
System.out.println(key + " = " + map.get(key));
}
public static String getValueOf(String input, String key){ //returns null if not found
String result = null;
Pattern pattern = Pattern.compile(key + "=.*+\\s");
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
result = matcher.group();
result = result.substring(result.indexOf('=') + 1, result.length() - 1);
}
return result;
}
}
Output (add more keys to the key-string if you want get more values):
bluetooth_mac = 45h6kuu
build_type = BFD
tdVersion = 1.2
seloger_mac = F4:0E:83:35:E8:D0
france_mac = F4:0E:83:35:E8:D1

Get the json path of a value with jackson

I'm trying to retrieve the json path of a value from a json string with jackson. As I couldn't find any function inside jackson giving me this result, I wanted to create my own function.
So I made this function :
public static String getJsonPath(Map.Entry<String, JsonNode> jsonNode, String valueSearched) {
String res = "";
String key = jsonNode.getKey();
JsonNode value = jsonNode.getValue();
if (value.isValueNode() && value.equals(valueSearched)) { // Here the value change to a ValueNode and the key weirdly equals to "".
return res + key;
} else {
if (value.isContainerNode()) {
if (value.isObject()) {
Iterator<Map.Entry<String, JsonNode>> elements = value.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
res += "." + element.getKey() + generateJsonPathArgumentFromJson(element, valueSearched);
}
} else {
int i = 0;
ArrayNode arrayNode = (ArrayNode) jsonNode;
Iterator<Map.Entry<String,JsonNode>> elements = arrayNode.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
i++;
res += "(" + i + ")" + generateJsonPathArgumentFromJson(element, valueSearched);
}
}
}
}
return "";
}
Why the key gets equal to "" after the first if ? Or there's a better way to construct a json path for a specific value ?
Just get the solutions :
protected static String generateJsonPathArgumentFromJson(JsonNode jsonNode, String valueSearched) {
if (jsonNode.isValueNode() && !jsonNode.asText().equals(valueSearched)) {
return null;
} else {
if (jsonNode.isContainerNode()) {
if (jsonNode.isObject()) {
Iterator<Map.Entry<String, JsonNode>> elements = jsonNode.fields();
while (elements.hasNext()) {
Map.Entry<String, JsonNode> element = elements.next();
String res = generateJsonPathArgumentFromJson(element.getValue(), valueSearched);
if (res != null) {
return "." + element.getKey() + res;
}
}
} else {
int i = 0;
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
JsonNode element = elements.next();
String res = generateJsonPathArgumentFromJson(element, valueSearched);
if (res != null) {
return "(" + i + ")" + res;
}
i++;
}
}
}
}
return "";
}
I'm sure there's better way to do, but at least it works :)

write key and values from map to a file

With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.

How to create a loop through LinkedHashMap<String,ArrayList<String>>?

Please help me to create a loop through LinkedHashMap<String,ArrayList<String>> h:
if (h.get("key1").size() == 0)
System.out.println("There is no errors in key1.");
else
System.out.println("ERROR: there are unexpected errors in key1.");
if (h.get("key2").size() == 0)
System.out.println("There is no errors in key2.");
else
System.out.println("ERROR: there are unexpected errors in key2.");
if (h.get("key3").size() == 0)
System.out.println("There is no errors in key3.");
else
System.out.println("ERROR: there are unexpected errors in key3.");
if (h.get("key4").size() == 0)
System.out.println("There is no errors in key4.\n");
else
System.out.println("ERROR: there are unexpected errors in key4.\n");
Like this?
for (String key : h.keySet())
{
System.out.println("Key: " + key);
for(String str : h.get(key))
{
System.out.println("\t" +str);
}
}
EDIT:
for (String key : h.keySet())
{
if(h.get(key).size() == 0)
{
System.out.println("There is no errors in " + key) ;
}
else
{
System.out.println("ERROR: there are unexpected errors in " + key);
}
}
Try this code:
Map<String, ArrayList<String>> a = new LinkedHashMap<String, ArrayList<String>>();
Iterator<Entry<String,ArrayList<String>>> itr = a.entrySet().iterator();
while (itr.hasNext()) {
Entry<String,ArrayList<String>> entry = itr.next();
String key = entry.getKey();
System.out.println("key: " + key);
List<String> list = entry.getValue();
System.out.println("value: " + list);
}
Another way in Java8 is with the foreach() method
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});

Categories

Resources