Java file input and output - java

I have the below method which is meant to append information to a file but I get the error below. In the method I use parts of robocode API which inherits from java.io.InputStream
All the permissions on the files and folders seem fine and the file does exist
static public void logInfo(String info)
{
RobocodeFileWriter in;
try {
in = new RobocodeFileWriter("log.txt");
in.append(info);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SYSTEM: An error occurred during initialization of itc.solomon
SYSTEM: java.security.AccessControlException: Preventing itc.solomon from access: (java.io.FilePermission log.txt read): You may only read files in your own root package directory.
java.security.AccessControlException: Preventing itc.solomon from access: (java.io.FilePermission log.txt read): You may only read files in your own root package directory.
at robocode.security.RobocodeSecurityManager.handleSecurityProblem(Unknown Source)
at robocode.security.RobocodeSecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkRead(SecurityManager.java:888)
at java.io.File.exists(File.java:748)
at robocode.RobocodeFileOutputStream.(Unknown Source)
at robocode.RobocodeFileOutputStream.(Unknown Source)
at robocode.RobocodeFileWriter.(Unknown Source)
at itc.CFile.logInfo(CFile.java:16)
at itc.solomon.(solomon.java:43)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at robocode.peer.proxies.HostingRobotProxy.loadRobotRound(Unknown Source)
at robocode.peer.proxies.HostingRobotProxy.run(Unknown Source)
at java.lang.Thread.run(Thread.java:636)

See this sample:
http://code.google.com/p/robocode/source/browse/robocode/trunk/robocode.samples/src/main/java/sample/SittingDuck.java
I think getDataFile("log.txt") will give you proper location.

I've searched a bit about this problem. It seems that there's a bug in the robocode package, awkwardly solved by:
while (!dataIsLoaded) {
try {
tryToReadData;
dataIsLoaded = true;
} catch (AnyException e) {}
}
It's a quite awful way to solve the problems, for many reasons (ignoring exceptions, busy-waiting, etc.) A more sane way would be downgrading the robocode package to a previous, more stable version.
See search results here.

Related

NoClassDefFoundError: caused by ClassNotFoundException

My program may use a library when it is present at runtime, but it is not required to have this library to run the program. However, when I run my program (without the library being present), it complains that it is not present for a very specific import:
java.lang.NoClassDefFoundError: nl/lolmewn/stats/api/storage/StorageException
at me.staartvin.plugins.pluginlibrary.Library.<clinit>(Library.java:34) ~[?:?]
at me.staartvin.plugins.pluginlibrary.PluginLibrary.loadLibraries(PluginLibrary.java:105) ~[?:?]
at me.staartvin.plugins.pluginlibrary.PluginLibrary.onEnable(PluginLibrary.java:68) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264) ~[spigot-latest.jar:git-Spigot-eadd615-4509a14]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:337) [spigot-latest.jar:git-Spigot-eadd615-4
9a14]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:403) [spigot-latest.jar:git-Spigot-eadd615-
09a14]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugin(CraftServer.java:381) [spigot-latest.jar:git-Spigot-eadd615-45
a14]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.enablePlugins(CraftServer.java:330) [spigot-latest.jar:git-Spigot-eadd615-4
9a14]
at net.minecraft.server.v1_12_R1.MinecraftServer.t(MinecraftServer.java:422) [spigot-latest.jar:git-Spigot-eadd615-4509a14
at net.minecraft.server.v1_12_R1.MinecraftServer.l(MinecraftServer.java:383) [spigot-latest.jar:git-Spigot-eadd615-4509a14
at net.minecraft.server.v1_12_R1.MinecraftServer.a(MinecraftServer.java:338) [spigot-latest.jar:git-Spigot-eadd615-4509a14
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:272) [spigot-latest.jar:git-Spigot-eadd615-4509
4]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:545) [spigot-latest.jar:git-Spigot-eadd615-4509a
]
at java.lang.Thread.run(Uenter code herenknown Source) [?:1.8.0_161]
Caused by: java.lang.ClassNotFoundException: nl.lolmewn.stats.api.storage.StorageException
at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_161]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:152) ~[spigot-latest.jar:git-Spigot-eadd615-4
9a14]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:100) ~[spigot-latest.jar:git-Spigot-eadd615-4
9a14]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_161]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_161]
... 14 more
The code that uses this StorageException class is this:
try {
user = stats.getUserManager().loadUser(player.getUniqueId(), stats.getStatManager());
} catch (StorageException e) {
e.printStackTrace();
}
Note that I have many imports using this library. The odd thing is that when I leave out the StorageException import (e.g. change it to a general Exception), it does not give any error anymore, even though there are other imports (from the exact same library) present!
Obviously, I want to use the StorageException class for catching errors, but I can't seem to do this.
How can I solve this issue?

