How to call Nashorn from Java - windows

I have a batfile that I want to call from java. I made a nashorn script, that runs successfully from commandline and from Netbeans 'run' command. Here it is:
#!C:/Program Files/Java/jdk1.8.0_25/bin -fv
$ENV.PWD = 'C:/Hydromodel/MapGenerate';
$EXEC("cmd /c start cmd_all.bat");
print ('finished!');
I try to call the script from java this way:
public class RunCmd {
public void nashornTest() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
Object eval = engine.eval("load('src/simple/a_test.js');");
//Object eval = engine.eval(new FileReader("C:/_Udvikling/Maven/realtid_2014/src/main/java/simple/a_test.js"));
} catch (Exception ex ) {
Logger.getLogger(CmdTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Both ways I get this error:
Severe: javax.script.ScriptException: TypeError: Cannot load script from src/simple/a_test.js in <eval> at line number 1
Even if the javascript file is reduced to:
print ('hello!');
I also tried this SO proposed way
The Error stays.
I googled, but most people seem to use Linux or Mac when writing about Nashorn.
Should I do anything special to call Nashorn from java on a Windows box?
mbwiese
I am running Netbeans 8 and JDK 8 with Glassfish 4.1 on Windows 7

Related

PowerShell DSC resource MSFT_PackageResource failed: The return code 1618 was not expected. Configuration is likely not correct

I have exe file downloaded in the VM in specific folder, I am trying to install Adobe using Powershell dsc code.
Script is failing with below error during execution (Configuration is called through ARM template), however if I check inside the VM, adobe is installed.
Tried running the same script manually inside the VM. Not facing any error though.
[{"code":"VMExtensionProvisioningError","message":"VM has reported a failure when processing extension 'configureWindowsServer'. Error message: "DSC Configuration 'Adobe' completed with error(s). Following are the first few: PowerShell DSC resource MSFT_PackageResource failed to execute Set-TargetResource functionality with error message: The return code 1618 was not expected. Configuration is likely not correct The SendConfigurationApply function did not succeed."\r\n\r\nMore information on troubleshooting is available at https://aka.ms/VMExtensionDSCWindowsTroubleshoot "}]}
Configuration Adobe
{
$PackagesFolder = "C:\Packages\Adobe"
$AcrobatReader = #{
"Name" = "Adobe Acrobat Reader DC"
"ProductId" = "XXXXXX-XXXXX-XXXXXXX"
"Installer" = "AcroRdrDC.exe"
"FileHash" = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"HashAlgorithm" = "SHA256"
"DestinationPath" = "$PackagesFolder\AdobeAcrobatReaderDC"
"Arguments" = "/msi EULA_ACCEPT=YES /qn"
}
Package AdobeAcrobatReaderDC {
Ensure = "Present"
Name = $AcrobatReader.Name
ProductId = $AcrobatReader.ProductId
Path = ("{0}\{1}" -f $AcrobatReader.DestinationPath, $AcrobatReader.Installer)
Arguments = $AcrobatReader.Arguments
}
}

making shell zip accessible to php

Hi got a LEMP stack un Ubuntu 18.04 with php 7.2.5
server info says
Shell Exec Is Supported
Shell Exec Zip Not Supported
therefore some of my plugins says
This server is not configured for the Shell Zip engine - please use a different engine mode. To make 'Shell Zip' available, ask your host to:
1. Install the zip executable and make it accessible to PHP.
I have tries this code
PHP - How to know if server allows shell_exec
if(function_exists('shell_exec')) {
echo "exec is enabled";
}
and the function is enabled
however when i test if it is executable with the code below nothing happens.
As DanFromGermany pointed out, you probably check then if it is
executable. Something like this would do it
if(shell_exec('echo foobar') == 'foobar'){
echo 'shell_exec works';
}
or tried this, returns nothing as well just white page
// Exec function exists.
// Exec is not disabled.
// Safe Mode is not on.
$exec_enabled =
function_exists('exec') &&
!in_array('exec', array_map('trim', explode(', ', ini_get('disable_functions')))) &&
strtolower(ini_get('safe_mode')) != 1
;
if($exec_enabled) { exec('blah'); }
I have also checked with the code below from https://wpguru.co.uk/2014/01/how-to-test-if-a-shell-command-will-work-in-php/ and it does work
// helper function
function checkShellCommand($command) {
$returnValue = shell_exec("$command");
if(empty($returnValue)) {
return false;
} else {
return true;
}
}
// test the shell command you'd like to use
if (!checkShellCommand('uname -a')) {
print 'This command cannot be executed.';
} else {
echo shell_exec('uname -a');
}
So, could anyone tell me how can I make it accessible to PHP
Many thanks
this was solved by
apt-get install zip unzip

