Powershell: Capturing standard out and error with Process object - java

I want to start a Java program from PowerShell and get the results printed on the console.
I have followed the instructions of this question:
Capturing standard out and error with Start-Process
But for me, this is not working as I expected. What I'm doing wrong?
This is the script:
$psi = New-object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = 'java.exe'
$psi.Arguments = #("-jar","tools\compiler.jar","--compilation_level", "ADVANCED_OPTIMIZATIONS", "--js", $BuildFile, "--js_output_file", $BuildMinFile)
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
$process.Start() | Out-Null
$process.WaitForExit()
$output = $process.StandardOutput.ReadToEnd()
$output
The $output variable is always empty (and nothing is printed on the console of course).

The docs on the RedirectStandardError property suggests that it is better to put the WaitForExit() call after the ReadToEnd() call. The following works correctly for me:
$psi = New-object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = 'ipconfig.exe'
$psi.Arguments = #("/a")
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
[void]$process.Start()
$output = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
$output

Small variation so that you can selectively print the output if needed. As in if your looking just for error or warning messages and by the way Keith you saved my bacon with your response...
$psi = New-object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = 'robocopy'
$psi.Arguments = #("$HomeDirectory $NewHomeDirectory /MIR /XF desktop.ini /XD VDI /R:0 /W:0 /s /v /np")
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
[void]$process.Start()
do
{
$process.StandardOutput.ReadLine()
}
while (!$process.HasExited)

Here is a modification to paul's answer, hopefully it addresses the truncated output. i did a test using a failure and did not see truncation.
function Start-ProcessWithOutput
{
param ([string]$Path,[string[]]$ArgumentList)
$Output = New-Object -TypeName System.Text.StringBuilder
$Error = New-Object -TypeName System.Text.StringBuilder
$psi = New-object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = $Path
if ($ArgumentList.Count -gt 0)
{
$psi.Arguments = $ArgumentList
}
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
[void]$process.Start()
do
{
if (!$process.StandardOutput.EndOfStream)
{
[void]$Output.AppendLine($process.StandardOutput.ReadLine())
}
if (!$process.StandardError.EndOfStream)
{
[void]$Error.AppendLine($process.StandardError.ReadLine())
}
Start-Sleep -Milliseconds 10
} while (!$process.HasExited)
#read remainder
while (!$process.StandardOutput.EndOfStream)
{
#write-verbose 'read remaining output'
[void]$Output.AppendLine($process.StandardOutput.ReadLine())
}
while (!$process.StandardError.EndOfStream)
{
#write-verbose 'read remaining error'
[void]$Error.AppendLine($process.StandardError.ReadLine())
}
return #{ExitCode = $process.ExitCode; Output = $Output.ToString(); Error = $Error.ToString(); ExitTime=$process.ExitTime}
}
$p = Start-ProcessWithOutput "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x","-y","-oE:\PowershellModules",$NewModules.FullName -verbose
$p.ExitCode
$p.Output
$p.Error
the 10ms sleep is to avoid spinning cpu when nothing to read.

