groovy file call in java - java

i want to do groovy file call in java
my source:
ex.groovy
def swingBuilder = new SwingBuilder()
swingBuilder.edt {
frame(title: 'ex', size: [200, 150], show: true) {
borderLayout(vgap: 5)
panel(constraints: BorderLayout.CENTER, border: emptyBorder(10)) {
button "a"
button "b"
}
}
}
ex1.java
class ex1{
public static void main(String[] args)throws Exception {
File sourceFile = new File("mypath/ex.groovy");
ClassLoader clo = jview.class.getClassLoader();
GroovyClassLoader classLoader = new GroovyClassLoader(clo);
Class groovy = classLoader.parseClass(sourceFile);
GroovyObject groovyob = (GroovyObject)groovy.newInstance();
groovyob.invokeMethod("run", null);
}
}
how do i?
help please..

You could use GroovyShell (if required with Binding)
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class ex1 {
public static void main(String[] args) {
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("mypath/ex.groovy");
}

Related

How do I create a class with bcel and bcel-util which passes the verifier?

I have a simple class that I'm trying to re-create programatically with BCEL library.
public class HelloWorld {
public static void main(String[] args) {
switch (args[0]) {
case "Hello":
System.out.println("Hello World");
break;
default:
break;
}
}
}
I have a build.gradle that looks like this:
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.apache.bcel:bcel:6.6.1'
implementation 'org.plumelib:bcel-util:1.1.16'
}
First thing I do is generate a class generator class with the help of the main class org.apache.bcel.util.BCELifier with argument HelloWorld. It prints source code to stdout.
The generated class HelloWorldCreator is also a main that I can run and it creates a HelloWorld.class. When I run this new HelloWorld class, I have this verifier error:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.VerifyError: Expecting a stackmap frame at branch target 51
Exception Details:
Location:
HelloWorld.main([Ljava/lang/String;)V #8: lookupswitch
Reason:
Expected stackmap frame at this location.
Bytecode:
0x0000000: 2a03 3259 4cb6 0014 ab00 0000 0000 002b
0x0000010: 0000 0001 0426 28b2 0000 0014 2b12 16b6
0x0000020: 001a 9a00 06a7 000e b200 2012 22b6 0028
0x0000030: a700 03b1
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:650)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:632)
After a bit of research, I found out there is side library bcel-util that makes up for lack of stackmap frames in class generated by bcel.
BCEL ought to automatically build and maintain the StackMapTable in a
manner similar to the LineNumberTable and the LocalVariableTable.
However, for historical reasons, it does not.
http://plumelib.org/bcel-util/api/org/plumelib/bcelutil/InstructionListUtils.html
Trying to follow the same piece of code indicated on this link, I came up with this code :
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionConst;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LOOKUPSWITCH;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.plumelib.bcelutil.InstructionListUtils;
public class HelloWorldCreator extends InstructionListUtils {
private InstructionFactory _factory;
private ConstantPoolGen _cp;
private ClassGen _cg;
public HelloWorldCreator() {
_cg = new ClassGen("HelloWorld", "java.lang.Object", "HelloWorld.java", Const.ACC_PUBLIC | Const.ACC_SUPER,
new String[] {});
_cg.setMajor(52);
_cg.setMinor(0);
_cp = _cg.getConstantPool();
_factory = new InstructionFactory(_cg, _cp);
}
void modifyClass(JavaClass jc) {
ClassGen cg = new ClassGen(jc);
String classname = cg.getClassName();
// save ConstantPool for use by StackMapUtils
pool = cg.getConstantPool();
for (Method m : cg.getMethods()) {
try {
MethodGen mg = new MethodGen(m, classname, pool);
// Get the instruction list and skip methods with no instructions
InstructionList il = mg.getInstructionList();
if (il == null) {
continue;
}
// Get existing StackMapTable (if present)
set_current_stack_map_table(mg, cg.getMajor());
fix_local_variable_table(mg);
// Create a map of Uninitialized_variable_info offsets to
// InstructionHandles.
build_unitialized_NEW_map(il);
// Update the Uninitialized_variable_info offsets before
// we write out the new StackMapTable.
update_uninitialized_NEW_offsets(il);
create_new_stack_map_attribute(mg);
// Update the instruction list
mg.setInstructionList(il);
mg.update();
// Update the max stack
mg.setMaxStack();
mg.setMaxLocals();
mg.update();
remove_local_variable_type_table(mg);
// Update the method in the class
cg.replaceMethod(m, mg.getMethod());
} catch (Throwable t) {
throw new Error("Unexpected error processing " + classname + "." + m.getName(), t);
}
}
}
public void create(OutputStream out) throws IOException {
createMethod_0();
createMethod_1();
JavaClass jc = _cg.getJavaClass();
modifyClass(jc);
jc.dump(out);
}
private void createMethod_0() {
InstructionList il = new InstructionList();
MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>",
"HelloWorld", il, _cp);
il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
il.append(InstructionFactory.createReturn(Type.VOID));
method.setMaxStack();
method.setMaxLocals();
_cg.addMethod(method.getMethod());
il.dispose();
}
private void createMethod_1() {
InstructionList il = new InstructionList();
MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID,
new Type[] { new ArrayType(Type.STRING, 1) }, new String[] { "arg0" }, "main", "HelloWorld", il, _cp);
il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
il.append(new PUSH(_cp, 0));
il.append(InstructionConst.AALOAD);
il.append(InstructionConst.DUP);
il.append(InstructionFactory.createStore(Type.OBJECT, 1));
il.append(_factory.createInvoke("java.lang.String", "hashCode", Type.INT, Type.NO_ARGS, Const.INVOKEVIRTUAL));
Select lookupswitch_8 = new LOOKUPSWITCH(new int[] { 69609650 }, new InstructionHandle[] { null }, null);
il.append(lookupswitch_8);
InstructionHandle ih_28 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
il.append(new PUSH(_cp, "Hello"));
il.append(_factory.createInvoke("java.lang.String", "equals", Type.BOOLEAN, new Type[] { Type.OBJECT },
Const.INVOKEVIRTUAL));
BranchInstruction ifne_34 = InstructionFactory.createBranchInstruction(Const.IFNE, null);
il.append(ifne_34);
BranchInstruction goto_37 = InstructionFactory.createBranchInstruction(Const.GOTO, null);
il.append(goto_37);
InstructionHandle ih_40 = il.append(_factory.createFieldAccess("java.lang.System", "out",
new ObjectType("java.io.PrintStream"), Const.GETSTATIC));
il.append(new PUSH(_cp, "Hello World"));
il.append(_factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING },
Const.INVOKEVIRTUAL));
BranchInstruction goto_48 = InstructionFactory.createBranchInstruction(Const.GOTO, null);
il.append(goto_48);
InstructionHandle ih_51 = il.append(InstructionFactory.createReturn(Type.VOID));
lookupswitch_8.setTarget(ih_51);
lookupswitch_8.setTarget(0, ih_28);
ifne_34.setTarget(ih_40);
goto_37.setTarget(ih_51);
goto_48.setTarget(ih_51);
method.setMaxStack();
method.setMaxLocals();
_cg.addMethod(method.getMethod());
il.dispose();
}
public static void main(String[] args) throws Exception {
HelloWorldCreator creator = new HelloWorldCreator();
creator.create(new FileOutputStream("HelloWorld.class"));
}
}
However, when running this new updated HelloWorldCreator, I still have the same verifier issue.

