0

I want to run Java file from Golang code.

Java File: Only for testing purpose.

public class AuthBridge {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        try {
            if(args.length != 3){
                return;
            }
            
            String keyRecived = args[0];
            String pubKey = args[1];
            String mode = args[2];
            System.out.println("Here" + keyRecived + " " + pubKey + " " + mode);
            if(new String(mode).equals("decrypt")){
                String response = new AuthBridge().Decrypt(keyRecived, pubKey);
                System.out.println(response);
            }else{
                return;
            }
               
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }
    }

    public String Decrypt(String input, String key){
        return "Testing";
    }
  
}

Golang Code Test Function only


import (
    "fmt"
    "os/exec"
    "testing"
)

func TestEncryption(b *testing.T) {
    cmd := exec.Command("java", "AuthBridge", "KeyRecived", "PublicKey", "decrypt")
    fmt.Println("cmd args:", cmd.Args)
    output, _ := cmd.CombinedOutput()
    fmt.Println("Output:", string(output))
}

Problem: When I run the go test file it shows me error

Output shows me error of class not found exception.

cmd args: [java AuthBridge KeyRecived PublicKey decrypt]
Output: Error: Could not find or load main class AuthBridge
Caused by: java.lang.ClassNotFoundException: AuthBridge

Anyone please help me with this? Thanks

Black_Dreams
  • 572
  • 1
  • 5
  • 11
  • You probably require a -classpath option. Your Go code is telling Java to run a class file without saying where it is. – user15187356 Apr 10 '21 at 14:12
  • `.class` file is already in same folder. – Black_Dreams Apr 10 '21 at 14:16
  • 'same' as what? Same as the current working directory of the running process, or same as the Go source file. It needs to be the former. – user15187356 Apr 10 '21 at 14:18
  • I don't get the error with the same code after running `javac AuthBridge.java`. When I delete `AuthBridge.class` I do get this error though. So I also agree that something with the classfile location should be done. If you want to run the java command in a different directory, you might also be interested in setting `cmd.Dir`. Note that the command is not necessarily run in the same directory as the test file – xarantolus Apr 10 '21 at 14:21
  • All the files are in main folder `AuthBridge.Java` and `AuthBridge.class` but don't know why this error comes ? – Black_Dreams Apr 11 '21 at 02:22
  • The Java SDK version is not mentioned. This [SO question](https://stackoverflow.com/questions/1279542/how-to-execute-a-java-class-from-the-command-line) might help. – Constantin Konstantinidis Apr 11 '21 at 14:48

0 Answers0