I was getting the deadlock scenario mentioned by Ash using Justin's solution. Modified the script accordingly to subscribe to async event handlers to get the output and error text which accomplishes the same thing but avoids the deadlock condition.
Seemed to resolve the deadlock issue in my testing without altering the return data.
# Define global variables used in the Start-ProcessWithOutput function.
$global:processOutputStringGlobal = ""
$global:processErrorStringGlobal = ""
# Launch an executable and return the exitcode, output text, and error text of the process.
function Start-ProcessWithOutput
{
# Function requires a path to an executable and an optional list of arguments
param (
[Parameter(Mandatory=$true)] [string]$ExecutablePath,
[Parameter(Mandatory=$false)] [string[]]$ArgumentList
)
# Reset our global variables to an empty string in the event this process is called multiple times.
$global:processOutputStringGlobal = ""
$global:processErrorStringGlobal = ""
# Create the Process Info object which contains details about the process. We tell it to
# redirect standard output and error output which will be collected and stored in a variable.
$ProcessStartInfoObject = New-object System.Diagnostics.ProcessStartInfo
$ProcessStartInfoObject.FileName = $ExecutablePath
$ProcessStartInfoObject.CreateNoWindow = $true
$ProcessStartInfoObject.UseShellExecute = $false
$ProcessStartInfoObject.RedirectStandardOutput = $true
$ProcessStartInfoObject.RedirectStandardError = $true
# Add the arguments to the process info object if any were provided
if ($ArgumentList.Count -gt 0)
{
$ProcessStartInfoObject.Arguments = $ArgumentList
}
# Create the object that will represent the process
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $ProcessStartInfoObject
# Define actions for the event handlers we will subscribe to in a moment. These are checking whether
# any data was sent by the event handler and updating the global variable if it is not null or empty.
$ProcessOutputEventAction = {
if ($null -ne $EventArgs.Data -and $EventArgs.Data -ne ""){
$global:processOutputStringGlobal += "$($EventArgs.Data)`r`n"
}
}
$ProcessErrorEventAction = {
if ($null -ne $EventArgs.Data -and $EventArgs.Data -ne ""){
$global:processErrorStringGlobal += "$($EventArgs.Data)`r`n"
}
}
# We need to create an event handler for the Process object. This will call the action defined above
# anytime that event is triggered. We are looking for output and error data received by the process
# and appending the global variables with those values.
Register-ObjectEvent -InputObject $Process -EventName "OutputDataReceived" -Action $ProcessOutputEventAction
Register-ObjectEvent -InputObject $Process -EventName "ErrorDataReceived" -Action $ProcessErrorEventAction
# Process starts here
[void]$Process.Start()
# This sets up an asyncronous task to read the console output from the process, which triggers the appropriate
# event, which we setup handlers for just above.
$Process.BeginErrorReadLine()
$Process.BeginOutputReadLine()
# Wait for the process to exit.
$Process.WaitForExit()
# We need to wait just a moment so the async tasks that are reading the output of the process can catch
# up. Not having this sleep here can cause the return values to be empty or incomplete. In my testing,
# it seemed like half a second was enough time to always get the data, but you may need to adjust accordingly.
Start-Sleep -Milliseconds 500
# Return an object that contains the exit code, output text, and error text.
return #{
ExitCode = $Process.ExitCode;
OutputString = $global:processOutputStringGlobal;
ErrorString = $global:processErrorStringGlobal;
ExitTime = $Process.ExitTime
}
}

Related

Different PowerShell script behavior in different console

So i write Windows update'r automat in java. For fetching needed data from windows servers i am using jPowerShell and i have stamble apon weird problem while execute this script
Java calling PowerShell Script
PowerShell ps = PowerShell.openSession();
PowerShellResponse response;
response = ps.executeScript("C:\\Users\\Prezes\\Desktop\\IsUpdateToInstal.ps1");
System.out.println(response.getCommandOutput());
PowerShell Script
$pw = ConvertTo-SecureString 'password' -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentList domein\login, $pw
Enter-PSSession -ComputerName IP -Credential $cred
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
$Critical = $SearchResult.updates | where { $_.MsrcSeverity -eq "Critical" }
$important = $SearchResult.updates | where { $_.MsrcSeverity -eq "Important" }
$other = $SearchResult.updates | where { $_.MsrcSeverity -eq $nul}
$totalUpdates = $($SearchResult.updates.count)
if($totalUpdates -gt 0)
{
$updatesToInstall = $true
}
else { $updatesToInstall = $false }
$other
$totalUpdates
$updatesToInstall
if i execute this script line by line in PowerShell standard consol everyting is working fine and proper value are returned.
But when i run this script in PowerShell ISE line by line or run by Java i notice some problem with this line
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
while i enter this line and press enter i can see in ISE "already running a command, please wait" when i wait a faw minutes communicate is the same and nothing change but when i press enter secound time command pass through immediately. If from them now i run rest of script evertying i working well.
When i try to excecute full script in ISE i am geting this error
Exception form HRESULT: 0x80072EE2
At C:\Users\Prezes\Desktop\IsUpdateToInstal.ps1:6 char:1
+ $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMExceptio
Java gives me null saying that i can't run methond on null object reffering to $UpdateSearcher
I am very early beginer with PowerShell and script that i am using is pure form some example finded in google.
So i had not figure out what was the cause of weird behavior but i managed to write someting that started to work for me through PowerShell api in java and get returned value.
$pw = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentList 792\opmanager, $pw
$TotalUpdates = Invoke-Command -ComputerName IP -ScriptBlock{
$UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session"))
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
$Critical = $SearchResult.updates | where { $_.MsrcSeverity -eq "Critical" }
$important = $SearchResult.updates | where { $_.MsrcSeverity -eq "Important" }
$other = $SearchResult.updates | where { $_.MsrcSeverity -eq $nul}
$totalUpdates = $($SearchResult.updates.count)
if($totalUpdates -gt 0)
{
$updatesToInstall = $true
}
else { $updatesToInstall = $false }
Return $totalUpdates
} -Credential $cred
$TotalUpdates

