setGraphic() not working correctly on recursively created TreeItems - java

I'm writing a folder synchronization app. Currently, I'm working on the part responsible for recursively going through the two user-specified directory structures, comparing the folders and files in them to the other structure, and displaying whether each file or folder is unchanged, changed, or new, by means of a colored dot. The problem is that the program in its current state, while evaluating the relation correctly, only displays the dot on one TreeItem per dot color instead on all of them. Pic for reference:
Whats causing this? I have a suspicion that it has to do with the way object assignment works in Java, so I'm reassigning one and the same object somehow to all the proper TreeItems, only stopping at the last one, but that's too broad to work with. See the offending function below.
private void compareAndFillInSourceTreeView(Path x, TreeItem root) throws IOException {
String xSourceName = x.getName(x.getNameCount() - 1).toString();
String xTargetName = (getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1))
.toString();
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("NEW CALL: " + x.toString() + " " + root);
System.out.println("EQUIVALENT: " + getEquivalentFileInTarget(x) + " EXISTS: " +
getEquivalentFileInTarget(x).toFile().exists());
System.out.println("IS NEW: " + xTargetName + ", " + (xTargetName == null));
System.out.println("UNCHANGED: " + x + " " + getEquivalentFileInTarget(x) + " NAMES: " + xSourceName + ", "
+ xTargetName);
System.out.println("CHANGED: " + ((x.getName(x.getNameCount() - 1)) ==
getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1)));
if (x.toFile().isFile()) {
System.out.println("THIS IS A FILE: " + x.toString());
//if new, i.e. doesn't exist in the target
if (!getEquivalentFileInTarget(x).toFile().exists()) {
System.out.println("EQUIVALENT DOESN'T EXIST FOR THIS FILE IN TARGET");
TreeItem newBranch = makeBranch(xSourceName, root);
newBranch.setGraphic(blueDotIcon);
}
//if unchanged
else if (sameContents(x, getEquivalentFileInTarget(x)) && (xSourceName.equals(xTargetName))) {
System.out.println("THIS FILE AND ITS EQUIVALENT ARE EQUAL");
TreeItem newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
newBranch.setGraphic(greenDotIcon);
}
//if same name, but different contents, i.e. changed
else if ((x.getName(x.getNameCount() - 1)).equals(
getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1))) {
TreeItem newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
newBranch.setGraphic(yellowDotIcon);
} else {
System.out.println("BAD, putInTreeView() Error, it should never reach this line");
System.out.println("Error log: " + x + ", " + getEquivalentFileInTarget(x));
}
} else if (x.toFile().isDirectory()){ //if it's a folder, checked explicitly because it's behaving weird
System.out.println("THIS IS A DIRECTORY: " + x.toString());
if (getEquivalentFileInTarget(x).toFile().exists()) {
System.out.println("EQUIVALENT EXISTS FOR THIS DIRECTORY IN TARGET.");
//make new branches and mark them as existing folders
TreeItem currentSourceTreeViewRoot = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
currentSourceTreeViewRoot.setExpanded(true);
currentSourceTreeViewRoot.setGraphic(greenDotIcon);
for (File i : x.toFile().listFiles()) {
System.out.println("Rec. called for: " + currentSourceTreeViewRoot);
compareAndFillInSourceTreeView(i.toPath(), currentSourceTreeViewRoot);
}
} else {
System.out.println("EQUIVALENT DOESN'T EXIST FOR THIS DIRECTORY IN TARGET.");
//if they don't exist, make the branches anyway and mark them as representing nonexistent folders
TreeItem currentSourceTreeViewRoot = makeBranch((x.getName(x.getNameCount() - 1)).toString(), root);
currentSourceTreeViewRoot.setExpanded(true);
for (File i : x.toFile().listFiles()) {
System.out.println("Rec. called for: " + currentSourceTreeViewRoot);
compareAndFillInSourceTreeView(i.toPath(), currentSourceTreeViewRoot);
}
}
}
}

Your assumption is correct. When assigning a graphic with setGraphic you are telling JavaFX where in the scene graph to locate this node. When you call setGraphic again with the same object as parameter you are effectively moving it to a different place in the scene graph.
Create a new dot/circle for every item and your problem should be solved.

Related

Bukkit plugin kick reason only using first word

