File.exists() security exception - java

I'm trying to write an applet for a website that needs access to a system on the LAN, so using a network path (\\THEBOX\DIR\SUBDIR). I'm checking if the directory exists before using it:
try {
File theDir = new File(filepath);
if (!theDir.exists()) theDir.mkdir();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getCause()+"\n\n"+e.getLocalizedMessage());
}
This catches the exception java.io.FilePermission. The .jar file is signed with a self certificate. Here's the catch- if I run this inside of void init() it works fine, but when I name it void myFunction() the error shows. I need to name it something other than init so it doesn't run on page load and can be called from javascript.
Edit:
As a workaround I'm going to switch back to using init(), but not load the applet until the button is clicked. While I'd prefer the more proper way we can't always be that fortunate.

Related

CodenameOne - filesystem access problems on iOS for Library folder

My CodenameOne app is being tested on the iOS simulator (iPad 8th iOS 14).
It writes some files in the private folder by means of this method:
public void writeFile() throws IOException {
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(Utils.getRootPath()+DATA_FILE);)
{
os.write(JSONText.getBytes("UTF-8"));
os.flush();
os.close();
} catch(IOException err) {
System.out.println("exception trying to write");
}
}
It works on the CN simulator (writes inside the .cn1/ folder)
but on iOS the exception is catched. The Library folder is of paramount importance on iOS.
Below is the method to get the root path
public static String getRootPath()
{
String documentsRoot=FileSystemStorage.getInstance().getRoots()[0];
String os=Display.getInstance().getPlatformName();
if (os.toLowerCase().contains("ios")) {
int pos=documentsRoot.lastIndexOf("Documents");
if (pos==-1) return documentsRoot+"/";
String libraryRoot=documentsRoot.substring(0,pos)+"Library";
String result=libraryRoot+"/";
return result;
}
The CN version of my app has to write those private files in the same location as the swift version, that is Library.
There is string manipulation, and no extra '/' are added, the file path seems legit.
So the string
file:///Users/mac/Library/Developer/CoreSimulator/Devices/alphanumeric-string/data/Containers/Data/Application/another-alphanumeric-string/Documents/
is transformed and
the getRootPath() method returns
file:///Users/mac/Library/Developer/CoreSimulator/Devices/alphanumeric-string/data/Containers/Data/Application/another-alphanumeric-string/Library/
But there is exception.
Furthermore, at some point after the writing attempt, I see in the console output something I think is relevant:
Failed to create directory /Users/mac/Library/Developer/CoreSimulator/Devices/alphanumeric-string/data/Containers/Data/Application/another-alphanumeric-string/Documents/cn1storage/
What is this? Is it related to my problem?
Is CN filesystem access broken or flawed?
I know io access permissions are automatically created by the CN compiler, but are they working?
So how to fix my issue about the Library folder?
The cn1storage printout just means the storage directory already exists.
The way to get the library path is this: Getting an iOS application's "~/Library" path reliably
You need to use that approach. I think your assumption that Document and Library reside under the exact same hierarchy is just incorrect.

File gets a full path of local source file as its name when uploaded using Java FTPClient

So i have a basic GUI application, where there is an option to upload image files to an ftp server. Everything works fine except one thing: the files are getting renamed during the upload. The new name of the file will be the full path of the directory, which contained the file.
So in my case, i have an image on the desktop: C:\Users\Bob\Desktop\image.png. When I select the file in the JfileChooser, the name is still just image.png. But when I click upload to FTP server, the file will be renamed to C:\Users\Bob\Desktop\image.png. So if I want to download that file, I have to use this path: /home/user/users/xy/images/C:\Users\Bob\Desktop\image.png in order to download it. Idk what causing this problem. I use FTPClient.putFileToPath(file,path) to upload the files, and it works fine, the files will be uploaded. I tried to copy a file from my machine to the ftp server with total commander, and this problem never occurred. I provided some code snippet, which does the uploading job.
uploadmenu.getUploadBtn().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!uploadMenuValidate()){
for(File f : img_container){
try {
//This still gives me the normal file name
System.out.println(f.getName());
ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
popup.setVisible(false);
}
}
});
I have all the files in the img_container array that I selected in the JFileChooser.
The File.toString() returns:
Returns the pathname string of this abstract pathname
You want to use File.getName():
ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f.getName());

HTML file not opening in executable jar