How to make CharSink respect file permissions?

I would expect exception to be thrown in this code at line: charSink.write("hi world"); since the file is set to be non writable. But this code executes without any exceptions. How to make CharSink respect file permissions?
public class CharSinkWritingNonWritableFile {
public static void main(String[] args) throws Exception {
final File file = getNewFile();
file.setWritable(false, false);
val charSink = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
file.setWritable(false, false);
charSink.write("hi world");
Files.readLines(file, Charsets.UTF_8).forEach(line -> {
System.out.println(line);
});
}
private static File getNewFile() {
final File file = new File("/tmp/hi-world");
if (file.exists()) {
file.delete();
}
return file;
}
}
Edit:
OS: MacOS 12.4

What's the best way to execute a .jar in java code

I need develop a "launcher" for a java application. This launcher need be able to:
check if main application is up-to-date;
if not, download a update;
run this application and self terminate.
Something like this:
public final class Launcher {
public static void main(String[] args) throws Exception {
String jarName = args[0];
if (jarHasUpdate(jarName)
refreshJar(jarName);
executeJar(jarName);
}
}
What better way of develop the step 3?
I'm trying 2 distinct ways:
1- Run another instance of Java
With the code:
Runtime.getRuntime().exec("java -jar mainApp.jar");
Problem: the launcher still running until mainApp have finished.
2- Using ClassLoader to load .jar at runtime
Like this:
public final class Launcher {
#SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Invalid number of arguments.");
System.exit(1);
}
Refresh.refreshFile(args[0]);
// args[0] .jar name
// args[1] class with main function
File file = new File(args[0]);
try (URLClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL() });) {
Class cls = cl.loadClass(args[1]);
Method method = cls.getDeclaredMethod("main", new Class[] { String[].class });
Object params = new String[] {};
method.invoke(cls, params);
}
}
}
Problem: if "mainApp.jar" has dependencies, this isn't loaded.

JADE_mulli agent system

