I'm trying to set the string of a Text object from a Thread but it's giving me this error:
Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.needsTextLayout(Unknown Source)
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source)
at javafx.scene.text.Text.access$200(Unknown Source)
at javafx.scene.text.Text$2.invalidated(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.scene.text.Text.setText(Unknown Source)
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70)
Handler Class:
#FXML
private Text timer;
#Override
public void initialize(URL url, ResourceBundle rb) {
init();
new Thread() {
public void run() {
while(true) {
Calendar cal = new GregorianCalendar();
int hour = cal.get(cal.HOUR);
int minute = cal.get(cal.MINUTE);
int second = cal.get(cal.SECOND);
int AM_PM = cal.get(cal.AM_PM);
String time = hour + "" + minute + "" + second;
timer.setText(time);
}
}
}.start();
}
I'm following a tutorial.
The guy in the tutorial is not using JavaFX.
I have tried using Platform.runLater(), it does work but it crashes my program.
I also tried creating a Timer on the Platform.runLater(new Runnable() { }) method but it gives me the same error as before.
Wrap timer.setText() in Platform.runLater(). Outside it, inside the while loop, add Thread.sleep(1000);
The reason behind Illegal State Exception is you are trying to update UI on some thread other than JavaFX Application thread.
The reason why your app was crashing when you added it was you were overloading the UI thread by adding a process to be executed on the UI thread infinitely. Making the thread sleep for 1000ms will help you overcome the issue.
If possible replace while(true) with a Timer or TimerTask.
For more options follow this link
Related
Just wondering what's causing this. I have no idea!
I am trying to make a queue plugin. I am using paper spigot. Please ignore all the holes in my plugins code as I'm simply testing it at the moment. If you have anything that you think I should change however I'd be glad to here it. Here is my error message spat out by the terminal.
[19:29:52 ERROR]: Could not load 'plugins\anarchyqueuet3.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.NoClassDefFoundError: redis/clients/jedis/Jedis
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:329) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.loadPlugins(CraftServer.java:318) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:222) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:616) ~[patched_1.12.2.jar:git-Paper-1618]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_241]
Caused by: java.lang.NoClassDefFoundError: redis/clients/jedis/Jedis
at com.Package.AnarchyQueue.<init>(AnarchyQueue.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_241]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:94) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:127) ~[patched_1.12.2.jar:git-Paper-1618]
... 6 more
Caused by: java.lang.ClassNotFoundException: redis.clients.jedis.Jedis
at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:156) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:104) ~[patched_1.12.2.jar:git-Paper-1618]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_241]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_241]
at com.Package.AnarchyQueue.<init>(AnarchyQueue.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_241]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:94) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:127) ~[patched_1.12.2.jar:git-Paper-1618]
... 6 more
And here's my code:
package com.Package;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.logging.Logger;
public class AnarchyQueue extends JavaPlugin {
//list of players in queue
private ArrayList<Player> players = new ArrayList<Player>();
//jedis object to communicate with other server
private Jedis jedis = new Jedis("localhost");
private int playerCount = 0;
static int maxPlayerCount = 10;
#Override
public void onEnable() {
onEnablePri();
}
#Override
public void onDisable() {
onDisablePri();
}
public void onPlayerJoin(PlayerJoinEvent event)
{
onPlayerJoinPri(event);
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
onCommandPri(sender,command,label,args);
return true;
}
//--------------------private methods--------------------
private void onEnablePri() {
log("Server test: "+jedis.ping(),1);
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
runPri();
}
}, 0L, 10L);;
}
private void runPri() {
try {
playerCount=Integer.parseInt(jedis.get("anarchy-player-count"));
} catch (Exception e) {
log("Player count get failed",1);
}
if(playerCount<maxPlayerCount)
{
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF("anarchy");
players.get(0).sendPluginMessage(this, "BungeeCord", out.toByteArray());
players.remove(0);
}
}
private void onDisablePri() {
//disable code
}
private void onPlayerJoinPri(PlayerJoinEvent event)
{
players.add(event.getPlayer());
}
private void onCommandPri(CommandSender sender, Command command, String label, String[] args) {
if(command.getName().equalsIgnoreCase("setmaxplayercount"))
{
jedis.set("anarchy-player-count",args[0]);
}
/*if (command.getName().equalsIgnoreCase("players")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be in game!");
}
else {
getCount();
}
} */
}
//private void getCount() {
//}
private void log(String str, int i)
{
if(i==0)
{
Logger.getLogger("Minecraft").info(str);
}
else
{
if(i!=1)
{
System.out.println("NUMBER NOT RECOGNISED: ");
}
System.out.println(str);
}
}
}
And finally here's my plugin.yml (in case this is wrong)
main: com.Package.AnarchyQueue
name: AnarchyQueue
version: '1.0'
description: The queue plugin for Ed_Silver's anarchy server.
load: postworld
author: Ed_Silver
prefix: AnarchyQueue
commands:
setmaxplayercount:
description: Sets max player count
usage: /setmaxplayercount [int]
I saw a post that spoke about needing to add a dependency using a pom.xml but I don't know if that applies to me.
Thanks in advance,
If you need anything just ask,
Edward
You are trying to import redis.clients.jedis.Jedis; but Minecraft cant find Jedis, you have to add Jedis to your maven or gradle project.
According to https://github.com/xetorthio/jedis :
https://github.com/xetorthio/jedis#how-do-i-use-it
Hopefully this helped, I am here to answer any more questions you have!
UPD: Problem was solved. Thanks.
https://github.com/CyberdyneCC/Thermos/issues/498#issuecomment-247083549
Please, help me with this problem.
I compile minecraft bukkit plugin for version 1.7.10 named Spark. Compilation is successful but i can`t load this.
Server core: Thermos 1.7.10.
Full stacktrace:
org.bukkit.plugin.InvalidPluginException: Cannot find main class `me.lucko.spark.bukkit.BukkitSparkPlugin'
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:191) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:145) ~[JavaPluginLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:334) ~[SimplePluginManager.class:1.7.10-1614.58]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:256) [SimplePluginManager.class:1.7.10-1614.58]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.loadPlugins(CraftServer.java:343) [CraftServer.class:1.7.10-1614.58]
at net.minecraft.world.storage.SaveHandler.initBukkitData(SaveHandler.java:462) [ayq.class:?]
at net.minecraft.world.storage.SaveHandler.func_75757_d(SaveHandler.java:138) [ayq.class:?]
at net.minecraft.world.World.<init>(World.java:374) [ahb.class:?]
at net.minecraft.world.WorldServer.<init>(WorldServer.java:162) [mt.class:?]
at net.minecraft.server.MinecraftServer.func_71247_a(MinecraftServer.java:375) [MinecraftServer.class:?]
at net.minecraft.server.dedicated.DedicatedServer.func_71197_b(DedicatedServer.java:337) [lt.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:643) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_211]
Caused by: java.lang.ClassNotFoundException: Failed to remap class me.lucko.spark.bukkit.BukkitSparkPlugin
at org.bukkit.plugin.java.PluginClassLoader.remappedFindClass(PluginClassLoader.java:534) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:455) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:211) ~[PluginClassLoader.class:1.7.10-1614.58]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_211]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_211]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:189) ~[PluginClassLoader.class:1.7.10-1614.58]
... 12 more
Caused by: java.lang.IllegalArgumentException: INVOKESPECIAL/STATIC on interfaces require ASM 5
at org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.a(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.b(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.accept(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.accept(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at net.md_5.specialsource.JarRemapper.remapClassFile(JarRemapper.java:246) ~[JarRemapper.class:?]
at net.md_5.specialsource.JarRemapper.remapClassFile(JarRemapper.java:232) ~[JarRemapper.class:?]
at org.bukkit.plugin.java.PluginClassLoader.remappedFindClass(PluginClassLoader.java:499) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:455) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:211) ~[PluginClassLoader.class:1.7.10-1614.58]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_211]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_211]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:189) ~[PluginClassLoader.class:1.7.10-1614.58]
... 12 more
Compilation was with using Eclipse IDE.
Class me.lucko.spark.bukkit.BukkitSparkPlugin source:
package me.lucko.spark.bukkit;
import me.lucko.spark.bukkit.placeholder.SparkMVdWPlaceholders;
import me.lucko.spark.bukkit.placeholder.SparkPlaceholderApi;
import me.lucko.spark.common.SparkPlatform;
import me.lucko.spark.common.SparkPlugin;
import me.lucko.spark.common.sampler.ThreadDumper;
import me.lucko.spark.common.sampler.TickCounter;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
public class BukkitSparkPlugin extends JavaPlugin implements SparkPlugin {
private CommandExecutor tpsCommand = null;
private SparkPlatform platform;
#Override
public void onEnable() {
this.platform = new SparkPlatform(this);
this.platform.enable();
// override Spigot's TPS command with our own.
if (getConfig().getBoolean("override-tps-command", true)) {
this.tpsCommand = (sender, command, label, args) -> {
if (!sender.hasPermission("spark") && !sender.hasPermission("spark.tps") && !sender.hasPermission("bukkit.command.tps")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return true;
}
BukkitCommandSender s = new BukkitCommandSender(sender) {
#Override
public boolean hasPermission(String permission) {
return true;
}
};
this.platform.executeCommand(s, new String[]{"tps"});
return true;
};
CommandMapUtil.registerCommand(this, this.tpsCommand, "tps");
}
if (getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) {
new SparkPlaceholderApi(this, this.platform);
getLogger().info("Registered PlaceholderAPI placeholders");
}
if (getServer().getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) {
new SparkMVdWPlaceholders(this, this.platform);
getLogger().info("Registered MVdWPlaceholderAPI placeholders");
}
}
#Override
public void onDisable() {
this.platform.disable();
if (this.tpsCommand != null) {
CommandMapUtil.unregisterCommand(this.tpsCommand);
}
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
this.platform.executeCommand(new BukkitCommandSender(sender), args);
return true;
}
#Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return this.platform.tabCompleteCommand(new BukkitCommandSender(sender), args);
}
#Override
public String getVersion() {
return getDescription().getVersion();
}
#Override
public Path getPluginDirectory() {
return getDataFolder().toPath();
}
#Override
public String getCommandName() {
return "spark";
}
#Override
public Stream<BukkitCommandSender> getSendersWithPermission(String permission) {
return Stream.concat(
getServer().getOnlinePlayers().stream().filter(player -> player.hasPermission(permission)),
Stream.of(getServer().getConsoleSender())
).map(BukkitCommandSender::new);
}
#Override
public void executeAsync(Runnable task) {
getServer().getScheduler().runTaskAsynchronously(BukkitSparkPlugin.this, task);
}
#Override
public ThreadDumper getDefaultThreadDumper() {
return new ThreadDumper.Specific(new long[]{Thread.currentThread().getId()});
}
#Override
public TickCounter createTickCounter() {
return new BukkitTickCounter(this);
}
}
What could be the problem and how to solve it?
Thanks.
Probably the problem is on your plugin.yml file. On this file you must specify the main class of your plugin so that then Bukkit/Spigot/Paper know where to point when the plugin is enabled. Could you please post the plugin.yml file?
I am using the HttpURLConnection class to connect to external web service from eclipse, then I am getting a error message "Connection Refused"
public class TestConnection {
static {
//for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
if (hostname.equals("localhost")) {
return true;
}
return false;
}
});
}
public static void main(String[] args)
{
HttpURLConnection urlConnection;
try {
//https get method with required parameters
// XMLHttpRequest s1 = new XMLHttpRequest ();
urlConnection = (HttpURLConnection) ((new URL("https://google.com").openConnection()));
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", "");
int HTTPS_RESPONSE_CODE = urlConnection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String HTTPS_RESULT=response.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at TestConnection.main(TestConnection.java:19)
But If i try to connect to the same site from a browser I am able to get a response from the service. Can you please let me know if there is a work around?
By default, the HttpURLConnection class will not allow localhost as the hostname. You need to define a custom hostname verifier which will allow localhost. You can place this code into a static block at the top of the class where you intend to use HttpURLConnection:
public final class YourClassName {
static {
//for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
if (hostname.equals("localhost")) {
return true;
}
return false;
}
});
}
// use HttpURLConnection here ...
}
Please find the working code,
PROXY_SERVER set to a valid proxy server and port for http I am using is 8080
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_SERVER, PROXY_PORT));
And when you establish the connection pass the proxy as an argument.
urlConnection = (HttpURLConnection) ((new URL(URI).openConnection(proxy)));
I am trying to parse quads with following piece of code using Nxparser in Eclipse.
String FileInput="c://ex.nq";
System.out.println("Adding "+FileInput);
// use the FileManager to find the input file
InputStream in = FileManager.get().open(FileInput);
if (in == null) {
throw new IllegalArgumentException("File: " + FileInput+ " not found");
}
//InputStream inS = RDFDataMgr.read(dsg, in, Lang.NQ);
//RDFDataMgr.loadDataset("c://examples.nq", Lang.NQ);
RDFXMLParser nxp=new RDFXMLParser(in, log4jConfPath); //"http://myuri"
while (nxp.hasNext()) {
Node[] ns = nxp.next();
for (Node n: ns) {
System.out.print(n.toString());
System.out.print(" ");
}
System.out.println(".");
}
Normally, parser indicates that it is able to parse N-Quads. Even though, it reads the triples, when I put a quad file (ex.nq) I have the following error:
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 7; Element or attribute do not match QName production: QName::=(NCName':')?NCName.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLEntityScanner.scanQName(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at org.semanticweb.yars2.rdfxml.ParserThread.run(Unknown Source)
The file I am using is "ex.nq" and inside I have the following quad:
<http://richard.cyganiak.de/foaf.rdf#RC> <http://xmlns.com/foaf/0.1/mbox> <mailto:richard#cyganiak.de> <http://example/2001-10-26_21-32-52> .
I am not sure if I have problem with file or something else. Any help would be appreciated.
I think you were close, based on the commented out bits.
String fileInput="c://ex.nq";
StreamRDF streamHandler = new StreamRDF() {
#Override void base(String base) {};
#Override void start() {};
#Override void finish() {};
#Override void prefix(String prefix, String iri) {};
#Override void quad(Quad quad) {
// Do something with your quad here
}
#Override void triple(Triple triple) {
// Do something with your triple here
}
};
TypedInputStream in = RDFDataMgr.open(fileInput);
if (in == null) {
throw new IllegalArgumentException("File " + fileInput + " not found");
}
RDFDataMgr.parse(streamHandler, in);
There are a number of predefined stream handlers that may do what you want, but this is the most general way to handle streams.
By trial and error, I have found that the standard java.bean XMLEncoder/Decoder will always use a static factory "newInstance" method when one is provided rather than the null constructor (but only if it is named "newInstance") . I can not find this is any documentation or in the DefaultPersistence delegate.
Am I looking in the wrong places?
Example:
public class TestClass {
private boolean changed = false;
public TestClass() {
}
public static TestClass newInstance() {
Thread.dumpStack();
return new TestClass();
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public static void doTestSave() throws FileNotFoundException, IOException {
BufferedOutputStream buffer = new BufferedOutputStream(new java.io.FileOutputStream("Test.xml"));
XMLEncoder e = new XMLEncoder(buffer);
Thread.currentThread().setContextClassLoader(TestClass.class.getClassLoader());
TestClass t = new TestClass();
t.setChanged(true);
e.writeObject(t);
e.close();
buffer.close();
}
public static Object loadTestFile() throws FileNotFoundException, IOException {
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream("Test.xml"));
XMLDecoder e = new XMLDecoder(buffer);
e.close();
buffer.close();
return e.readObject();
}
}
`
The stack dump from newInstance when loadTestFile is run is:
at java.lang.Thread.dumpStack(Thread.java:1273)
at kcl.waterloo.XMLCoder.TestClass.newInstance(TestClass.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:37)
at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:244)
at java.beans.Statement.invokeInternal(Statement.java:239)
at java.beans.Statement.access$000(Statement.java:39)
at java.beans.Statement$2.run(Statement.java:140)
at java.security.AccessController.doPrivileged(Native Method)
at java.beans.Statement.invoke(Statement.java:137)
at java.beans.Expression.getValue(Expression.java:98)
at com.sun.beans.MutableExpression.getValue(ObjectHandler.java:445)
at com.sun.beans.ObjectHandler.getValue(ObjectHandler.java:108)
at com.sun.beans.ObjectHandler.eval(ObjectHandler.java:130)
at com.sun.beans.ObjectHandler.startElement(ObjectHandler.java:238)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:142)
at java.beans.XMLDecoder.getHandler(XMLDecoder.java:238)
at java.beans.XMLDecoder.readObject(XMLDecoder.java:201)
at kcl.waterloo.XMLCoder.TestClass.loadTestFile(TestClass.java:74)
I think I have worked this out.
Relates to Oracle Bug ID 4920456 where making newInstance() static was suggested as a solution - but this leads to the static method being called instead of the null constructor.
The java.beans.Statement invoke method in-line docs explains that "For class methods, [it] simluate[s] the effect of a meta class by taking the union of the static methods of the actual class, with the instance methods of "Class.class" and the overloaded "newInstance" methods defined by the constructors."
A side-effect seems to be that when a no argument static method named newInstance is present in a class, this method is called when the java.lang.Class.newInstance() method should be called to invoke the null constructor.
The solution is not to use "newInstance" as a method name in a class using XMLEncoder.