I have a program I have written in Eclipse and it runs fine -- the HTML file opens when I run the program through Eclipse. But when I create a jar file of the program, everything else runs fine except this HTML file won't open in the browser (or anywhere):
operation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File htmlFile = new File("help/operation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (MalformedURLException MURLe) {
MURLe.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
The rest of the program runs fine, and my images and sounds work fine and are opened, but this HTML file will not open in the menu or with the Ctrl+key shortcut. Your help is appreciated. Thanks.
When you have a file inside your jar, you cannot access it like you are doing now.
You need to read it as a stream, that's the only way.
Suppose your project is foo. Then help/operation.html will refer to
..\abc\help\operation.html
But the deployed jar file will not contain it.
You have include this operation.html file in your source code (where you write code).
Then eclipse (or any IDE) will add it into your jar file when you deploy it.
And now you can use your file as follows.
Suppose your file is present in as shown in figure.
Now you can refer your html file from any class. In this example referring it from
Accesser class.
File resFile = new File(Accesser.class.getResource("operation.html").toURI());
If you want to open your file in browser you will have to copy this file into the
user's System.
File htmlFile = new File("operation.html");
if(!htmlFile.exists) {
Files.copy(resFile.toPath(), htmlFile.toPath());
}
Desktop.getDesktop().browse(htmlFile.toURI());
Files is present in java.nio.file package

How to find and load a file within a Java Applet using getCodeBase()?

First time posting here, will try to be succinct. This is a classic 'can't access file within an Applet' problem, but I'm having a particular difficulty with it.
I'm trying to rewrite this file:
A JavaSound test for libpd
into a template applet to load libpd (https://github.com/libpd/libpd) patches made in PureData (puredata.info)...this already works in a normal Main function in a non-applet Java program (see above), where the main function finds the patch using:
PdBase.openAudio(0, outChans, (int) sampleRate);
int patch = PdBase.openPatch("samples/com/noisepages/nettoyeur/libpd/sample/test.pd");
PdBase.computeAudio(true);
The reason it tries to load the path and file into a int variable is that the core function itself does this with:
public synchronized static int openPatch(File file) throws IOException {
if (!file.exists()) {
throw new FileNotFoundException(file.getPath());
}
String name = file.getName();
File dir = file.getParentFile();
long ptr = openFile(name, (dir != null) ? dir.getAbsolutePath() : ".");
if (ptr == 0) {
throw new IOException("unable to open patch " + file.getPath());
}
int handle = getDollarZero(ptr);
patches.put(handle, ptr);
return handle;
}
public synchronized static int openPatch(String path) throws IOException {
return openPatch(new File(path));
}
This is because PD tries to identify each patch by giving an int 'handle' (dollarZero, for legacy reasons), so that int handle gets passed around to open and close the patch file.
So now. I'm trying to load the same file in an Applet, so since I believe it runs 'in the client' and won't know what path I'm talking about, I read up on java.net.URL and tried to build variations of:
patchURL = new URL("test.pd");
PdBase.openPatch(patchURL.getPath().toString());
and
URL url = this.getClass().getResource("test.pd");
inspired by previous questionsin the init() and start() functions of the applet, turning the original main into a local static method sound().
All I get is null pointers. I would've thought all I needed was a simple getDocumentBase(), but can't seem to make it work. Anyone?
libpd is just a thin wrapper on top of Pure Data, and Pure Data doesn't know about URLs or input streams in Java. The openPatch method merely sends the patch name and directory to Pd, and then Pd will try to open the corresponding file. So, applets are out, unless you're willing to tinker with security policies.
About finding files, the simple sample program is part of the libpd Eclipse project. It's meant to be run in Eclipse, and the hard-coded path to the patch is relative to the project root in Eclipse. If you want your code to run in a different setting, you have to adjust your paths accordingly.

JApplet writing to text file, destroy() / stop()

I am attempting to write a JApplet that uses information in a text file to load and save data from. I have successfully got the applet to load the information, but the saving appears to be having issues. I have included the code to save below. the file name I am using is the same as I use to write to. The file must be included in the JAR when I run because the applet initializes properly. Is there any reason why the writing sin't working properly? i have resorted to calling this method from both the stop() and destroy() methods.
As a note, the load and saving both work perfectly when run from eclipse, but when in a JAR only the loading works, but nothing saves so I can't change the load data.
Ideally, I want this saveLocations() method to be called whenever the page is closed or refreshed.
NOTE: mOUtputStream is indeed a PrintWriter (it used to be an OutputStream, I guess I should change the name)
Thanks so much in advance for the help.
private void saveLocations() throws IOException {
//JOptionPane.showMessageDialog(null, "Alert", "Saving", JOptionPane.INFORMATION_MESSAGE);
// System.out.println("saving!");
try {
mOutputStream = new PrintWriter(new File(getClass().getResource("/listings/saveData.txt").toURI()));
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(locations.size());
for (Location l : locations) {
System.out.println("r: " + l.getRawListing());
mOutputStream.print(l.getRawListing()+ "\n");
}
if (mOutputStream != null)
mOutputStream.close();
}
You can't write to a file inside a JAR file -- period. Don't even try. If you need to write to a file, then that file has to be outside the JAR. For an applet, that would require it to be signed, and to ask the user for specific permission to do so.
In the applet case, I'm not sure what copy of the JAR file you're hoping will be written to: the copy in the browser cache, or the copy on the server? Either way, it's not going to happen.

Categories

Resources