So I'm making a kick/ban command for my server and the format is /kick name reason.
I got it all working but the reason can only be 1 word and anything over that excludes it, for example /kick BattleDash hello world would say BattleDash was kicked for hello.
Here's my code:
if (cmd.getName().equalsIgnoreCase("kick") && sender instanceof Player) {
Player player = (Player) sender;
int length = args.length;
if (length >= 2) {
boolean playerFound = false;
for (Player playerToKick : Bukkit.getServer().getOnlinePlayers()) {
if(playerToKick.getName().equalsIgnoreCase(args[0])) {
playerToKick.kickPlayer(ChatColor.RED + "Kicked by Administrator " + player.getName() + "\nReason: " + args[1]);
player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: Kicked player " + playerToKick.getName() + "succesfully!");
break;
}
}
if (playerFound == false) {
player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: " + args[0] + " was not found!");
}
} else player.sendMessage(ChatColor.RED + "[BATTLEDASHLOGS]: Incorrect arguments!" + ChatColor.RED + " /kick <PlayerName> <reason>");
return true;
}
(Also if you don't include a reason it gives internal error in chat and exception occured in console)
Your code is doing that due to the way it was programmed.
If we take a look at line that takes the argument:
playerToKick.kickPlayer(ChatColor.RED + "Kicked by Administrator " + player.getName() + "\nReason: " + args[1]);
We can see that you're only using args[1]. If we see a message as an array, the problem will be clear:
At position 0 (remember arrays start at 0): BattleDash
1: hello
2: world
When you take only args[1] to your message, only hello would be used! What we need to do instead, is use all the arguments. One way to do that is like this:
// First, transform your array into a list, so it's easier to understand
List<String> arguments = new ArrayList<>(args);
String playerName = arguments.get(0); // Get the player name
arguments.remove(0); // Remove the player name from our arguments list, we don't want it in the message
String message = String.join(" ", arguments); // Combine all the other arguments into a message

getInt Function Doesn't Return Anything

I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.
The answer has been solved by merging my two configuration files together.

NPE in a do/while loop due to EOF...catching the EOF earlier to avoid the NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have written this program to compare 2 files. They are 500mb to 2.8gb in size and are created every 6 hours. I have 2 files from 2 sources (NMD and XMP). They are broken up into lines of text that have fields separated by the pipe(|) character. Each line is a single record and may be up to 65,000 characters long. The data is about TV shows and movies, showing times and descriptive content. I have determined that any particular show or movie has a minimum of 3 pieces of data that will uniquely identify that show or movie. IE: CallSign, ProgramId and StartLong. The two sources for this data are systems called NMD and XMP hence that acronym added to various variables. So my goal is to compare a file created by NMD and one created by XMP and confirm that everything that NMD produces is also produced by XMP and that the data in each matched record is the same.
What I am trying to accomplish here is this: 1. Read the NMD file record by record for the 3 unique data fields. 2. Read the XMP file record by record and look for a match for the current record in the NMD file. 3.The NMD file should iterate one record at a time. Each NMD record should then be searched for in the entire XMD file, record by record for that same record. 4. Write a log entry in one of 2 files indicating success or failure and what that data was.
I have an NPE issue when I reach the end of the testdataXMP.txt file. I assume the same thing will happen for testdataNMD.txt. I'm trying to break out of the loop right after the readLine since the epgsRecordNMD or epgsRecordXMP will have just reached the end of the file if it at that point in the file. The original NPE was for trying to do a string split on null data at the end of the file. Now I'm getting an NPE here according to the debugger.
if (epgsRecordXMP.equals(null)) {
break;
}
Am I doing this wrong? If I'm really at the end of the file, the readLine ought to return null right?
I did it this way too, but to my limited experience they feel like they are effectively the same thing. It too threw an NPE.
if (epgsRecordXMP.equals(null)) break;
Here's the code...
public static void main(String[] args) throws java.io.IOException {
String epgsRecordNMD = null;
String epgsRecordXMP = null;
BufferedWriter logSuccessWriter = null;
BufferedWriter logFailureWriter = null;
BufferedReader readXMP = null;
BufferedReader readNMD = null;
int successCount = 0;
readNMD = new BufferedReader(new FileReader("d:testdataNMD.txt"));
readXMP = new BufferedReader(new FileReader("d:testdataXMP.txt"));
do {
epgsRecordNMD = readNMD.readLine();
if (epgsRecordNMD.equals(null)) {
break;
}
String[] epgsSplitNMD = epgsRecordNMD.split("\\|");
String epgsCallSignNMD = epgsSplitNMD[0];
String epgsProgramIdNMD = epgsSplitNMD[2];
String epgsStartLongNMD = epgsSplitNMD[9];
System.out.println("epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD );
do {
epgsRecordXMP = readXMP.readLine();
if (epgsRecordXMP.equals(null)) {
break;
}
String[] epgsSplitXMP = epgsRecordXMP.split("\\|");
String epgsCallSignXMP = epgsSplitXMP[0];
String epgsProgramIdXMP = epgsSplitXMP[2];
String epgsStartLongXMP = epgsSplitXMP[9];
System.out.println("epgsCallsignXMP: " + epgsCallSignXMP + " epgsProgramIdXMP: " + epgsProgramIdXMP + " epgsStartLongXMP: " + epgsStartLongXMP);
if (epgsCallSignXMP.equals(epgsCallSignNMD) && epgsProgramIdXMP.equals(epgsProgramIdNMD) && epgsStartLongXMP.equals(epgsStartLongNMD)) {
logSuccessWriter = new BufferedWriter (new FileWriter("d:success.log", true));
logSuccessWriter.write("NMD match found in XMP " + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logSuccessWriter.write("\n");
successCount++;
logSuccessWriter.write("Successful matches: " + successCount);
logSuccessWriter.write("\n");
logSuccessWriter.close();
System.out.println ("Match found");
System.out.println ("Successful matches: " + successCount);
}
} while (epgsRecordXMP != null);
readXMP.close();
if (successCount == 0) {
logFailureWriter = new BufferedWriter (new FileWriter("d:failure.log", true));
logFailureWriter.write("NMD match not found in XMP" + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logFailureWriter.write("\n");
logFailureWriter.close();
System.out.println ("Match NOT found");
}
} while (epgsRecordNMD != null);
readNMD.close();
}
}
You should not make this:
if (epgsRecordXMP.equals(null)) {
break;
}
If you want to know if epgsRecordXMPis null then the if should be like this:
if (epgsRecordXMP == null) {
break;
}
To sum up: your app throws NPE when try to call equals method in epgsRecordXMP.

Unable to understand the HLDA Output in MALLET

Below is a snippet of my code:
HierarchicalLDA hlda = new HierarchicalLDA();
hlda.initialize(instances, instances, 5, new Randoms());
hlda.estimate(1000);
hlda.printState(new PrintWriter(new File("Data.txt")));
I am unable to understand the meaning of both the console output and what is printed in the "Data.txt" file. I have already scoured the MALLET site but haven't found anything helpful. Any help or suggestion would be greatly appreciated.
Thanks in advance!
In hLDA each document samples a path through a tree of topics. Each token exists on one "level" of that path. The printState method gives you the ids of each tree node in the path for the document, followed by information about the word: the numeric ID for the word, the string for that id, and the level in the path.
node = documentLeaves[doc];
for (level = numLevels - 1; level >= 0; level--) {
path.append(node.nodeID + " ");
node = node.parent;
}
for (token = 0; token < seqLen; token++) {
type = fs.getIndexAtPosition(token);
level = docLevels[token];
// The "" just tells java we're not trying to add a string and an int
out.println(path + "" + type + " " + alphabet.lookupObject(type) + " " + level + " ");
}

How to save information from JTable to a File?

Here is my case:
So far my group and I, managed to read information from an external file and place it in a JTable. But we need an update button. So we guess we should take all the information from JTable after editting something inside it, and replace it with the current information in the same file. So we kind of think we have to overwrite the old file.
So far we got this: (for int i... is a part of the code but can't get it inside the grey area :P)
for(int i = 0; i < model.getRowCount(); i++) {
p += model.getValueAt(i, 0) + " "
+ model.getValueAt(i, 1) + " "
+ (Integer) model.getValueAt(i, 2) + " "
+ model.getValueAt(i, 3) + " "
+ (Integer)model.getValueAt(i, 4) + " "
+ model.getValueAt(i, 5) + " "
+ model.getValueAt(i, 6) + " "
+ model.getValueAt(i, 7) + " "
+ (Integer)model.getValueAt(i, 8) + "\n";
}
// Update File
SaveMember sm = new SaveMember();
sm.update(p);
Inside our SaveMember.java we got:
public void update(String x) throws Exception {
File f = new File("Members/Members.txt");
PrintStream output = new PrintStream(f);
output.print(x);
So by now when we go and change the data and press the button update, it doesn't do anything at all, and doesn't replace the old data with the new.. Thanks for reading! :)
I'm not sure. If you have double checked that your code is executed at all (maybe you forgot to attach the ActionListener to your button - we all do that from time to time...) try flush the output stream and close the stream afterwards.
First check if your code in the for loop is executed at all. Set a breakpoint after the for loop and inspect the string p. If you are not familiar with debugging, print the string to the console with System.out.println(p).
If your code is NOT executed: Check why the method your code is in is not called. Perhaps you forgot to attach an action listener to your update button or the action listener has an early return under some circumstances.
If your code is executed: What do you do with the exception that is thrown by the method update? Make sure to log it with your logger or print it to the console (again via System.out.println(exc)). If you get a FileNotFoundException the path to the file is not correct.

Categories