Data retrieval from Perl to Java - perl

Currently, I am reading some data from Perl, I want to retrieve messages from Perl for each and every step. I tried using this code,
Process process = Runtime.getRuntime().exec(new String[] {"perl","C:\\Perl\\bin\\try.pl", "uname=test"});
BufferedReader reader =new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = reader.readLine();
System.out.println("perl said [ " + s + " ]");
My perl script as follows,
$path_to_file = $ARGV[0] or die("argument not passed") ;
print "success";
# some code
If I dont receive any argument, then we need to retrieve the message, that there is no argument passed. like that I want log all the information. I tried giving print data. That is working. But if the argument is not passed. I want the data that argument not passed.
is it possible to retrieve?

I hereby found the answer for my above question,
Process process = Runtime.getRuntime().exec(new String[] {"perl","C:\\Perl\\bin\\try.pl", "uname=test"});
BufferedReader readError = new BufferedReader( new InputStreamReader(process.getErrorStream()));
s = readError.readLine();
System.err.println("perl said [ " + s + " ]");
By this way i capture the error details. Thanks for all your suggestions. Also, i changed my perl script as follows,
my $path_to_file = $ARGV[0] or {print " Argument not passed! " };

Related

Perl to exec a program with arguments containing "#"

Am a newbie in Perl and need help with a small problem
Situation:
I have to execute a command line program through perl.
The arguments to this command line are email addresses
These email addresses are passed to me through another module.
Problem:
I have written the code to create the argument list from these email addresses but am having problem in running exec().
NOTE: If I pass hardcoded strings with escaped "#" character to the exec() as command args,it works perfectly.
Sub creating cmd args map
sub create_cmd_args {
my($self, $msginfo) = #_;
my #gd_args_msg = ('--op1');
my $mf = $msginfo->sender_smtp;
$mf =~ s/#/\\#/ig; ## Tried escaping #, incorrect results.
push #gd_args_msg, '-f="'.$mf.'"';
for my $r (#{$msginfo->per_recip_data}) {
my $recip = $r->recip_addr_smtp;
$recip =~ s/#/\\#/ig; ## Tried escaping #, incorrect results.
push #gd_args_msg, '-r="'.($recip).'"';
}
return #gd_args_msg;
}
Sub that uses this args map to exec the program
sub check {
my($self, $msginfo) = #_;
my $cmd = $g_command;
my #cmd_args = create_cmd_args($self, $msginfo);
exec($cmd, #cmd_args); ### ******* fails here
}
Sample run:
INPUT:
sender_smtp: <ashish#isthisreal.com>
receiver_smtp: <areyouarealperson#somedomain.com>
Could someone please guide me what is wrong here?
As an argument to a command in the shell,
-f="<ashish#isthisreal.com>"
causes the the string
-f=<ashish#isthisreal.com>
to be passed to the program. Your program passes
-f="<ashish\#isthisreal.com>"
to the program. The problem isn't the #; the problem is the " and \ you are adding.
my $mf = $msginfo->sender_smtp;
push #gd_args_msg, "-f=$mf"; # Assuming $mf is <ashish#isthisreal.com>
If you look at the post at Trying to convert Perl to PHP and the code within the md5sum implementation that calls the command line you will see an approach that will save you from needing to worry about escaping characters.

Expect script output at Perl console

I have a exp script -script.exp to enter a name and password. it calls test.sh file like below.
set timeout -1
spawn ./test.sh -create
match_max 100000
expect -exact "Enter the name: "
send -- "abcd\r"
expect -exact "\r
Please confirm password: "
send -- "xxy\r"
expect -exact "\r
expect eof
It gives me a output at expect window -
"Successfully entered the name"
if some issue there it throws exception or error message.
I run this expect script in a Perl file-- like below
$cmd="expect script.exp";
system($cmd);
$outputfromexp=?
I need a output of fail or passed status of exp at Perl console after running the script.
How can i do this? Please help me.
I tried calling as suggested in my Perl script--
use strict;
use warnings;
sub sysrun {
my ($command) ="expect script.exp";
my $ret_code;
$ret_code = system("$command");
if ( $ret_code == 0 ) {
# Job suceeded
$ret_code = 1;
}
else {
# Job Failed
$ret_code = 0;
}
return ($ret_code);
}
my $ret_code=sysrun();
print "reuturmsfg- $ret_code\n";
But its printing nothing-- just reuturmsfg-.
I made the changes-
my $ret_code=sysrun();
it gives me 0 and 1 return code.
If I understand the question correctly, to get the return code you want to do:
system($cmd);
my $ret_code = $?;
To get STDOUT output from the execution:
my #out = `$cmd`;
my $ret_code = $?;
I strongly suggest using strict and warnings in your code.

Examples from Net::RabbitMQ not working

I'm trying to learn RabbitMQ for a project I'm working on. My research showed two libraries to use, Net::RabbitMQ and AnyEvent::RabbitMQ. AnyEvent::RabbitMQ seems overly baroque for my needs but Net::RabbitMQ does not appear to work as the examples show it should.
Below is some example code I found, it matches what I saw in the POD, but it isn't working.
#!/usr/bin/env perl
use strict;
use warnings;
use Net::RabbitMQ;
{
# closure to return a new channel ID every time we call nextchan
my $nextchan = 1;
sub nextchan { return $nextchan++ }
}
### BEGIN CONFIGURABLE PARAMETERS ######################################
my $qserver = q{xx.xx.xx.xx};
my %qparms = ();
my $qname = q{gravity.checks};
my $message = q{Test injection};
### NO CONFIGURABLE PARAMETERS BELOW THIS LINE #########################
my $mq = Net::RabbitMQ->new();
my $chanID = nextchan();
$message .= " " . scalar(localtime);
print STDERR qq{Will try to send message "$message" through channel $chanID};
$mq->connect( $qserver, %qparms );
It errors out :
$. / send . pl
Will try to send message "Test injection Fri Nov 14 06:50:44 2014" through channel 1 Usage : Net::RabbitMQ::connect( conn, hostname, options ) at . /send.pl line 28.
The problem is that the %qparams need to be passed by reference and not directly. The change line 28 to :
$mq->connect($qserver, \%qparms) ;
Solved my problem.
It doesn't error out. It prints to STDERR without checking if an error occured. It says I'll try and then it does:
$mq->connect( $qserver, %qparms );
This is just an information, not an error.

methods like opencurrentdatabase in perl

I am new to perl. I am asked to execute a macro in ms access database using perl. This is the code i used
$oAccess = Win32::OLE->GetActiveObject('Access.Application');
$oAccess ->OpenCurrentDatabase($path);
$oAccess ->{DoCmd}->RunMacro("DO ALL");
Today when i was executing the program i found that only if the access database is open the code works fine else it returns the following error
Can't call method "OpenCurrentDatabase" on an undefined value at auto.pl line 30
So I was wondering if i could find any other code which would serve the purpose without an open ms access database.
my $MSAccess;
eval {$MSAccess = Win32::OLE->GetActiveObject('Access.Application')};
die "Access not installed" if $#;
unless (defined $MSAccess) {
$MSAccess = Win32::OLE->new('Access.Application','Quit')
or die "Unable to start Access";
}
$MSAccess->{visible} = 0;

Pass string with quote into a VB application with cscript.exe

I have a VB script that takes in several parameters that could include spaces using cscript, and I make the call using:
nsExec::exec 'cscript.exe "$PATH_TO_FILE\program.vbs" "Something with spaces" "Something else"'
Now, I want one of the "Something else" strings to include a double quote character, where the string is
Something " else.
I have tried
nsExec::exec 'cscript.exe "$PATH_TO_FILE\program.vbs" "Something with spaces" "Something "" else."'
with an escaped " but that did not work, it simply used "Something else" as the string passed in.
Basically, there is not a way to deal with these quotes, so you need a workaround (use QUOTE and then replace in program with a ').
You can read the entire process command line as one string like this (JScript code, sorry):
// Read process command line
var WshShell = WScript.CreateObject("WScript.Shell");
var objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
var childProcess =
WshShell.Exec
(
'"' + WshShell.Environment('PROCESS')('ComSpec') + '"'
+
" /C Echo \"Text lines\" && Set /p VarName="
);
childProcess.StdOut.ReadLine();
var current_pid =
objWMIService.ExecQuery
(
"Select * From Win32_Process Where ProcessId=" + childProcess.ProcessID
);
current_pid = (new Enumerator(current_pid)).item().ParentProcessId;
if (current_pid)
{
childProcess.StdIn.WriteLine("value"); // child process should now exit
}
else
{
WScript.StdErr.WriteLine("Get current PID from WMI failed.");
WScript.Quit(7);
}
var cmd_line = objWMIService.ExecQuery("Select * From Win32_Process Where ProcessID=" + current_pid);
cmd_line = (new Enumerator(cmd_line)).item().CommandLine;
WScript.Echo(cmd_line);
but than you will have to parse the string into separate arguments yourself.