pland
pland

Reputation: 858

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?

Upvotes: 0

Views: 1072

Answers (1)

Nettoyeur
Nettoyeur

Reputation: 91

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.

Upvotes: 1

Related Questions