Fail to start windows service created using Procrun in powerShell

I created a java application(.jar) as a windows service using Procrun. This Service get installed and runs successfully when I use a batch(.bat) file. but I have this requirement of creating the same service using windows powerShell.
When I use PowerShell, service get installed but cannot start the service I checked in the windows event viewer and it displays as "Incorrect Function" Can anyone please tell me what could be the reason for this.
This is the string I used in PowerShell script to install the windows service
$CmdInstall=#'
--Description="$Description"
--DisplayName="$DisplayName"
--Install="$DAEMON"
--Startup=auto
--Type=
--DependsOn=
--Environment=
--User=
--Password=
--ServiceUser=
--ServicePassword=
--LibraryPath=
--JavaHome
--Jvm=auto
--JvmOptions=-Xmx1024M
--Classpath=server.jar
--JvmMs=
--JvmMx=
--JvmSs=
--StartMode=jvm
--StartImage=
--StartPath=
--StartClass=at.mrdevelopment.esl.server.Server
--StartMethod=main
--StartParams=
--StopMode=jvm
--StopImage=
--StopPath=
--StopClass=at.mrdevelopment.esl.server.ServerServiceStarter
--StopMethod=stop
--StopParams=
--StopTimeout=120
--LogPath=$LogPath
--LogPrefix=$InstanceName
--LogLevel=DEBUG
--LogJniMessages=
--StdOutput=auto
--StdError=auto
--PidFile=${InstanceName}.pid
'#
Any help would be appreciated.
This is the PowerShell script I used.
#region Parameters
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[ValidateNotNullOrEmpty()]
[string]$Action="//IS"
,
[ValidateNotNullOrEmpty()]
[string]$ServiceName="//ESL_SERVICE"
,
[ValidateNotNullOrEmpty()]
[string]$DisplayName="ESL_SERVICE"
,
[ValidateNotNullOrEmpty()]
[string]$Description="ESL Service"
,
[ValidateNotNullOrEmpty()]
[string]$InstanceName="server.jar"
,
[ValidateNotNullOrEmpty()]
[string]$LogPath='C:\Apachelogs'
,
[string]$Pause=60
)
#endregion
#region Main
$CmdInstall=#'
--Description="$Description"
--DisplayName="$DisplayName"
--Install="$DAEMON"
--Startup=auto
--Type=
--DependsOn=
--Environment=
--User=
--Password=
--ServiceUser=
--ServicePassword=
--LibraryPath=
--JavaHome
--Jvm=auto
--JvmOptions=-Xmx1024M
--Classpath=server.jar
--JvmMs=
--JvmMx=
--JvmSs=
--StartMode=jvm
--StartImage=
--StartPath=
--StartClass=at.mrdevelopment.esl.server.Server
--StartMethod=main
--StartParams=
--StopMode=jvm
--StopImage=
--StopPath=
--StopClass=at.mrdevelopment.esl.server.ServerServiceStarter
--StopMethod=stop
--StopParams=
--StopTimeout=120
--LogPath=$LogPath
--LogPrefix=$InstanceName
--LogLevel=DEBUG
--LogJniMessages=
--StdOutput=auto
--StdError=auto
--PidFile=${InstanceName}.pid
'#
$DAEMON_HOME = "C:\imagotag\server"
$DAEMON = "$DAEMON_HOME\prunsrv_64.exe"
$ESL_HOME = "C:\imagotag\server"
$CmdArgsDict=#{}
$CmdArgsDict.Add('//IS', "$Action$ServiceName $CmdInstall")
$CmdArgs = $CmdArgsDict[$action]
# Convert backslashes in the paths to java-friendly forward slashes
$CmdArgs = $CmdArgs -replace "\\","/"
# Variable interpolation: expand embedded variables references (need to call this twice)
$CmdArgs = $ExecutionContext.InvokeCommand.ExpandString($CmdArgs)
$CmdArgs = $ExecutionContext.InvokeCommand.ExpandString($CmdArgs)
# Split on newlines to convert to an array of lines
$CmdArgsString = $CmdArgs -split "`n"
# Convert array of lines into a string
$CmdArgsString = "$CmdArgsString"
#--- Execute the command
if ($PSCmdlet.ShouldProcess(
"`n$DAEMON`n$CmdArgs","Manage ESL Service"
))
{
"$DAEMON $CmdArgsString"
$p=Start-Process "$DAEMON" `
-ArgumentList "$CmdArgsString" `
-Wait `
-NoNewWindow `
-PassThru
$rc = $p.ExitCode
"`nExit Code: $rc"
}
#endregion
My PowerShell script is TestPS.ps1 and I execute the script like this
.\TestPS.ps1 //IS
For creating a service , use the following cmdlet in PS:
$username = "Username"
$password = "password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
new-service -Name [INSERT SERVICE NAME] -DisplayName "[INSERT DISPLAY NAME]" -Description "[INSERT DESCRIPTION]" -BinaryPathName "[INSERT BINARY PATH]" -StartupType Manual -Credential $cred
If you wish to perform it remotely, then use the following function:
function Install-Service(
[string]$serviceName = $(throw "serviceName is required"),
[string]$targetServer = $(throw "targetServer is required"),
[string]$displayName = $(throw "displayName is required"),
[string]$physicalPath = $(throw "physicalPath is required"),
[string]$userName = $(throw "userName is required"),
[string]$password = "",
[string]$startMode = "Automatic",
[string]$description = "",
[bool]$interactWithDesktop = $false
)
{
# can't use installutil; only for installing services locally
#[wmiclass]"Win32_Service" | Get-Member -memberType Method | format-list -property:*
#[wmiclass]"Win32_Service"::Create( ... )
# todo: cleanup this section
$serviceType = 16 # OwnProcess
$serviceErrorControl = 1 # UserNotified
$loadOrderGroup = $null
$loadOrderGroupDepend = $null
$dependencies = $null
# description?
$params = `
$serviceName, `
$displayName, `
$physicalPath, `
$serviceType, `
$serviceErrorControl, `
$startMode, `
$interactWithDesktop, `
$userName, `
$password, `
$loadOrderGroup, `
$loadOrderGroupDepend, `
$dependencies `
$scope = new-object System.Management.ManagementScope("\\$targetServer\root\cimv2", `
(new-object System.Management.ConnectionOptions))
"Connecting to $targetServer"
$scope.Connect()
$mgt = new-object System.Management.ManagementClass($scope, `
(new-object System.Management.ManagementPath("Win32_Service")), `
(new-object System.Management.ObjectGetOptions))
$op = "service $serviceName ($physicalPath) on $targetServer"
"Installing $op"
$result = $mgt.InvokeMethod("Create", $params)
Test-ServiceResult -operation "Install $op" -result $result
"Installed $op"
"Setting $serviceName description to '$description'"
Set-Service -ComputerName $targetServer -Name $serviceName -Description $description
"Service install complete"
}
Here is the Guide to Install Windows Service Remotely
Note: Make sure you are running everything with elevated mode.
Hope it helps.
Your problems came from a misconfigured service. That comes from a problem with the parameters of prunsrv.exe.
The script works well after changing the line
$CmdArgsString = $CmdArgs -split "`n"
to
$CmdArgsString = $CmdArgs -split "`r`n"