Why is Java returning an error rather than an IOException when try and get a file lock

This code running with Java 1.8.0_72 25.72-b15 64bit on Windows 8.1
protected FileLock getFileLockForWriting(FileChannel fileChannel, String filePath) throws IOException
{
logger.finest("locking fileChannel for " + filePath);
FileLock fileLock;
try
{
fileLock = fileChannel.tryLock();
}
//Assumes locking is not supported on this platform so just returns null
catch (IOException exception)
{
return null;
}
//Couldnt getFields lock because file is already locked by another application
if (fileLock == null)
{
throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_FILE_LOCKED.getMsg(filePath));
}
return fileLock;
}
is reporting this error for a particular user
java.lang.Error: java.io.IOException: The specified server cannot perform the requested operation
at sun.nio.ch.FileKey.create(Unknown Source)
at sun.nio.ch.SharedFileLockTable.<init>(Unknown Source)
at sun.nio.ch.FileLockTable.newSharedFileLockTable(Unknown Source)
at sun.nio.ch.FileChannelImpl.fileLockTable(Unknown Source)
at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
at java.nio.channels.FileChannel.tryLock(Unknown Source)
at org.jaudiotagger.tag.id3.AbstractID3v2Tag.getFileLockForWriting(AbstractID3v2Tag.java:1080)
at org.jaudiotagger.tag.id3.AbstractID3v2Tag.writeBufferToFile(AbstractID3v2Tag.java:1462)
at org.jaudiotagger.tag.id3.ID3v23Tag.write(ID3v23Tag.java:751)
at org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:1011)
at org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:920)
at org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:932)
at com.jthink.songkong.analyse.analyser.SongSaver.realSave(SongSaver.java:798)
at com.jthink.songkong.analyse.analyser.SongSaver.saveSongToFile(SongSaver.java:623)
at com.jthink.songkong.analyse.analyser.SongSaver.saveChanges(SongSaver.java:185)
at com.jthink.songkong.analyse.analyser.SongSaver.call(SongSaver.java:160)
at com.jthink.songkong.analyse.analyser.SongSaver.call(SongSaver.java:54)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: The specified server cannot perform the requested operation
at sun.nio.ch.FileKey.init(Native Method)
... 21 more
It seems it is returning an Error because file locking is not supported, but it should be returning an IOException, (my code expects an IOException), why should this be
Update
I case relevent it’s a Western Digital MyBook Live 3TBNAS, Firmware version is 02.43.10-048 which running Debian 5.0.4
All code above FileKey.create can throw a IOException so your assumption that this behaviour is not ok is correct.
Indeed this was already filed as bug. In Java 9 the Error will be gone and a IOException will be thrown instead.
Therefore for now you should be prepared to catch the error and evaluate the inner IOException.

Running jTSS in Eclipse

I am trying to run the Trusted Computing API JSR321 in Eclipse by following the tutorial provide at Getting Started with JSR321 in Windows 7.
After successfully enabling my TPM (manufacturer: STM & version: 1.2).
I tried to run the code given in the tutorial,
import javax.trustedcomputing.tpm.TPMContext;
public class HellowWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
TPMContext context = TPMContext.getInstance();
context.connect(null);
//Do somthing cool here
context.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I also added the external jar files as Classpaths in eclipse for the IAIK jTSS (jTSS 0.7.1a), they also mentioned that
It is necessary to set the jsr321.tpmcontextimpl property to the classname of your TPMContext implementation.
For example java -cp YourClasspath -Djsr321.tpmcontextimpl=iaik.tc.jsr321.tpm.TPMContextImpl yourjavaapplication.class
So I added the above code by right clicking on the project and going to the Run As -> Run Configuration and in the Arguments tab in the section provided for VM arguments I inserted the following command
-cp C:\Users\workspace\HelloWorld\bin -Djsr321.tpmcontextimpl=iaik.tc.jsr321.tpm.TPMContextImpl HellowWorld
But I am getting the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/trustedcomputing/tpm/TPMContext
at HellowWorld.main(HellowWorld.java:10)
Caused by: java.lang.ClassNotFoundException: javax.trustedcomputing.tpm.TPMContext
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
I have already added all the mentioned dependencies in Java Build Paths inside Project Properties.
Kindly suggest a solution.
Thanks