Beanshell Script throws error while running from terminal but it runs perfectly in GUI mode in JMETER

I tried to run the following script:
import org.apache.commons.io.FileUtils; // necessary import
int lines = FileUtils.readLines(new File("${testPlanFileDir}/csv/test_smtp_save.csv")).size() - 1; // get lines count
vars.put("lines", String.valueOf(lines)); // store the count into "lines" variable
To get the number of lines in my csv, so that I can execute a loop according to the number of lines in the CSV file.
The script above runs perfectly if I run from GUI mode, but when I run from terminal then it throws following error.
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval
Sourced file: inline evaluation of:
``import org.apache.commons.io.FileUtils; // necessary import int lines = FileUtil . . . ''
: Typed variable declaration : Method Invocation FileUtils.readLines
How do you get this ${testPlanFileDir} variable value? Apart from it the code looks good.
If you want to have more relevant error message you can try putting your code into the try block:
import org.apache.commons.io.FileUtils;
try {
int lines = FileUtils.readLines(new File("${testPlanFileDir}/csv/test_smtp_save.csv")).size() - 1;
vars.put("lines", String.valueOf(lines));
}
catch (Throwable ex) {
log.error("Error in Beanshell", ex);
throw ex;
}
And look into jmeter.log file - it will contain the "usual" stacktrace.
Alternatively you can add debug() command to the very beginning of your Beanshell script - it will toggle debugging output to stdout
See How to Use BeanShell: JMeter's Favorite Built-in Component for more Beanshell-related tips and tricks
Replace ${testPlanFileDir} by:
vars.get("testPlanFileDir")
You should avoid using Beanshell in favor of JSR223+Groovy+Cache which is embedded in JMeter 3.0, see:
http://jmeter.apache.org/changes.html
https://www.ubik-ingenierie.com/blog/jmeter_performance_tuning_tips/
I used this to get the current directory of .jmx file.
Declared varaible TestPlanFileDir as;
${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}

how to set path, when repo is downloaded using gradle

