Generate Java Code with Roaster

Roaster is a library that allows easy parsing and formatting of java source files. Roaster introduces a fluent interface to manipulate Java source files, like adding fields, methods, annotations and so on.

Below is one example:

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.JavaClassSource;

public class POJOGenerator {
	
	public static void main(String[] args) throws IOException {
		//create an empty instance
		final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
		
		//set the package name, and Java class name
		javaClass.setPackage("demo.JavaCodeGenerator.roaster").setName("PersonPojo");

		//add interface, can be one or more		
		javaClass.addInterface(Serializable.class);
		
		//extend an abstract class
		javaClass.extendSuperType(Date.class);
		
		//add a Long/private/static/final Long field, with value '-1L' 
		javaClass.addField()
		  .setName("serialVersionUID")
		  .setType("long")
		  .setLiteralInitializer("-1L")
		  .setPrivate().setStatic(true).setFinal(true);

		//add a String property, setter/getter functions are generated
		javaClass.addProperty(String.class, "firstName");
		//add an Integer property, final and not exposed
		javaClass.addProperty(Integer.class, "id").setMutable(true).setAccessible(false);
		//add a new property with class 'demo.JavaCodeGenerator.App', an Import line is added
		javaClass.addProperty("demo.JavaCodeGenerator.App", "app");

		//add a public constructor function, 
		javaClass.addMethod()
		  .setConstructor(true)
		  .setPublic()
		  .setBody("this.id = id;")
		  .addParameter(Integer.class, "id");
				
		//add another private function
		javaClass.addMethod()
		.setName("increaseId")
		.setPrivate()
		.setBody("this.id += step;")
		.addParameter("int", "step");
		
		//check if any syntax error
		if(javaClass.hasSyntaxErrors()){
			System.err.println("SyntaxError: "+javaClass.getSyntaxErrors());
		}
		
		//output to file
		String filePath = "src/main/java/demo/JavaCodeGenerator/roaster/PersonPojo.java";
		FileUtils.forceMkdir(new File("src/main/java/demo/JavaCodeGenerator/roaster"));
		FileUtils.writeStringToFile(new File(filePath), javaClass.toString());
	}

}

The output class looks as below:

package demo.JavaCodeGenerator.roaster;

import java.io.Serializable;
import java.util.Date;
import demo.JavaCodeGenerator.App;

public class PersonPojo extends Date implements Serializable {

    private static final long serialVersionUID = -1L;
    private String firstName;
    private Integer id;
    private App app;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public App getApp() {
        return app;
    }

    public void setApp(App app) {
        this.app = app;
    }

    public PersonPojo(java.lang.Integer id) {
        this.id = id;
    }

    private void increaseId(int step) {
        this.id += step;
    }
}

Execute a system command in Java

Execute a system command – Rosetta Code.

Java

Works withJava version 1.5+
import java.util.Scanner;
import java.io.*;
 
public class Program {
    public static void main(String[] args) {    	
    	try {
    		Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
    		Scanner sc = new Scanner(p.getInputStream());    		
    		while (sc.hasNext()) System.out.println(sc.nextLine());
    	}
    	catch (IOException e) {
    		System.out.println(e.getMessage());
    	}
    }
}
Works withJava version 1.4+

There are two ways to run system commands. The simple way, which will hang the JVM (I would be interested in some kind of reason). — this happens because the the inputStream buffer fills up and blocks until it gets read. Moving your .waitFor after reading the InputStream would fix your issue (as long as your error stream doesn’t fill up)

import java.io.IOException;
import java.io.InputStream;
 
public class MainEntry {
    public static void main(String[] args) {
        executeCmd("ls -oa");
    }
 
    private static void executeCmd(String string) {
        InputStream pipedOut = null;
        try {
            Process aProcess = Runtime.getRuntime().exec(string);
            aProcess.waitFor();
 
            pipedOut = aProcess.getInputStream();
            byte buffer[] = new byte[2048];
            int read = pipedOut.read(buffer);
            // Replace following code with your intends processing tools
            while(read >= 0) {
                System.out.write(buffer, 0, read);
 
                read = pipedOut.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            if(pipedOut != null) {
                try {
                    pipedOut.close();
                } catch (IOException e) {
                }
            }
        }
    }
 
 
}

And the right way, which uses threading to read the InputStream given by the process.

import java.io.IOException;
import java.io.InputStream;
 
public class MainEntry {
    public static void main(String[] args) {
        // the command to execute
        executeCmd("ls -oa");
    }
 
    private static void executeCmd(String string) {
        InputStream pipedOut = null;
        try {
            Process aProcess = Runtime.getRuntime().exec(string);
 
            // These two thread shall stop by themself when the process end
            Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));
            Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));
 
            pipeThread.start();
            errorThread.start();
 
            aProcess.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}
 
//Replace the following thread with your intends reader
class StreamGobber implements Runnable {
 
    private InputStream Pipe;
 
    public StreamGobber(InputStream pipe) {
        if(pipe == null) {
            throw new NullPointerException("bad pipe");
        }
        Pipe = pipe;
    }
 
    public void run() {
        try {
            byte buffer[] = new byte[2048];
 
            int read = Pipe.read(buffer);
            while(read >= 0) {
                System.out.write(buffer, 0, read);
 
                read = Pipe.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(Pipe != null) {
                try {
                    Pipe.close();
                } catch (IOException e) {
                }
            }
        }
    }
}