PowerShell | System.Diagnostics.Process | Java | Hide Window

I try to start an Java program from a PowerShell script, but I don't want see any window. I have already tried all possible combinations of parameters for ProcessStartInfo and Process, but it still displays a empty shell window for java.exe. This is my current PowerShell code:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "$jre\bin\java.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.CreateNoWindow = $true
$pinfo.WindowStyle = "Hidden"
$pinfo.UseShellExecute = $false
$pinfo.WorkingDirectory = $temp
if ($integrated) {
Write-Output "Connecting using integrated security ..."
# Start with different user context
$securePassword = ConvertTo-SecureString $pw -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePassword
$pinfo.UserName = $credential.GetNetworkCredential().UserName
$pinfo.Domain = $credential.GetNetworkCredential().Domain
$pinfo.Password = $credential.Password
$pinfo.Arguments = "-jar `"$jar`" validate -url `"$jdbc`" -i -dbVersion `"$msSqlVersion`""
} else {
Write-Output "Connecting ..."
$pinfo.Arguments = "-jar `"$jar`" validate -url `"$jdbc`" -u `"$user`" -p `"$pw`" -dbVersion `"$dbVersion`""
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start()
$p.StandardOutput.ReadToEnd()
$p.StandardError.ReadToEnd()
$p.WaitForExit()
I hope anyone could help me with this issue.

Create external process and wait 5 seconds kill it in php

I want to kill a external process after 5 seconds it created
That process is javac Hello.java & java Hello
I figured out a method that is kill process's pid, but samples below cannot get pid.
<?php
system('javac Hello.java & java Hello', $retval);
popen('javac Hello.java & java Hello', 'w');
?>
I don't understand proc_open() and proc_get_status example in PHP manual.
In my case, how to do that?
Here is a very clear explanation for how to use proc_open()
https://www.sitepoint.com/proc-open-communicate-with-the-outside-world/
I've done my job for creating an external process to compile , run java program, wait seconds, kill java running process in PHP script.
Here is that script:
<?php
/**
This is a judge script for verifying lab assignment
of NTU Civil Engineering Computer Programing with no testdata.
You can copy, redistribute, or modify it freely.
Tips:
It is not necessary to use file already provided.
Any related file can be uploaded via testdata field.
Then how to apply specific file uploaded to ./problem/testdata/[item]/[subitem]
completely depends on by how the judge file is defined.
*/
// Error report mechanism of this script
ini_set('display_errors', '1');
ERROR_REPORTING(E_ALL);
// Auto load class definition file that this script will be using.
function __autoload($class_name) {
include_once($class_name . '.php');
}
class Java_No_Input {
private $stu_account;
private $item;
private $subitem;
private $main;
private $dir_name;
private $status;
private $solution_output;
private $student_output;
private $hookup;
public function __construct () {
// Arguments: student account, item, subitem
$this->stu_account = $_SERVER['argv'][1];
$this->item = $_SERVER['argv'][2];
$this->subitem = $_SERVER['argv'][3];
try {
// Connect to MySQL database TAFreeDB
$this->hookup = UniversalConnect::doConnect();
// Create directory to put source codes temporarily
$this->createDir();
// Fetch student and solution source from table [item]_[subitem]
$this->fetchSource();
// Start judge
$this->startJudge();
// Update judge status
$this->updateStatus();
// Remove directory
$this->removeDir();
$this->hookup = null;
exit();
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br>';
}
}
public function createDir () {
$this->dir_name = './process/' . uniqid(time(), true);
mkdir($this->dir_name);
mkdir($this->dir_name . '/student');
mkdir($this->dir_name . '/solution');
}
public function removeDir () {
system('rm -rf ' . $this->dir_name, $retval);
if ($retval !== 0 ) {
echo 'Directory can not be removed...';
exit();
}
}
public function fetchSource () {
$stmt = $this->hookup->prepare('SELECT main, classname, original_source, ' . $this->stu_account . ' FROM ' . $this->item . '_' . $this->subitem);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['main'] === 'V') {
$this->main = $row['classname'];
}
$student = fopen($this->dir_name . '/student/' . $row['classname'], 'w');
fwrite($student, $row[$this->stu_account]);
fclose($student);
$solution = fopen($this->dir_name . '/solution/' . $row['classname'], 'w');
fwrite($solution, $row['original_source']);
fclose($solution);
}
}
public function startJudge () {
// Solution and student directory whose source is in
$solution_dir = $this->dir_name . '/solution';
$student_dir = $this->dir_name . '/student';
// Compile source code from both solution and student
$solution_CE = $this->compile($solution_dir);
if (!empty($solution_CE)) {
// Configure result that will response to client side
$error_msg = '<h1>Solution has compiler error</h1>' . '<pre><code>' . $solution_CE . '</code></pre>';
$this->configureView($error_msg);
// System error
$this->status = 'SE';
return;
}
$student_CE = $this->compile($student_dir);
if (!empty($student_CE)) {
// Configure result that will response to client side
$error_msg = '<h1>Your source code has compiler error</h1>' . '<pre><code>' . $student_CE . '</code></pre>';
$this->configureView($error_msg);
// Compiler error
$this->status = 'CE';
return;
}
// Execute source code from both solution and student
$solution_RE = $this->execute($solution_dir, 2);
if (!empty($solution_RE)) {
// Configure result that will response to client side
$error_msg = '<h1>Solution has runtime error</h1>' . '<pre><code>' . $solution_RE . '</code></pre>';
$this->configureView($error_msg);
// System error
$this->status = 'SE';
return;
}
$student_RE = $this->execute($student_dir, 2);
if (!empty($student_RE)) {
// Configure result that will response to client side
$error_msg = '<h1>Your source code has runtime error</h1>' . '<pre><code>' . $student_RE . '</code></pre>';
$this->configureView($error_msg);
// Runtime error
$this->status = 'RE';
return;
}
// Compare output from both solution and student
$this->solution_output = $this->execute($solution_dir, 1);
$this->student_output = $this->execute($student_dir, 1);
$retval = strcmp($this->solution_output, $this->student_output);
if ($retval === 0) {
// Accept
$this->status = 'AC';
}
else {
// Wrong Answer
$this->status = 'WA';
}
// Configure result that will response to client side
$error_msg = null;
$this->configureView($error_msg);
return;
}
public function compile ($dir) {
// Configure descriptor array
$desc = array (
0 => array ('pipe', 'r'), // STDIN for process
1 => array ('pipe', 'w'), // STDOUT for process
2 => array ('pipe', 'w') // STDERR for process
);
// Configure compilation command
$cmd = 'javac -d ' . $dir . ' ';
$source = glob($dir . '/*');
foreach ($source as $key => $value) {
$cmd .= $value . ' ';
}
// Create compilation process
$process = proc_open($cmd, $desc, $pipes);
// Close STDIN pipe
fclose($pipes[0]);
// Get output of STDERR pipe
$error = stream_get_contents($pipes[2]);
// Close STDOUT and STDERR pipe
fclose($pipes[1]);
fclose($pipes[2]);
// Close process
proc_close($process);
return $error;
}
public function execute ($dir, $pipe_id) {
// Configure descriptor array
$desc = array (
0 => array ('pipe', 'r'), // STDIN for process
1 => array ('pipe', 'w'), // STDOUT for process
2 => array ('pipe', 'w') // STDERR for process
);
// Configure execution command
$cmd = 'exec java -classpath ' . $dir . ' ';
$last_pos = strrpos($this->main, '.java');
$classname = substr($this->main, 0, $last_pos);
$cmd .= $classname;
// Create execution process
$process = proc_open($cmd, $desc, $pipes);
// Get pid of execution process
$process_status = proc_get_status($process);
$pid = $process_status['pid'];
// Close STDIN pipe
fclose($pipes[0]);
// Wait seconds
sleep(1);
// Kill execution process
posix_kill($pid, SIGTERM);
// Get output of STDOUT or STDERR pipe
$output = stream_get_contents($pipes[$pipe_id]);
// Close STDOUT and STDERR pipe
fclose($pipes[1]);
fclose($pipes[2]);
return $output;
}
public function updateStatus () {
$stmt = $this->hookup->prepare('UPDATE ' . $this->item . ' SET ' . $this->stu_account . '=\'' . $this->status . '\' WHERE subitem=\'' . $this->subitem . '\'');
$stmt->execute();
}
public function configureView ($error_msg) {
if (!is_null($error_msg)) {
echo $error_msg;
}
else {
$result = '';
if ($this->status === 'WA') {
$result = 'Wrong Answer';
}
if ($this->status === 'AC') {
$result = 'Accept';
}
echo<<<EOF
<h1>$result</h1>
<div class='WHOSE_DIV'>
<img class='UP_DOWN_IMG' src='./tafree-svg/attention.svg'>
<div class='RES_DIV'>
<div class='SOL_DIV'>{$this->solution_output}</div>
<div class='STU_DIV'>{$this->student_output}</div>
</div>
</div>
EOF;
}
return;
}
}
$judger = new Java_No_Input();
?>

