Having Java call an Applescript file with arguments - java

I have a Java program that calls an Applescript file to run, and returns information back to Java. However, I need to also pass some arguments to the Applescript file. The relevant portion of the Java file:
public static void scriptRunner(String[] args) {
// Connect to the database.
ConnectionManager.getInstance().setDBType(DBType.MYSQL);
// Prepare the AppleScript file to be executed.
String homeFolder = System.getenv("HOME");
File scriptFile = new File(homeFolder + "/Documents/Output--Test.applescript");
InputStream scriptStream = null;
try {
scriptStream = FileUtils.openInputStream(scriptFile);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not find the Output AppleScript file. Please notify Chris McGee", "File not found", JOptionPane.ERROR_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(scriptStream));
// These two lines prepare the scripting engine, ready to run the script.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
// Add the parameters to the engine so they will be passed to the script.
engine.put("javaOrderNum", args[0]);
engine.put("javaShipDate", args[1]);
engine.put("javaInitials", args[2]);
engine.put("javaOverruns", args[3]);
// Run the script and evaluate the result.
log.trace("Run the script and evaluate the result.");
Object result = null;
try {
result = engine.eval(bufferedReader); // Run the script and place the result into an abstract object.
} catch (ScriptException e) {
JOptionPane.showMessageDialog(null, "Either an error occurred with the Output script or the user cancelled it.", "Script error / cancel", JOptionPane.INFORMATION_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
log.debug(result); // Check that we received the correct information back from the script.
log.debug("");
.
.
.
Sadly, the engine.put lines, as suggested from a forum I read during my searches to get this problem solved, don't seem to work. The AppleScript file:
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
set jInitials to item 3 of arguments
set jOverruns to item 4 of arguments
-- Set the correct folder variable
if (folderExists(POSIX path of "/Volumes/Users/Scripts/")) then
set server_prefix to "/Volumes/Users/Scripts/"
else if (folderExists(POSIX path of "/centralserver/Users/Scripts/")) then
set server_prefix to "/centralserver/Users/Scripts/"
else
display alert "Please connect to the central server, then try again.
If you have already done so, please let Chris McGee know."
end if
with timeout of (30 * 60) seconds
tell application "Adobe InDesign CS6"
set myJavaScript to server_prefix & "sky-artdept/Test/Output.jsx"
set myResult to do script myJavaScript with arguments {jOrderNum, jShipDate, jInitials, jOverruns} language javascript
return myResult
end tell
end timeout
on folderExists(posixPath)
return ((do shell script "if test -e " & quoted form of posixPath & "; then
echo 1;
else
echo 0;
fi") as integer) as boolean
end folderExists
I am given an error that the variable arguments is not defined. What can I try next?

I can't help with the javascript running the applescript. But, you applescript code is missing a declaration. You're asking for "item 1 of arguments" but you never define the variable arguments.
When the script is not inside any handler, it is implicit that it is inside a run() handler. And, since you're needing to pass arguments on run, you should try wrapping your script, minus the on folderExists() handler, inside a run handler that includes the arguments declaration.
on run(arguments)
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
…
end timeout
end run
on folderExists(posixPath)
…
end folderExists

Related

Process does not exit when launched from Java

I am launching WebTorrent-CLI from within my Java application as a separate process. I am using zt-exec for managing the process. When WebTorrent is launched with the following command, it is supposed to exit after the file at given index (value of --select) has been downloaded.
"D:\downloadmanager\node\webtorrent.cmd" download "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel" --select 0 --out "D://nf/"
As expected, webtorrent-cli does exit after downloading 0th file when the command above is used to launch it from command line. But when I try the same from within my Java app, it completely ignores the --select option and continues downloading other files in the torrent.
Basically, when launched as a process from Java, webtorrent ignores all the options set (--select, --out or whatever). I should mention that there is nothing wrong with the library because recently I've tried replacing it with commons-exec and that solved nothing. Also, to make sure that the right command is passed while starting the process, I'm printing the command right before calling executor.start(). The command above is copied from the output retrieved from printing the command before the process starts.
This is how the process is started:
#Override
public synchronized void start() throws IOException {
if (mWasDownloadStarted || mWasDownloadFinished) return;
mExec.getCommand().listIterator().forEachRemaining(s -> {
System.out.print(s + " ");
});
mExec.start();
setProcessId();
mWasDownloadStarted = true;
mWasDownloadStopped = false;
}
This is how the command is prepared:
private String buildCommand() {
List <String> command = new ArrayList<>();
command.add("\"" + mManager.mWTLocation + "\"");
command.add("download");
command.add("\"" + mManager.mMagnetUrl + "\"");
if (mManager.mFileIndex >= 0) {
command.add("--select " + mManager.mFileIndex);
}
if (mManager.mSaveTo != null) {
command.add("--out \"" + mManager.mSaveTo + "\"");
}
mManager.mExec.command(command);
String cmdStr = "";
for (String s : command) {
cmdStr = cmdStr.concat(s + " ");
}
return cmdStr.trim();
}
What might be wrong?
Okay, so I was able to fix this issue.
The / character following the path specified as value of --out was causing the problem. In order to fix this, I added a line in node_modules/webtorrent-cli/bin/cmd.js to print the arguments passed to webtorrent:
console.log(process.argv)
With the /, output of this line was something like the following:
[ 'D:\\downloadmanager\\node\\node.exe',
'D:\\downloadmanager\\node\\node_modules\\webtorrent-cli\\bin\\cmd.js',
'download',
'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel',
'--select',
'0',
'--out',
'D:\\nf"' ]
Note the " that is included in the path after D:\\nf. When / is removed from the path, the quote disappears and webtorrent behaves as expected.
I doubt that this is a bug in webtorrent. I think zt-exec (or maybe I) was doing something stupid.
Somewhat unrelated, but I think I should also mention that I had to enclose every value for each option with quotes, even the index, to get rid of other nasty errors (e.g.: Error 87, the parameter is incorrect)

Rsync command not working in java

The following commands works directly:
rsync -rtuc --delete-after --exclude '.git*' --filter 'protect .git/**/*' ~/some/source/ ~/some/destination/
But when run via java:
private Boolean syncFiles() {
// Success flag default to true
Boolean success = true;
// Attempt sync repo
try {
ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
"rsync", "-rtuc","--delete-after", "--exclude", "'.git*'", "--filter", "'protect .git/**/*'", "~/some/source/", "~/some/destination/"
});
// Wait until process terminates
int output = runtimeProcessBuilder.start().waitFor();
// Determine if successful
if (output == 0) {
System.out.println("Backup of " + getSource() + " to " + getDestination()
+ " was successful");
} else {
System.out.println("Error: rsync returned error code: " + output);
success = false;
}
} catch (Exception ex) {
success = false;
System.out.println("Error:");
System.out.println(ex.getMessage());
Logger.getLogger(Rsync.class.getName()).log(Level.SEVERE, null, ex);
}
return success;
}
I get the error:
Unknown filter rule: `'protect .git/**/*'' Error: rsync returned error
code: 1 rsync error: syntax or usage error (code 1) at exclude.c(902)
[client=3.1.2]
The shell handles quoting before passing the parameters to the command.
The comes into play with this part of your command line:
'protect .git/**/*'
The shell interprets this as the single parameter:
protect .git/**/*
If the single quotes had not been there in the first place, the shell would have:
interpreted it as two parameters (because of the space)
expanded glob characters like "*"
The solution is to pass:
"protect .git/**/"
as one of your Java parameters, rather than "'protect .git/**/*'".
You may have similar problems with ~, which the shell will expand to your home directory.
The answer to the solution is as follows:
The ProcessBuilder object needs to be initialised as follows:
ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
"rsync", "-rtuc","--delete-after", "--filter", "protect .git", "--exclude", "'.git*'", "~/some/source/", "~/some/destination/"
});

Java Bukkit/Spigot - Block Specified Commands

i'm trying to make a plugin, it must block a specified commands setted by config. i've maked this but it doesn't block any command.
Code:
#EventHandler(priority = EventPriority.HIGHEST)
public void onPreprocess(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
String command = event.getMessage();
List<String> bCmds = this.plugin.cfg.getStringList("blocked-commands");
for (String bCmd : bCmds)
{
if(command.equalsIgnoreCase(bCmd))
{
event.setCancelled(true);
}
}
}
Config:
blocked-commands:
- /pl
- /op
- /sp
- /gravityblock
PS: I've tried to use:
String command = event.getMessage().subString(1);
Thanks for Help... :)
Registered events? implemented listner?
Also your code will not work with additional arguments in the command.
If it contains spaces, split it with " " and get the first element to just get the command
if (cmd.contains(" ")) cmd = cmd.split(" ")[0];
As stated by Bukkit's wiiki, the priorities are called in the following order:
EventPriority.LOWEST
EventPriority.LOW
EventPriority.NORMAL
EventPriority.HIGH
EventPriority.HIGHEST
EventPriority.MONITOR
Maybe you could try to use the Lowest priority, so the event gets cancelled before the command is handled.
I also believe that the command might have arguments, so it might not be equal to the string provided, you should also try
String command = event.getMessage();
if (command.toLowerCase().startsWith("/command") ) {
//cancel
}

Java ProgramCall.run hangs

Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe

How can I pipe input to a Java app with Perl?

I need to write a Perl script that pipes input into a Java program. This is related to this, but that didn't help me. My issue is that the Java app doesn't get the print statements until I close the handle. What I found online was that $| needs to be set to something greater than 0, in which case newline characters will flush the buffer. This still doesn't work.
This is the script:
#! /usr/bin/perl -w
use strict;
use File::Basename;
$|=1;
open(TP, "| java -jar test.jar") or die "fail";
sleep(2);
print TP "this is test 1\n";
print TP "this is test 2\n";
print "tests printed, waiting 5s\n";
sleep(5);
print "wait over. closing handle...\n";
close TP;
print "closed.\n";
print "sleeping for 5s...\n";
sleep(5);
print "script finished!\n";
exit
And here is a sample Java app:
import java.util.Scanner;
public class test{
public static void main( String[] args ){
Scanner sc = new Scanner( System.in );
int crashcount = 0;
while( true ){
try{
String input = sc.nextLine();
System.out.println( ":: INPUT: " + input );
if( "bananas".equals(input) ){
break;
}
} catch( Exception e ){
System.out.println( ":: EXCEPTION: " + e.toString() );
crashcount++;
if( crashcount == 5 ){
System.out.println( ":: Looks like stdin is broke" );
break;
}
}
}
System.out.println( ":: IT'S OVER!" );
return;
}
}
The Java app should respond to receiving the test prints immediately, but it doesn't until the close statement in the Perl script. What am I doing wrong?
Note: the fix can only be in the Perl script. The Java app can't be changed. Also, File::Basename is there because I'm using it in the real script.
I've grown rather fond of the IO::Handle derived modules. They make it easy to control flushing, reading data, binary mode, and many other aspects of a handle.
In this case we use IO::File.
use IO::File;
my $tp = IO::File->new( "| java -jar test.jar" )
or die "fail - $!";
# Manual print and flush
$tp->print( 'I am fond of cake' );
$tp->flush;
# print and flush in one method
$tp->printflush( 'I like pie' );
# Set autoflush ON
$tp->autoflush(1);
$tp->print( 'I still like pie' );
Also, since the file handle is lexically scoped, you don't have to close it manually. It will automatically close when it goes out of scope.
BTW, unless you are targeting a perl older than 5.6, you can use the warnings pragma instead of -w. See perllexwarn for more info.
$|=1 only works on the currently selected file handle (by default, STDOUT). To make your TP file handle hot you need to do this after opening it:
select(TP);
$| = 1;
select(STDOUT);

Categories