I am using gradle to download the selenium chrome driver from maven
webtestsCompile 'org.seleniumhq.selenium:selenium-chrome-driver:2.32.0'
I am trying to use this directly and I see that I get this error :
Caused by:
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
I have looked up a couple of questions from stack-overflow and other places it requires me to set the value of the property webdriver.chrome.driver to the location where I have downloaded with some-thing like this :
System.setProperty("webdriver.chrome.driver", "path to chrome-driver");
I am wondering what is the best way to go about this ?
EDIT 1:
I verified the java.class.path a snippet of this path looks like this :
/home/bhavya/.gradle/caches/artifacts-26/filestore/org.seleniumhq.selenium/selenium-chrome-driver/2.32.0/jar/14a4e8e32a4129c682c67381f5d7bf11f2327e1/selenium-chrome-driver-2.32.0.jar
This looks like the selenium-chrome-driver is present in the java.class.path.
Edit 2 :
I would want the chrome driver to work irrespective of the operating system that I am using, currently I am on a ubuntu box but a lot of this will get tested on a windows box. When I hard coded the value of the webdriver.chrome.driver to the value in EDIT 1, I am facing the following issue :
java.lang.IllegalStateException: The driver is not executable: /home/bhavya/.gradle/caches/artifacts-26/filestore/org.seleniumhq.selenium/selenium-chrome-driver/2.32.0/jar/14a4e8e32a4129c682c67381f5d7bf11f2327e1/selenium-chrome-driver-2.32.0.jar
Edit 3 :
Task within which I am running the test suite --
task webs(type: Test, dependsOn: updateNodeModules) {
testClassesDir = sourceSets.webtests.output.classesDir
classpath = sourceSets.webtests.runtimeClasspath
def javaHomeBin = new File(System.getProperty("java.home"), "bin");
def javaExec = new File(javaHomeBin, "java").getAbsolutePath();
systemProperties['jar.path'] = jar.archivePath
if(project.hasProperty('url')){
println" url passed as variable is $url"
systemProperties["selenium.webdriver.url"] = "$url"
}
systemProperties["selenium.webbrowser.type"] = "firefox"
if(project.hasProperty('browser')){
println "the browser passed is $browser"
systemProperties["selenium.webbrowser.type"] = "$browser"
}
include '**/UserEditControllerWebTest.class'
doFirst {
println " iterator is $it"
def chrome=configurations.testRuntime.find {
it.name.contains("selenium-chrome-driver")
}.path
println " chrome driver path is $chrome"
systemProperties["webdriver.chrome.driver"]= "$chrome"
}
}
Assuming that you need to set this system property for your tests, you can do something like:
test.doFirst {
systemProperty "webdriver.chrome.driver",
classpath.find {
it.name.contains("selenium-chrome-driver")
}.path
}

h2 with custom java alias and javac compiler issues in multi process environment

H2 database with custom function alias defined as:
create alias to_date as $$
java.util.Date toDate(java.lang.String dateString, java.lang.String pattern) {
try {
return new java.text.SimpleDateFormat(javaPattern).parse(dateString);
} catch(java.text.ParseException e) {
throw new java.lang.RuntimeException(e);
}
}
$$;
H2 initialized as:
jdbc:h2:mem:testdb;INIT=runscript from 'classpath:create_alias.sql
This is used in tests, executed for multiple projects concurrently on a Jenkins instance. Sometimes such tests would fail with following error:
Could not get JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "javac: file not found: org/h2/dynamic/TO_DATE.java
Usage: javac <options> <source files>
use -help for a list of possible options
"; SQL statement:
create alias to_date as $$
java.util.Date toDate(java.lang.String dateString, java.lang.String pattern) {
....
My guess is that org.h2.util.SourceCompiler is assuming that there is only one instance of h2 running at the time and writes the generated Java source to 'java.io.tmpdir', which is shared among all processes running under same account. I propose following fix:
Index: SourceCompiler.java
===================================================================
--- SourceCompiler.java (revision 5086)
+++ SourceCompiler.java (working copy)
## -40,7 +40,15 ##
*/
final HashMap<String, Class<?>> compiled = New.hashMap();
- private final String compileDir = Utils.getProperty("java.io.tmpdir", ".");
+ private final String compileDir;
+
+ {
+ // use random folder under java.io.tmpdir so multiple h2 could compile at the same time
+ // without overwriting each other files
+ File tmp = File.createTempFile("h2tmp", ".tmp");
+ tmp.mkdir();
+ compileDir = tmp.getAbsolutePath();
+ }
static {
Class<?> clazz;
Should I open the support ticket or there are workarounds for this issue?
You can use javax.tools.JavaCompiler API and provide your own implementation for in-memory JavaFileManager to completely avoid creating those temp files.
BTW, Janino also support javax.tools.JavaCompiler API.
I had the same problem running multiple Jenkins executors and having Arquillian/Wildfly/H2 integration tests configuration. I found a workaround by setting java.io.tmpdir property to the build directory in the test standalone.xml.

Resources