'How to add jenkins node via Java program

I must manage Jenkins node via a Java program. I found this example but when I launch it do nothing, no error e no result on Jenkins interface:

    @Test
public void test() {
    //fail("Not yet implemented");
    //Main.main(new String[]{"-version"});
    //Main.main(new String[]{"-s", "http://localhost:8080", "-auth", "admin:password", "list-plugins"});
    //Main.main(new String[]{"-ssh"});
    StringBuilder str = new StringBuilder("<slave>");
    str.append("  <name>nodo-test</name>");
    str.append("  <description>test</description>");
    str.append("  <remoteFS>/home/build/jenkins-node</remoteFS>");
    str.append("  <numExecutors>1</numExecutors>");
    str.append("  <mode>NORMAL</mode>");
    str.append("  <retentionStrategy class=\"hudson.slaves.RetentionStrategy$Always\"/>");
    str.append("  <launcher class=\"hudson.plugins.sshslaves.SSHLauncher\" plugin=\"[email protected]\">");
    str.append("    <host>nodo-test</host>");
    str.append("    <port>22</port>");
    str.append("    <credentialsId>xxxxxx</credentialsId>");
    str.append("  </launcher>");
    str.append("  <label>build</label>");
    str.append("  <nodeProperties/>");
    str.append("  <userId>Marco</userId>");
    str.append("</slave>");
    //Main.main(new String[]{"-s", "http://localhost:8080", "-auth", "admin:password", "create-node", str.toString()});
    
    Process process;
    try {
        process = Runtime.getRuntime().exec("java -jar ./jenkins-cli.jar -s http://localhost:8080/jenkins create-node nodo-test");
        OutputStream stdin = process.getOutputStream();
        InputStream stdout = process.getInputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        writer.write(str.toString());
        writer.flush(); 
        writer.close();
        System.out.println("End runtime");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    System.out.println("End");
}

What is wrong ? Is there a method to do the same thing without use jenkins-cli ? Thanks for your support.

UPDATE: the code, in effect, show error on "flush": "Pipe is being closed". FYI I'm trying to add a node to a Jenkins server running in a docker image "localhost:8080".



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source