Getting output from Perl script called from Java code

I've read a lot of questions/examples on this issue, but unfortunately I have not been able to solve my problem. I need to call a Perl script (that I cannot change) from Java code, and then I need to get the output from that script.
The script is used to take student programming homework assignments, and check them for copying by comparing all of them together. The script can take ~45 seconds to run, but only requires the arguments to be properly formatted, there is no interactivity.
My issue is when I call the script from my Java code I get the first line of output from the script but nothing else. I'm using Runtime.exe() and then waitFor() to wait for the script to finish. However the waitFor() function returns before the script actually finishes. I don't know any Perl so I'm not sure if the script is doing something that 'confuses' the java Process object, or if there's an issue in my code.
Process run = Runtime.getRuntime().exec(cmd);
output = new BufferedReader(new InputStreamReader(run.getInputStream()));
run.waitFor();
String temp;
while((temp = output.readLine()) != null){
System.out.println(temp);
}
The Perl script..
use IO::Socket;
#
# As of the date this script was written, the following languages were supported. This script will work with
# languages added later however. Check the moss website for the full list of supported languages.
#
#languages = ("c", "cc", "java", "ml", "pascal", "ada", "lisp", "scheme", "haskell", "fortran", "ascii", "vhdl", "perl", "matlab", "python", "mips", "prolog", "spice", "vb", "csharp", "modula2", "a8086", "javascript", "plsql", "verilog");
$server = 'moss.stanford.edu';
$port = '7690';
$noreq = "Request not sent.";
$usage = "usage: moss [-x] [-l language] [-d] [-b basefile1] ... [-b basefilen] [-m #] [-c \"string\"] file1 file2 file3 ...";
#
# The userid is used to authenticate your queries to the server; don't change it!
#
$userid=[REDACTED];
#
# Process the command line options. This is done in a non-standard
# way to allow multiple -b's.
#
$opt_l = "c"; # default language is c
$opt_m = 10;
$opt_d = 0;
$opt_x = 0;
$opt_c = "";
$opt_n = 250;
$bindex = 0; # this becomes non-zero if we have any base files
while (#ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
($first,$rest) = ($1,$2);
shift(#ARGV);
if ($first eq "d") {
$opt_d = 1;
next;
}
if ($first eq "b") {
if($rest eq '') {
die "No argument for option -b.\n" unless #ARGV;
$rest = shift(#ARGV);
}
$opt_b[$bindex++] = $rest;
next;
}
if ($first eq "l") {
if ($rest eq '') {
die "No argument for option -l.\n" unless #ARGV;
$rest = shift(#ARGV);
}
$opt_l = $rest;
next;
}
if ($first eq "m") {
if($rest eq '') {
die "No argument for option -m.\n" unless #ARGV;
$rest = shift(#ARGV);
}
$opt_m = $rest;
next;
}
if ($first eq "c") {
if($rest eq '') {
die "No argument for option -c.\n" unless #ARGV;
$rest = shift(#ARGV);
}
$opt_c = $rest;
next;
}
if ($first eq "n") {
if($rest eq '') {
die "No argument for option -n.\n" unless #ARGV;
$rest = shift(#ARGV);
}
$opt_n = $rest;
next;
}
if ($first eq "x") {
$opt_x = 1;
next;
}
#
# Override the name of the server. This is used for testing this script.
#
if ($first eq "s") {
$server = shift(#ARGV);
next;
}
#
# Override the port. This is used for testing this script.
#
if ($first eq "p") {
$port = shift(#ARGV);
next;
}
die "Unrecognized option -$first. $usage\n";
}
#
# Check a bunch of things first to ensure that the
# script will be able to run to completion.
#
#
# Make sure all the argument files exist and are readable.
#
print "Checking files . . . \n";
$i = 0;
while($i < $bindex)
{
die "Base file $opt_b[$i] does not exist. $noreq\n" unless -e "$opt_b[$i]";
die "Base file $opt_b[$i] is not readable. $noreq\n" unless -r "$opt_b[$i]";
die "Base file $opt_b is not a text file. $noreq\n" unless -T "$opt_b[$i]";
$i++;
}
foreach $file (#ARGV)
{
die "File $file does not exist. $noreq\n" unless -e "$file";
die "File $file is not readable. $noreq\n" unless -r "$file";
die "File $file is not a text file. $noreq\n" unless -T "$file";
}
if ("#ARGV" eq '') {
die "No files submitted.\n $usage";
}
print "OK\n";
#
# Now the real processing begins.
#
$sock = new IO::Socket::INET (
PeerAddr => $server,
PeerPort => $port,
Proto => 'tcp',
);
die "Could not connect to server $server: $!\n" unless $sock;
$sock->autoflush(1);
sub read_from_server {
$msg = <$sock>;
print $msg;
}
sub upload_file {
local ($file, $id, $lang) = #_;
#
# The stat function does not seem to give correct filesizes on windows, so
# we compute the size here via brute force.
#
open(F,$file);
$size = 0;
while (<F>) {
$size += length($_);
}
close(F);
print "Uploading $file ...";
open(F,$file);
$file =~s/\s/\_/g; # replace blanks in filename with underscores
print $sock "file $id $lang $size $file\n";
while (<F>) {
print $sock $_;
}
close(F);
print "done.\n";
}
print $sock "moss $userid\n"; # authenticate user
print $sock "directory $opt_d\n";
print $sock "X $opt_x\n";
print $sock "maxmatches $opt_m\n";
print $sock "show $opt_n\n";
#
# confirm that we have a supported languages
#
print $sock "language $opt_l\n";
$msg = <$sock>;
chop($msg);
if ($msg eq "no") {
print $sock "end\n";
die "Unrecognized language $opt_l.";
}
# upload any base files
$i = 0;
while($i < $bindex) {
&upload_file($opt_b[$i++],0,$opt_l);
}
$setid = 1;
foreach $file (#ARGV) {
&upload_file($file,$setid++,$opt_l);
}
print $sock "query 0 $opt_c\n";
print "Query submitted. Waiting for the server's response.\n";
&read_from_server();
print $sock "end\n";
close($sock);
Thank you for any input you may have on my problem.
You can use my native Java client for MOSS instead .
Don't mind the version number. I've been using it in production successfully.

Categories