PlaceHolderAPI not working - java

As part of my plugin i have a clear chat command and at the end of the blank messages there is an option to display text. My problem is that the PlaceHolderAPI isn't working as it should.
Command Code:
if (label.equalsIgnoreCase("clearchat") || label.equalsIgnoreCase("mcc")) {
if (p.hasPermission("mystic.chat.admin.clearchat")) {
for (int i = 0; i < getConfig().getInt("clearChat.blankLines"); i++) {
Bukkit.broadcastMessage(" ");
}
for (String s : getConfig().getStringList("clearChat.endMessage")) {
s = PlaceholderAPI.setPlaceholders(p, s);
// This is here to check if the PlaceHolderAPI even knows there is place holders in it
p.sendMessage(String.valueOf(PlaceholderAPI.containsPlaceholders(s)));
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', s));
}
return true;
} else {
p.sendMessage(ChatColor.RED + "You are lacking the required permission node!");
return true;
}
}
Config File section:
clearChat:
blankLines: 256
endMessage:
- '&bChat was cleared by %player_name%'
When i run the command "/mcc" or "/clearchat" it always says false (for not recognizing any placeholders) and none of the place holders are replaced.
I do have the API correctly in the build path, and the command words perfectly, other than the place holders not converting.
I feel as if im making a stupid mistake, or that im doing this the complete wrong way...

You shouldn't need to use another api using p.getName() should suffice then using String.replace to replace the %name%

You are using the API wrong
You did this
s = PlaceholderAPI.setPlaceholders(p, s);
If the API would throw an error if there are no placeholders just surround that line with a try{} catch (Exception e) then send it to the player
p.sendMessage(s);
There is no need for the String.valueOf(s) as the API [is expected to] return a String, anyways setting the String s = PlaceholderAPI.setPlaceholders(p, s); will cast whatever object is there to a string.

Related

GStreamer open plain m3u from http

I'm trying to open plain m3u file without any meta data from http server:
1.ts
2.ts
3.ts
Simple way with playbin fails, telling it's a text file (yes, it is! tried both m3u and m3u8 extensions)
gst-launch-1.0.exe playbin uri=http://10.42.0.3:8765/list.m3u8
ERROR: from element /GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0: This appears to be a text file
decodebin cannot decode plain text files
decodebin in solo refuses to get file from http:
gst-launch-1.0 filesrc location=http://10.42.0.3:8765/list.m3u8 ! decodebin
ERROR: from element /GstPipeline:pipeline0/GstFileSrc:filesrc0: Could not open file "http://10.42.0.3:8765/list.m3u8" for reading.
and forced uridecodebin (that is supposed to accept playlists according to GStreamer documentation) fails like playbin:
gst-launch-1.0.exe uridecodebin uri=http://10.42.0.3:8765/list.m3u
ERROR: from element /GstPipeline:pipeline0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0: This appears to be a text file
decodebin cannot decode plain text files
If I add HLS-style meta data to same file:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:2.662589,
1.ts
#EXTINF:2.829011,
2.ts
#EXTINF:2.995411,
3.ts
it is correctly displayed with:
gst-launch-1.0.exe playbin uri=http://10.42.0.3:8765/list.m3u8
without any problems.
Is there any way to show video from m3u (or any other simle-list fileformat) without meta data?
And is there any way to jump to specified track during playback (I use Java bindings but they seem to have same naming as original lib)?
p.s. Same pure m3u is correctly played with vlc, ffplay and mpv
p.p.s. I understand that I can parse m3u and send links one-by-one on finished event, but I hope to gain some gapless playback without extra pain :-)
ADDED:
I wrote quick-and-durty parser with switcher:
playbin.getBus().connect(new Bus.EOS() {
#Override
public void endOfStream(GstObject source) {
EventQueue.invokeLater(() -> {
if (filesIndex < files.length) {
try {
playbin.stop();
playbin.setURI(new URI(request + files[filesIndex]));
playbin.play();
System.out.println("SWITCHED TO: " + request + files[filesIndex]);
} catch (Exception e){
e.printStackTrace();
}
}
filesIndex++;
});
}
});
playbin.getBus().connect(new Bus.ERROR() {
#Override
public void errorMessage(GstObject gstObject, int i, String s) {
EventQueue.invokeLater(() -> {
if (filesIndex < files.length) {
try {
playbin.stop();
// filesIndex++; Retry?
playbin.setURI(new URI(request + files[filesIndex]));
playbin.play();
System.out.println("SWITCHED ON ERROR TO: " + request + files[filesIndex]); // Error counter?
} catch (Exception e){
e.printStackTrace();
}
}
filesIndex++;
});
}
});
where files[] is m3u splited by lines, and this works very well (including jumping), but I still wonder what is a "built-in" way of playing lists and switching indexes

Cannot find a image file that exists in java