I can't deploy the agent in JADE implemented in Java, any alternatives ?
package package1;
import jade.core.Agent;
public class JadePFE extends Agent {
#Override
protected void setup() {
System.out.println("Hello agent 007");
}
}
I think you mean to start the JADE platform, this is the contents of the my main method which launches the whole thing. Hope it helps
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] args1 = new String[3];
args1[0] = "-gui";
args1[1] = "-agents";
args1[2] = "agentName:package.agentClassName";
jade.Boot.main(args1);
}
}
If I have understand, you want know how deploy an agent (and maybe start the platform) directly from the code.
I show you how:
import jade.core.Runtime;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.*;
public class Start {
public static void main(String args[]) throws InterruptedException, StaleProxyException {
// Get a hold on JADE runtime
Runtime runTime = Runtime.instance();
// Exit the JVM when there are no more containers around
runTime.setCloseVM(true);
// Create a profile and the main container and start RMA
Profile mainProfile = new ProfileImpl(true);
AgentContainer mainContainer = runTime.createMainContainer(mainProfile);
AgentController rma = mainContainer.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
Thread.sleep(500);
// Create a Sniffer
AgentController sniffer = mainContainer.createNewAgent(
"mySniffer", "jade.tools.sniffer.Sniffer",
new Object[]{"BuyerAgent1;BuyerAgent2;ShipperAgent1;ShipperAgent2"});
sniffer.start();
Thread.sleep(500);
// Create a Introspector
AgentController introspector = mainContainer.createNewAgent(
"myIntrospector", "jade.tools.introspector.Introspector",
null);
introspector.start();
Thread.sleep(500);
// Prepare for create and fire new agents:
Profile anotherProfile;
AgentContainer anotherContainer;
AgentController agent;
/* Create a new profile and a new non-main container, connecting to the
default main container (i.e. on this host, port 1099)
NB. Two containers CAN'T share the same Profile object: create a new one. */
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent1", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent2", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a ShipperAgent...");
agent = anotherContainer.createNewAgent("ShipperAgent1", "transfersimulation.ShipperAgent", new Object[0]);
agent.start();
Thread.sleep(900);
return;
}
}
This works if no other JADE Platform is already running.

How to specify multiple options using apache commons cli?

I want something like:
java programName -jobs1 -C 10 -W 20
java programName -job2
java programName -job3
With contents:
Option o1 = new Option("job2", "some desc");
Option o2 = new Option("job3" , "(some desc")
Option o3 = OptionBuilder.hasArgs(2).withArgName( "W" ).withArgName("C").withDescription( "Some desc" ).create("job1")
Option o4 = new Option("help");
Options os = new Options().addOption(o1).addOption(o2).addOption(o3).addOption(o4).
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "ProgramName", options );
...where the output is:
Usage ProgramName
-job1 <c> Some Desc
-job2 Some desc
-job3 Some desc
-help Print this message
I expect for -job1 it should print -job1 -C <> -W <>
Am I missing something? It doesn't work with more than one argument. By the way, I used commons-cli 1.2.
You cannot have context-sensitive arguments. You can have the arguments: job1, job2, job3, C & W, but you cannot say (through the library) that C & W are only valid for job1.
If job1/2/3 are mutually exclusive, create an OptionGroup. Then in code, make sure C & W are only given for job1.
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.HelpFormatter;
public class StackOverflowExample
{
public static final String JOB1 = "job1";
public static final Option job1 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job1")
.create(JOB1);
public static final String JOB2 = "job2";
public static final Option job2 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job2")
.create(JOB2);
public static final String JOB3 = "job3";
public static final Option job3 =
OptionBuilder.hasArg(false)
.isRequired(false)
.withDescription("description of job3")
.create(JOB3);
public static final String MY_C = "C";
public static final Option my_c =
OptionBuilder.hasArg(true)
.withArgName("count")
.isRequired(false)
.withDescription("description of C")
.create(MY_C);
public static final String MY_W = "W";
public static final Option my_w =
OptionBuilder.hasArg(true)
.withArgName("width")
.isRequired(false)
.withDescription("description of W")
.create(MY_W);
public static void main(String[] args)
{
Options options = new Options();
OptionGroup optgrp = new OptionGroup();
optgrp.addOption(job1);
optgrp.addOption(job2);
optgrp.addOption(job3);
options.addOptionGroup(optgrp);
options.addOption(my_c);
options.addOption(my_w);
try {
CommandLineParser parser = new GnuParser();
CommandLine cmdline = parser.parse(options, args);
if (((cmdline.hasOption(MY_C)) || (cmdline.hasOption(MY_W))) &&
(! cmdline.hasOption(JOB1))) {
HelpFormatter help = new HelpFormatter();
help.printHelp("cmdname", options);
System.exit(-1);
}
System.out.println("OK");
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
}
Which produces the following output:
<~/sandbox/CoreUtils/scratch> $ javac -d . -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample.java
<~/sandbox/CoreUtils/scratch> $ java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job1
OK
<~/sandbox/CoreUtils/scratch> $ java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job2
usage: cmdname
-C <count> description of C
-job1 description of job1
-job2 description of job2
-job3 description of job3
-W <width> description of W

Categories

Resources