Jump to content

OSBot File API


liverare

Recommended Posts

So you want to files, huh? M'kay.

Example code:

import java.io.IOException;

import org.osbot.rs07.script.Script;
import org.osbot.rs07.script.ScriptManifest;

@ScriptManifest(author = "", info = "", logo = "", name = "Chicken Killer", version = 0)
public class ChickenKiller extends Script {

	OSBotFileAPI osbotFile;
	String profile;
	
	@Override
	public void onStart() throws InterruptedException {
		initialiseCustomAPIs();
		
		iWantToOpenAFile();
		iWantToSaveStuffToAFile("Hello world!");
	}

	private void initialiseCustomAPIs() {
		osbotFile = new OSBotFileAPI();
		osbotFile.exchangeContext(bot);
		osbotFile.initializeModule();
	}

	private void iWantToOpenAFile() {
		try {
			profile = osbotFile.open();
			logger.debug(profile);
		} catch (RuntimeException | IOException e) {
			logger.error(e);
		}
	}
	
	private void iWantToSaveStuffToAFile(String stuff) {
		try {
			osbotFile.save("Hello world!");
		} catch (RuntimeException | IOException e) {
			logger.error(e);
		}
	}

	@Override
	public int onLoop() throws InterruptedException {
		return 250;
	}
}

 

Testing:

Folder is automatically created if it doesn't exist:

I2fEbEJ.png

4cxRSB2.png

 

I manually created a text file for testing and added it into the script data folder:

yqfHDMC.png

mTh2u75.png

 

I re-ran the script so that I could now select something:

75Zfu1W.png

fxK92DR.png

 

And then the script did a little save testing with the same file:

PlOp1CW.png

ogOKB9G.png

 

Functions:

public boolean folderExists()
protected synchronized String readFromFile(File file) throws FileNotFoundException, IOException
public synchronized String readFromFile(String filename) throws FileNotFoundException, IOException
protected synchronized void writeToFile(File file, String fileContent) throws IOException
public synchronized void writeToFile(String filename, String fileContent) throws IOException
public synchronized String open(FileFilter fileFilter) throws RuntimeException, FileNotFoundException, IOException
public synchronized String open() throws RuntimeException, FileNotFoundException, IOException
public synchronized void save(FileFilter fileFilter, String fileContent) throws IOException
public synchronized void save(String fileContent) throws IOException
public synchronized boolean deleteFile(String filename)

 

Source:

import java.awt.Component;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.stream.Collectors;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.osbot.rs07.script.API;
import org.osbot.rs07.script.Script;

public class OSBotFileAPI extends API {

	Script script;
	String scriptName;
	String scriptFolderDir;
	File scriptFolder;
	Component botCanvas;

	@Override
	public void initializeModule() {
		initialiseVariables();
		createScriptFolder();
	}

	private void initialiseVariables() {
		script = bot.getScriptExecutor().getCurrent();
		scriptName = script.getName();
		scriptFolderDir = (scriptName + File.separator); // (e.g. "ChickenKiller/")
		scriptFolder = new File(script.getDirectoryData(), scriptFolderDir);
		botCanvas = bot.getCanvas();
	}

	private void createScriptFolder() {
		if (!scriptFolder.exists()) {
			if (scriptFolder.mkdirs()) {
				logger.info("Successfully created new script folder for " + scriptName + ":");
				logger.info(scriptFolder.getAbsolutePath());
			} else {
				logger.error("Failed to create a new script folder for " + scriptName + ":");
				logger.error(scriptFolder.getAbsolutePath());
			}
		}
	}

	public boolean folderExists() {
		return scriptFolder.exists();
	}

	protected synchronized String readFromFile(File file)
			throws FileNotFoundException, IOException {
		
		String fileContents = null;
		
		if (file == null || !file.exists() || file.isDirectory()) {
			throw new IllegalArgumentException("Invalid file");
		}
		
		try (
				FileReader in = new FileReader(file);
				BufferedReader br = new BufferedReader(in)
				) {
			
			fileContents = br.lines().collect(Collectors.joining("\n"));
		}
		
		return fileContents;
	}

	public synchronized String readFromFile(String filename)
			throws FileNotFoundException, IOException {
		
		File file;
		
		if (filename == null || filename.isEmpty()) {
			throw new IllegalArgumentException("Filename must be valid");
		}
		
		file = new File(scriptFolder, filename);
		
		return readFromFile(file);
	}
	
	protected synchronized void writeToFile(File file, String fileContent)
			throws IOException {
		
		if (file == null) {
			throw new IllegalArgumentException("Invalid file");
		} else if (!file.exists() && !file.createNewFile()) {
			throw new IllegalArgumentException("Failed to create file: " + file);
		}
		
		try (
				FileWriter out = new FileWriter(file);
				BufferedWriter bw = new BufferedWriter(out)
			) {
			
			bw.write(fileContent != null ? fileContent : "");
		}
	}
	
