How to use the HWUT unit test tool with java files - java

I've been using the HWUT unit test tool with C and python and now I'm trying it with Java. In python I can tell HWUT to run all .py files with python if I specify a "hwut-info.dat" file as
Some title
----------------------
python *.py
But for Java I can't do that, because java expects the file names without extension. The java compiler shall consider the '*.java' files but it does
expect the file stem as input, i.e. java FileStem in order to treat FileStem.java.

Later HWUT versions (> 0.28.0) will provide some sophisticated functionality to
pass information about path names, i.e. in those (at the time of this writing)
'future versions' the usage of an extension-less java file can be specified as
java -cp mypackages:. {{file.java%}}
For the time being, you need a script to run your test, such as 'runjava.sh':
#! /usr/bin/env bash
java -cp ../../package:. $(basename ${1%.*}) ${#:2}
It calls the java interpreter, cuts the extension from the filename and passes
all remaining arguments to the file to be executed. In your 'hwut-info.dat'
file you need to specify:
My title
--------------------------------------------------------
bash ./runjava.sh *.class
This lets HWUT search for *.class files in the current directory. The
'runjava.sh', though, omits the extension and calls 'java' with the file stem.
Inside your Java test application you reflect on the command line like:
public class Mine {
public static void main(String[] args) {
if( args.length >= 1 && args[0].equals("--hwut-info") ) {
System.out.println("Title ...");
...
}
}
...
}

Related

can't run .jar file /java.jar: line 1: public: command not found

I have Ubuntu 16.04.
and downloaded a JDK with a tar.gz file extension and followed This wikihow to install it.
When I try to run a .jar game (like Minecraft) It works successfully, and I have netbeans downloaded that is connected to the same JDK and compiled some programs that i can run in terminal, But When I type :
./Hello_world.jar
Which is :
package main;
public class project {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
I get this output :
./Hello_world.jar: line 1: $'PK\003\004': command not found
./Hello_world.jar: line 2: $'\b.\020oK': command not found
./Hello_world.jar: line 3: syntax error near unexpected token `)'
./Hello_world.jar: line 3:-oK�}����META-INF/MANIFEST.MFM�1
�0��#��uHh Q���X� ��N1�Ҧ$)��7�(�p�ww
�A����|��}�1���ή�n��p<�Рŗ��:CpN~�s�ν�˚�3��%
��)���goPK`
Simple: JAR files aren't executables. You can only invoke binaries/scripts by telling your shell to ./command.
They are archives that contain compiled Java classes.
Thus you use them like:
java -jar somejar.jar
This starts a java virtual machine, and tells it to open the given JAR file. The JVM will then figure the "main" class to run from the meta information that can be backed into the JAR file - to then "run" that main class.
( assuming that the corresponding JAR file has been built in a why that allows running it like this. see here for details on how you enable this "easy way" of running a JAR file )
And just in case: with some scripting magic, you actually can turn a JAR file into a "binary", see here for example.

Ensuring files are available to the JVM

I'm trying to install TensorFlow for Java on Windows 10 using this Article
. I followed the steps carefully but the windows commands didn't work with me so I decided to do it manually.
The first command is to make the .jar part of the classpath and I did it manually
but the second step was to ensure that the following two files are available to the JVM: the .jar file and the extracted JNI library
but I don't know how to do that manually
The code:
package securityapplication;
import org.tensorflow.TensorFlow;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class SecurityApplication {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
could someone help? cuz my program that uses TensorFlow still have the following error
The text in the image is :
Exception in thread "main" java.lang.UnsatisfiedLinkError: Cannot find TensorFlow native library for OS: windows, architecture: x86. See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md for possible solutions (such as building the library from source). Additional information on attempts to find the native library can be obtained by adding org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.TensorFlow.init(TensorFlow.java:36)
at org.tensorflow.TensorFlow.<clinit>(TensorFlow.java:40)
at org.tensorflow.Graph.<clinit>(Graph.java:194)
at securityapplication.SecurityApplication.main(SecurityApplication.java:15) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
The result after running the first command in cmd:
The result after running the second command in Windows PowerShell:
Any suggestions?!
Thank you
The first command failure (javac) suggests that the javac command is not in your PATH environment variables. See for example, this StackOverflow question
For the second command failure, I believe the space after -D is what is causing you trouble as Holger suggested.
IDEs like Eclipse and others also provide a means to set the java.library.path property for the JVM (see this StackOverflow answer for example).
Background: TensorFlow for Java consists of a Java library (packaged in a .jar file) and a native library (.dll on Windows, distributed in a .zip file). You need to ensure that the .jar file is in the classpath and the directory containing the .dll is in included in the java.library.path of the JVM when executing a program.
Hope that helps.

How can I embed java code into batch script?Is it possible to create .java/.bat hybrid?

While there are some techniques that allows you to create the perfect (and not so perfect) batch file hybrids with some 'native' windows script languages.
What a 'perfect' hybrid should look like:
The embedded code must be usable as it is and you should be capable
to copy-pasted it in any other editor/IDE you want. There should be
no endless echoes to temp files and weird escape sequences.(rather
possible for every language that support multi-line comments).
No 'poisonous' prints of error messages (e.g. /* will print an error
in command prompt despite the execution of the batch will continue
on the next line)
No temporary files.With the exception of compiled binary files which
is unavoidable for the languages that does not have an interpreter.
Is it possible to create the 'perfect' java/batch hybrid?
The answer is almost.
The main impediment is that the all compilers I know are very strict about the file extensions and will refuse to compile any file that has no .java extension.
As any command in batch files starting with # will be not displayed we can use the java annotations to silence the error message that comes from the java comment (should be saved with .bat extension):
#Deprecated /* >nul 2>&1
:: self compiled java/.bat hybrid
::
:: deprecated is the only one annotation that can be used outside the class definition
:: and is needed for 'mute' start of multi-line java comment
:: that will be not printed by the batch file.
:: though it still creates two files - the .class and the .java
:: it still allows you to embed both batch and java code into one file
#echo off
setlocal
java -version >nul 2>&1 || (
echo java not found
exit /b 1
)
::find class name
::can be different than the script name
for /f "usebackq tokens=3 delims=} " %%c in (`type %~f0 ^|find /i "public class"^|findstr /v "for /f"`) do (
set "javaFile=%%c"
goto :skip
)
:skip
copy "%~f0" "%javaFile%.java" >nul 2>&1
javac "%javaFile%.java"
java "%javaFile%"
::optional
::del %javaFile%.* >nul 2>&1
end local
exit /b 0
*******/
public class TestClass
{
public static void main(String args[])
{
System.out.println("selfcompiled .bat/.java hybrid");
}
}
The example above covers points 1. and 2. but of course there's still need of creation of .java file.Still copying is faster than echoing java content line by line.
One step further (or half step) - making a .java extension to act like .bat (or almost)
Lets say you don't the like the part in the code that finds the java class name and the self-copy code.
You can make the .java extension to act like .bat file.Or almost - the %0 will be lost and the file name will be stored in %1.
For that purpose you need to call this batch file with admin permissions:
#echo off
:: requires Admin permissions
:: allows a files with .JAVA (in this case ) extension to act like .bat/.cmd files.
:: Will create a 'caller.bat' asociated with the extension
:: which will create a temp .bat file on each call (you can consider this as cheating)
:: and will call it.
:: Have on mind that the %0 argument will be lost.
rem :: "installing" a caller.
if not exist "c:\javaCaller.bat" (
echo #echo off
echo copy "%%~nx1" "%%temp%%\%%~nx1.bat" /Y ^>nul
echo "%%temp%%\%%~nx1.bat" %%*
) > c:\javaCaller.bat
rem :: associating file extension
assoc .java=javafile
ftype javafile=c:\javaCaller "%%1" %%*
Then the self-compiled .java file will look like this (should be saved with .java extension):
#Deprecated /* >nul 2>&1
:: requires ran javaExtInstaller.bat
:: https://github.com/npocmaka/batch.scripts/blob/master/Java/javaExtInstaller.bat
::
:: self compiled java/.bat hybrid
::
:: deprecated is the only one annotation that can be used outside the class definition
:: and is needed for 'mute' start of multi-line java comment
:: that will be not printed by the batch file.
:: allows you to embed both batch and java code into one file
#echo off
setlocal
java -version >nul 2>&1 || (
echo java not found
exit /b 1
)
if not exist "%~n1.class" javac "%~nx1"
:: to compile the class every time use:
:: javac "%~nx1"
java "%~n1"
endlocal
exit /b 0
*******/
public class TestClass
{
public static void main(String args[])
{
System.out.println("selfcompiled .bat/.java hybrid");
}
}
there still will have a creation of temp .bat file by the javaCaller.bat but it will be not 'visible' and batch part is much shorter.
In the examples there are no packages as the only single java file is used .Packages will make only the example harder to understand.
Didn't you saw my DosTips post on Alternate Data Streams? This method have all the advantages you want for perfect hybrid scripts because the non-Batch code is stored in its own space (alternate stream), so it don't requires a single additional character! The code can be edited with Windows Notepad. The "only" problem is if the java compiler was designed to recognize the Alternate Data Stream. I successully tested this method with VBS, JScript and PowerShell, but unfortunately I have not a java compiler installed...
However, the test to check if this method work with your java compiler is very simple. Copy the code below and create BatchJavaTest.bat file with it:
#echo off
rem Compile the java code stored in this file as an ADS with name "TestClass.java"
javac "%~F0:TestClass.java"
java "TestClass"
Now we need to create the ADS with the java code. To do that, enter the following in the command-line:
notepad BatchJavaTest.bat:TestClass.java
When Notepad open, paste the following on it:
public class TestClass
{
public static void main(String args[])
{
System.out.println("selfcompiled .bat/.java hybrid from an ADS!");
}
}
Save this file and test the Batch one. That is it!
Please, report the result!
PS - This program must be tested in a NTFS disk in order for it to work...

Getting java.lang.NoClassDefFoundError when trying the execute a java.class

I created the following class located in the MainJPrint.java file
import com.XXXXX.pdfPrint.PDFPrint;
public class MainJPrint
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
print(".....");
}
public static String print (final String url)
{
Object rc = AccessController.doPrivileged(new java.security.PrivilegedAction()
{
public Object run()
{
...
}
}
}
}
In the same folder I have a jar archive jPrint.jar
I compile the class using the following command
>javac -classpath jPrint.jar MainJPrint.java
When I'm trying to execute resulted class file, I get this error:
>java MainJPrint
java.lang.NoClassDefFoundError: com/XXXXX/pdfPrint/PDFPrint
If I uncomment the Hello World line and comment the next line, the program runs fine.
I'm using j2sdk1.4.2 installed at C:\j2sdk1.4.2.
I do also have installed other java versions (at C:\Program Files\Java: jre 1.6.0_01, jre 1.6.0_02, j2re1.4.2, jre6, jre7, jdk1.7.0_03)
The PATH variable contains the C:\j2sdk1.4.2\bin path, however I think the java.exe is loaded from the upper version, but it shouldn't matter and I can call it like
>C:\j2sdk1.4.2\bin\java.exe MainJPrint
jPrint.jar is a third party archive and I need to create an applet which exposes a method so I can call it with javascript. I'm not a java developer, I'm having some little troubles and I'm really on an end here.
I tried other options like:
>java MainJPrint -cp .
>java MainJPrint -cp jPrint.jar
So how can I execute that class file which uses a class located in a separate archive?
To execute a class that depends on external JARs, you need to specify all elements of the classpath on the command line.
If you don't specify a classpath, Java automatically uses . (the current directory), which is why, if MainJPrint didn't depend on jPrint.jar, your invocation java MainJPrint would have worked.
But when you specify -cp jPrint.jar, Java does NOT automatically add the current directory to the classpath, which means that it then cannot find MainJPrint. You need to specify both. On Mac/*nix, the following invocation should work:
java -cp jPrint.jar:. MainJPrint
Or on Windows:
java -cp jPrint.jar;. MainJPrint

execute a java program through batch script

I have a java class "Test.java" which contains certain code.
public class Test {
public static void main(String[] args) throws Exception {
testMount();
}
public static void testMount() throws Exception {
System.out.println(System.getProperty("os.name"));
//Windows
String volumeToMount = "\\\\?\\Volume{****-****-******-********}\\";
String mountPoint = "C:\\temp\\";
mountFileSystem("", "", volumeToMount, mountPoint); //This carries out the operation
}
}
I have already compiled the code in Linux Operating System. I want to run the compiled code through a batch script ( .bat file). How do i do that? What is the syntax for that? If i have to add some external jars, where and how do I insert them in the syntax within the .bat file?
here is an example of bat file for executing a java code from the jar with external jars:
#echo off
if "X%JAVA_HOME%" == "X" goto setjavahome
goto setup
:setjavahome
rem #### MODIFY ##########
set JAVA_HOME=c:\program files\javasoft\jre\1.2
rem #######################
:setup
set JNDI_LIB=lib\ldap.jar;lib\jndi.jar;lib\providerutil.jar;lib\ldapbp.jar
set JSSE_LIB=lib\jsse.jar;lib\jnet.jar;lib\jcert.jar
set COMMON=.;%JNDI_LIB%;%JSSE_LIB%
set EXEC=browser.jar lbe.ui.BrowserApp
set CMD="%JAVA_HOME%\bin\java" -cp %COMMON%;%EXEC%
echo %CMD%
%CMD%
.bat is for Windows; try to compile your Java codes in Windows to EXE (with your external libraries, as suggested by galchen), and add your EXE name along with relative / absolute path to the batch file.
For example, the output EXE is named as test.exe, the batch file should contain:
START C:\PATH\TO\YOUR\EXE\test.exe
Advantage of compiling to EXE is mainly for performance.

Categories

Resources