I have written a function which takes in a BufferedImage and compares it to a pre-existing image in my hard drive checking if they are same or not.
public boolean checkIfSimilarImages(BufferedImage imgA, File B) {
DataBuffer imgAdata = imgA.getData().getDataBuffer();
int sizeA = imgAdata.getSize();
BufferedImage imgB = null;
try {
imgB = ImageIO.read(B);
} catch (IOException ex) {
Logger.getLogger(SupportClass.class.getName()).log(Level.SEVERE, null, ex);
}
DataBuffer imgBdata = imgB.getData().getDataBuffer();
int sizeB = imgBdata.getSize();
if(sizeA == sizeB) {
for(int i = 0; i < sizeA; i++) {
if (imgAdata.getElem(i) != imgBdata.getElem(i)) {
return false;
}
}
}
return true;
}
This throws IOException "Cant read input file". Idk why this is happening. I am calling the function like this...
while(support.checkIfSimilarImages(currentDisplay, new File(pathToOriginalImage)) == false) {
System.out.println("Executing while-loop!");
bot.delay(3000);
currentDisplay = bot.createScreenCapture(captureArea);
}
where,
String pathToOriginalImage = "‪‪‪‪C:\\Users\\Chandrachur\\Desktop\\Home.jpg";
I can see that the path is valid. But as I am testing it for File.exists() or File.canRead() or File.absoluteFile().exists() inside the checkIfSimilarImages function and everything is returning false.
I have researched my question here and tried out these suggestions:
It is not only for this location, I have tried a variety of other locations but in vain. Also it is not a problem where I have hidden file extensions and the actual file might be Home.jpg.jpg .
The only thing that might be is that permissions might be different. I dont really know how to verify this, but there is no reason it should have some permission which is not readable by java. It is just another normal jpg file.
Can it be because I am passing the file object reference into a function so in this process somehow the reference is getting modified or something. I just dont know. I am running out of possibilities to test for...
The whole stack trace is as follows:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at battlesbot.SupportClass.checkIfSimilarImages(SupportClass.java:77)
at battlesbot.AutomatedActions.reachHomeScreen(AutomatedActions.java:72)
at battlesbot.BattlesBot.main(BattlesBot.java:22)
Exception in thread "main" java.lang.NullPointerException
at battlesbot.SupportClass.checkIfSimilarImages(SupportClass.java:81)
at battlesbot.AutomatedActions.reachHomeScreen(AutomatedActions.java:72)
at battlesbot.BattlesBot.main(BattlesBot.java:22)
C:\Users\Chandrachur\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 11 seconds)
I am on Windows 10, IDE is NetBeans.
UPDATE:
Huge thanks to #k5_ . He told me to paste this in path and it worked.
"C:/Users/Chandrachur/Desktop/Home.jpg";
It seems some invisible characters were in the path. But I still don't understand what that means.
Usually this kind of problem lies with access problem or typos in the filename.
In this case there were some invisible unicode characters x202A in the filename. The windows dialog box, the file path was copied from, uses them for direction of writing (left to right).
One way of displaying them would be this loop, it has 4 invisible characters at the start of the String. You would also see them in a debugger.
String x = "‪‪‪‪C:\\Users\\Chandrachur\\Desktop\\Home.jpg";
for(char c : x.toCharArray()) {
System.out.println( c + " " + (int) c);
}

createNewFile( ) causes warning message, how to eliminate?

By using createNewFile method and delete method of the File class I successfully generate files from my program. But there is an annoying warning message after the compilation process. My question is how can I remove that warning messages without using #SUPPRESSWARNIGN. Because when I do inspection for my code I see a probable bug warnings which are caused by these 2 methods. Yes, by using #SuppressWarning warnings and probable bug messages go away.
I do not know if it is related with the Java version but in any case I am using Java 8. I did the research for this problem, could not find anything on the internet. I saw people on the internet used these 2 methods in the same way I used. May be they ignored the warning messages. But I do not want to.
Here is my code :
private void createAFile() throws IOException {
String outputFileName = getFileName();
String outputPathName = getFilePath();
String fullOutputPath = outputPathName + "/" + outputFileName;
output = new File(fullOutputPath);
if(output.exists()){
output.delete(); //this returns a boolean variable.
}
output.createNewFile(); //this also return a boolean variable.
}
Warnings are :
Warning:(79, 20) Result of 'File.delete()' is ignored.
Warning:(84, 16) Result of 'File.createNewFile()' is ignored.
Thank you
If you want to avoid these messages you can provide logging for the case when these method return false.
Something like this
private static Logger LOG = Logger.getLogger("myClassName");
// some code
if (!output.delete()) {
LOG.info("Cannot delete file: " + output);
}
These look like warnings generated from a code check tool . What i would do is this :
boolean deleted,created; // both should be instantiatd to false by default
if(output.exists()){
deleted = output.delete(); //this returns a boolean variable.
}
if(deleted){
created = output.createNewFile();
}
if(!deleted||!created){
// log some type of warning here or even throw an exception
}

Highlight a text displayed in eclipse editor area programatically [duplicate]

A qustion about Eclipse PDE development: I write a small plugin for Eclipse and have the following
* an org.eclipse.ui.texteditor.ITextEditor
* a line number
How can I automatically jump to that line and mark it? It's a pity that the API seems only to support offsets (see: ITextEditor.selectAndReveal()) within the document but no line numbers.
The best would be - although this doesn't work:
ITextEditor editor = (ITextEditor)IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, true );
editor.goto(line);
editor.markLine(line);
It this possible in some way? I did not find a solution
on the class DetailsView I found the following method.
private static void goToLine(IEditorPart editorPart, int lineNumber) {
if (!(editorPart instanceof ITextEditor) || lineNumber <= 0) {
return;
}
ITextEditor editor = (ITextEditor) editorPart;
IDocument document = editor.getDocumentProvider().getDocument(
editor.getEditorInput());
if (document != null) {
IRegion lineInfo = null;
try {
// line count internaly starts with 0, and not with 1 like in
// GUI
lineInfo = document.getLineInformation(lineNumber - 1);
} catch (BadLocationException e) {
// ignored because line number may not really exist in document,
// we guess this...
}
if (lineInfo != null) {
editor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
}
}
}
Even though org.eclipse.ui.texteditor.ITextEditor deals wiith offset, it should be able to take your line number with the selectAndReveal() method.
See this thread and this thread.
Try something along the line of:
((ITextEditor)org.eclipse.jdt.ui.JavaUI.openInEditor(compilationUnit)).selectAndReveal(int, int);

create a text file in java

I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.

Categories

Resources