	public synchronized void writeToFile(String filename, String fileContent)
			throws IOException {
		
		File file;
		
		if (filename == null || filename.isEmpty()) {
			throw new IllegalArgumentException("Filename must be valid");
		}
		
		file = new File(scriptFolder, filename);
		
		writeToFile(file, fileContent);
	}

	public synchronized String open(FileFilter fileFilter)
		throws RuntimeException, FileNotFoundException, IOException {
		
		String fileContents = null;
		JFileChooser fileChooser;
		int selectionState;
		File selectedFile;
		
		if (scriptName == null) {
			throw new RuntimeException("Initialise the API module first!");
		}
		
		fileChooser = new JFileChooser(scriptFolder);
		fileChooser.setMultiSelectionEnabled(false);
		if (fileFilter != null) {
			fileChooser.setFileFilter(fileFilter);
		}
		selectionState = fileChooser.showOpenDialog(botCanvas);
		if (selectionState == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileChooser.getSelectedFile();
			fileContents = readFromFile(selectedFile);
		}

		return fileContents;
	}

	public synchronized String open() throws RuntimeException, FileNotFoundException, IOException {
		return open(null);
	}

	public synchronized void save(FileFilter fileFilter, String fileContent)
			throws IOException {
		
		JFileChooser fileChooser;
		int selectionState;
		File selectedFile;
		
		if (scriptName == null) {
			throw new RuntimeException("Initialise the API module first!");
		}
		
		fileChooser = new JFileChooser(scriptFolder);
		fileChooser.setMultiSelectionEnabled(false);
		if (fileFilter != null) {
			fileChooser.setFileFilter(fileFilter);
		}
		selectionState = fileChooser.showSaveDialog(botCanvas);
		if (selectionState == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileChooser.getSelectedFile();
			writeToFile(selectedFile, fileContent);
		}
	}

	public synchronized void save(String fileContent) throws IOException {
		save(null, fileContent);
	}
	
	public synchronized boolean deleteFile(String filename) {
		
		File file;
		
		if (filename == null || filename.isEmpty()) {
			throw new IllegalArgumentException("Filename must be valid");
		}
		
		file = new File(scriptFolder, filename);
		
		return !file.exists() || (file.isFile() && file.delete());
	}
}

  • Like 3
  • Heart 1
Link to comment
Share on other sites

  • 1 month later...

How do you make it work Mad cause I get a an error when I use Files API

[ERROR][Bot #1][02/20 05:41:20 PM]: Blocked permission: ("java.io.FilePermission" "C:\Users\ItsAMe\MyScriptStuff\accounts.txt" "read")

 

String fileName = System.getProperty("user.home") + "\\MyScriptStuff\\accounts.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))){
    stream.forEach((String s) -> {
        log(s);
    });
} catch (IOException e1) {
    e1.printStackTrace();
}

Edit cause it wasnt in the OSbot\\data folder. Works now, why dont they allow all folders tho?

Edited by oyyob11
Link to comment
Share on other sites

27 minutes ago, oyyob11 said:

How do you make it work Mad cause I get a an error when I use Files API


[ERROR][Bot #1][02/20 05:41:20 PM]: Blocked permission: ("java.io.FilePermission" "C:\Users\ItsAMe\MyScriptStuff\accounts.txt" "read")

 


String fileName = System.getProperty("user.home") + "\\MyScriptStuff\\accounts.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))){
    stream.forEach((String s) -> {
        log(s);
    });
} catch (IOException e1) {
    e1.printStackTrace();
}

 

Your problem is "C:\Users\ItsAMe\MyScriptStuff\accounts.txt".

Why? Because OSBot won't let you look, let alone touch, any files outside of the OSBot data directory: C:\Users\...\osbot\data\...

Edited by liverare
Link to comment
Share on other sites

Its quite annoying, im not sure why they wouldnt just have a melicious code scanner, and have it scan for all them kind of things. Than have staff manually review before posting to sdn, if an update occurs, have staff check it out again. Since I started coding on this api this morning ive had nothing but problems and headaches with the security and setup of the api... very disappointing, im sure things like this push dev's away. Not trying to be rude to anyone but why not trust people alittle instead of making me pull my hair out :(

Link to comment
Share on other sites

On 21/02/2018 at 1:02 AM, oyyob11 said:

Its quite annoying, im not sure why they wouldnt just have a melicious code scanner, and have it scan for all them kind of things. Than have staff manually review before posting to sdn, if an update occurs, have staff check it out again. Since I started coding on this api this morning ive had nothing but problems and headaches with the security and setup of the api... very disappointing, im sure things like this push dev's away. Not trying to be rude to anyone but why not trust people alittle instead of making me pull my hair out :(

It's just a security measure. If OSBot reads a malicious file, then the developers can be assured it originated from the data folder and that a scriptwriter/user is likely responsible for it. It has the added benefit of preventing scriptwriters from loading in password files.

I know there are other security measures in place, such as scriptwriters are no longer able to use Reflection, also I believe there's some sort of limitation when it comes to connecting to websites (or web stuff). It can be annoying at times, but I guess it's just the developers not taking the chance, because bad stuff has happened in the past.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...