Dynamic loading java classes in terminal

The application is modular plug-in architecture. That is, while the work is done dynamically load classes. For this purpose a custom class loader extends ClassLoader.
The essence of the problem is that in Eclipse application runs, while in terminal (ubuntu) using the following line of code (where the Catalog "m /" indicates the location of the modules * .class):
java -jar ModularApp.jar m/
I get the following message:
10:07:24,085 DEBUG main CModuleLoader:findClass:39 - Run of the System Classloader.
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NoClassDefFoundError: ru/intetech/module/CModule
at java.lang.ClassLoader.defineClass1(Native Method) at
java.lang.ClassLoader.defineClass(ClassLoader.java:800) at
java.lang.ClassLoader.defineClass(ClassLoader.java:643) at
ru.intetech.moduleloader.CModuleLoader.findClass(CModuleLoader.java:35)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at
java.lang.ClassLoader.loadClass(ClassLoader.java:358) at
ru.intetech.modularApp.Main.main(Main.java:42) ... 5 more Caused by:
java.lang.ClassNotFoundException: ru.intetech.module.CModule at
java.lang.ClassLoader.findClass(ClassLoader.java:531) at
ru.intetech.moduleloader.CModuleLoader.findClass(CModuleLoader.java:40)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at
java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 12 more
Here's a snippet of code, the user class loader (extending ClassLoader), where there is an error:
protected Class<?> findClass(String className) throws ClassNotFoundException
{
try
{
byte b[]=getClassAsBytes(m_pathToBin+className+".class");
return (defineClass(className, b, 0, b.length));
}
catch(FileNotFoundException ex)
{
m_log.debug("Run of the System Classloader.");
return (super.findClass(className));
}
catch(IOException ex)
{
m_log.debug("Run of the Bootstrap.");
return (super.findClass(className));
}
}
What could be the problem?
P.S. Loader implemented on the basis of this article:
http://sysmagazine.com/posts/104229/
Look: The stack trace shows the message "Run of the System Classloader", which proves that the first catch was executed. This was caused by a FileNotFoundException, which clearly occurred in the getClassAsBytes method: This is what you must investigate: Find out what file you are trying to read (put a trace showing the the absolute path), and why that file does not exist.
(Eventually, that catch block tries to load the required class by the system classloader, which has no acces to that class, and so, it throws the ClassNotFoundException).

RMI tutorial errors with ComputeEngine

So I've spent quite awhile trying to find an answer from other people having trouble with the RMI tutorial, but I'm completely stumped on this. I'm doing this tutorial through eclipse.
My ComputeEngine Class. This is just copied from the tutorial, so I don't think there's anything wrong with it.
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import compute.Compute;
import compute.Task;
public class ComputeEngine implements Compute {
public ComputeEngine() {
super();
}
public <T> T executeTask(Task<T> t) {
return t.execute();
}
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
String name = "Compute";
Compute engine = new ComputeEngine();
Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, stub);
System.out.println("ComputeEngine bound");
} catch (Exception e) {
System.err.println("ComputeEngine exception:");
e.printStackTrace();
}
}
}
I start the rmiregistry in the command line with
set classpath=
start rmiregistry
My VM arguments in eclipse are:
-Djava.rmi.server.codebase=file:/C:/Users/Kevin/workspace/RMI/bin/
-Djava.rmi.server.hostname=Compute
-Djava.security.policy=server.policy
I have the compute.jar file and the the server.policy files in the bin folder. I granted all permissions for the policy file.
grant{
permission java.security.AllPermission;
};
After all that, I run ComputeEngine and get the following errors:
ComputeEngine exception:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown Source)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.newCall(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at engine.ComputeEngine.main(ComputeEngine.java:31)
It seems like it has some kind of problem with rebind, but I don't understand what. I also don't understand the AccessControlException, when I have the policy file. I've checked to make sure the rmiregistry is still running, and I don't close the empty window that comes up after starting it.
So yeah, I'm lost.
Clearly your security policy file isn't being found. It would need to be in the current working directory when you execute the program. Run your program with -Djava.security.debug=access,failure to see exactly what's going on.
The exception clearly says that your code base does not have permission to creat sockets/ for network communication. The reason could be with your security policy specification alone. Do not specify the policy file explicitly and allow the JVM to use the default security policy. The default policy specifies the right permissions so you should be fine.

Categories

Resources