How to run a Groovy script in my Spring Boot Application? - java

So I have an existing spring boot app. I want to add a Groovy script (let's say "HelloWorld.groovy") to display the message hello world. how can i do this?
below is how i want it took like :
// some random code here
// ...
// ...
// groovy script : "HelloWorld" to be executed
// some random code ...

There are a lot of different ways to do it and there isn't enough information in the question to know for sure what the best solution for you is going to be, but one way to do it is to create a GroovyShell and evaluate the script in that shell.
import groovy.lang.GroovyShell;
public class GroovyDemo {
public static void main(String[] args) {
System.out.println("This represents some random code");
String groovyScript = "println 'first line of Groovy output'\n" +
"println 'second line of Groovy output'";
GroovyShell groovyShell = new GroovyShell();
// instead of passing a String you could pass a
// URI, a File, a Reader, etc... See GroovyShell javadocs
groovyShell.evaluate(groovyScript);
System.out.println("This represents some more random code");
}
}
Output:
This represents some random code
first line of Groovy output
second line of Groovy output
This represents some more random code

Related

Packaging a jar with preconfigured command line arguments

I am wondering if there's a way to create a jar that includes some command line arguments in it, the arguments that are usually passed in the command line when one tries to start up the jar (these parameters are then passed on to the main function). Basically instead of starting my app with
java -jar myapp.jar "arg1" "arg2", I want to start my app with
java -jar myapp.jar
and have "arg1" and "arg2" passed to the main function.
The reason behind this is that I want to deploy this to different environments, and I want my jar to contain different parameters according to the environment it's being deployed at.
Maybe there's another way to achieve similar results ??
Cheers.
PS: Looking for a maven solution.
Edit: I'll add a complete example to make this a bit more clear:
Let's say I have 2 environments: "Production" and "Test". I want to run the jar in the same way no matter in what environment I deploy it. So I always want to run it with:
java -jar myapp.jar
But! In order for my 2 environments to run ok, I need the Production environment jar to start it's main method with an argument "prod" and I need the Test environment jar to start it's main method with an argument "test".
If I correctly understood your problem, in your main() you could define a simple logic to handle the case where you do not specify any input parameter; the logic could retrieve the desired values according to the correct platform/env.
As an example:
public class Test01
{
public static void main(String... aaa)
{
// Check input
if(aaa.length == 0) {
/* Insert logic to retrieve the value you want, depending on the platform/environment.
* A trivial example could be: */
aaa = new String[2];
aaa[0] = "First value";
aaa[1] = "Second value";
}
// Processing, e.g. print the 2 input values
System.out.println(aaa[0] + ", " + aaa[1]);
}
}
Fyi, I created a runnable jar using eclipse, and start the application by either
java -jar Test01.jar
or
java -jar Test01.jar arg1 arg2
Hope this helps!
One solution is to change main(String[] args) to get values from env var if they are not present in the passed arguments.
String user;
String password;
if(args.length < 2)
{
user = System.getenv("appUser");
password = System.getenv("appPassword");
} else {
user = args[0];
password = args[1];
}
You can also create another class with a main function that will call the real one.
public class CallerMyApp{
public void main(String[] args) {
String[] realArgs = {System.getenv("appUser"), System.getenv("appPassword")};
MyApp.main(realArgs);
}
}
Then to execute its something like
java -cp myapp.jar CallerMyApp

How to eliminate empty new line using Regex?

how to eliminate empty new line into source code using regex.?
my basic is java
example :
class ex{
String a="Hello World";
public static void main(String[] args){
System.out.println(a);
}
}
result source code without empty new line :
class ex{
String a="Hello World";
public static void main(String[] args){
System.out.println(a);
}
}
To delete an empty line use:
String result = text.replaceAll("(?im)^\\s*\r?\n", "");
You could do it using:
//read line
if (line.matches("^\\s*$")) {
System.out.println("ignoring empty line");
}
Alternatively, you could use IDE's like eclipse/netbeans/Intellij etc and configure how you would like to indent your code automatically.
Many modifications of a text file (Java or otherwise) can be achieved by using standard tools. Writing a program for eliminating empty lines is a waste of time.
If you are on Linux, run your file through grep:
grep -v '^\s*$' Input.java >Output.java
For Windows, get one of the work-alikes which Google ("grep on windows") will find you. The command, using cmd, would be the same, but the Windows program may come with a GUI, which might make it even simpler.

Invoke java method through perl and get the return value without using inbuilt functions

I have a Java program which has a static method
private static int checkURL(String currentURL)
From my perl script, I want to call this method and get return value of this method.
I have a constraint that I can't use any inbuilt Perl modules offered by CPAN.
I am thinking to call Java through system() command in Perl but issue is how to call this method and get the return code?
call external command and get back result (straight from http://www.perlhowto.com/executing_external_commands)
#-- scalar context
$result = `command arg1 arg2`;
Using Java module
use Java;
my $java = new Java;
my $obj = $java->create_object("com.my.Class","constructor parameter");
$obj->checkURL("http://www.google.com/");
$obj->setId(5);
Iniline::Java is also a famous module for Java/Perl integration.
Edit: I have a constraint that I can't use any inbuilt perl modules offered by CPAN.
Oh sorry I didn't see that. I had tried something like below some time ago.
Hello.java
class Hello {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program to test return code.\n");
System.exit(100);
}
}
test.pl
#!/usr/bin/perl
use strict;
use warnings;
my $command = "java Hello";
print "Command is $command:\n";
system($command);
my $retval = $? >> 8;
print "The return code is $?\n";
print "retval is $retval\n";
Run it
perl test.pl
Output
Command is java Hello:
This is a simple Java program to test return code.
The return code is 25600
retval is 100

How to read and write text files from the main in java

The static method main, which receives an array of strings. The array should have two elements: the path where the files are located (at index 0), and the name of the files to process (at index 1). For example, if the name was “Walmart” then the program should use “Walmart.cmd” (from which it will read commands) and “Walmart.pro” (from which it will read/write products).
I don't want anyone to write the code for me because this is something I need to learn. However I've been reading this through and the wording is confusing. If someone could help me understand what it wants from me through pseudo-code or an algorithm it would be greatly appreciated.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
The main method's String array input argument consists of whatever String arguments you pass to the program's main method when you run the program. For example, here is a simple program that loops over args and prints a nice message with each argument's index and value on a separate line:
package com.example;
public class MainExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.printf("args[%d]=%s\n", i, args[i]);
}
}
}
Once you've compiled the program, you can run it on the command-line and pass it some arguments:
java -cp . com.example.MainExample eh? be sea 1 2 3 "multiple words"
Output:
args[0]=eh?
args[1]=be
args[2]=sea
args[3]=1
args[4]=2
args[5]=3
args[6]=multiple words
So lets explain to you
Create a class Inventory : if you don't know how to create a class google it just as is
The static method main: Every executable class in java (at least from the console) has the main method you should google java main method and propably in the same place you find it you will see the default arguments that it receives
When you learn about the default arguments of method main you will undertand about the 'args' that has to be on it
You will have t study the class String google it "java String class"
You will have to study the class File google it "java File class"
At the end everything else would be just logic and I beleave you have learned some at this point.
public class Inventory { // class inventory
public static void main(String[] args) // main method
{
if(args.length==2){ // check if args contains two elements
String filePath = args[0];
String fileName = args[1];
filePath+= System.getProperty("file.separator")+fileName;
File fileCMD = new File(filePath+".cmd");
//fileCMD.createNewFile();
File filePRO =new File(filePath+".pro");
//filePRO.createNewFile();
}
else {
//write the code to print the message Usage: java Inventory Incorrect number of parameters for a while and exit the program.
}
}
This is what I've understood. Basically you have to write a program to create two files, one called fileName.cmd and the other fileName.pro. You have to construct the path of the files using the arguments (input parameters of the main method) and system's file separator. If the arguments don't have two elements you have to print the 'invalid' message. That's it.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
You have to use command line to pass the arguments and launch the program , something like the following code in cmd or terminal:
java inventory thePath theFileName
That's how it get initialized.

Can we Runtime.getRuntime().exec("groovy");

I installed Groovy.
And I am trying to run groovy scripts from a command prompt that I created using Java, like so:
Runtime.getRuntime().exec("groovy");
So if I type in "groovy" to the command line, this is what I get:
>>>groovy
Cannot run program "groovy": CreateProcess error=2, The system cannot find the file specified
Does anyone have an idea as to what might be going wrong? Should I just use Groovy's implementation of exec? Like:
def processBuilder=new ProcessBuilder("ls")
processBuilder.redirectErrorStream(true)
processBuilder.directory(new File("Your Working dir")) // <--
def process = processBuilder.start()
My guess is that it wouldn't matter whether using Java's implementation or Groovy's implementation.
So how do I run a groovy script?
The way originally described in the question above calling the groovy executable invokes a second Java runtime instance and class loader while the efficient way is to embed the Groovy script directly into the Java runtime as a Java class and invoke it.
Here are three ways to execute a Groovy script from Java:
1) Simplest way is using GroovyShell:
Here is an example Java main program and target Groovy script to invoke:
== TestShell.java ==
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
// call groovy expressions from Java code
Binding binding = new Binding();
binding.setVariable("input", "world");
GroovyShell shell = new GroovyShell(binding);
Object retVal = shell.evaluate(new File("hello.groovy"));
// prints "hello world"
System.out.println("x=" + binding.getVariable("x")); // 123
System.out.println("return=" + retVal); // okay
== hello.groovy ==
println "Hello $input"
x = 123 // script-scoped variables are available via the GroovyShell
return "ok"
2) Next is to use GroovyClassLoader to parse the script into a class then create an instance of it. This approach treats the Groovy script as a class and invokes methods on it as on any Java class.
GroovyClassLoader gcl = new GroovyClassLoader();
Class clazz = gcl.parseClass(new File("hello.groovy");
Object aScript = clazz.newInstance();
// probably cast the object to an interface and invoke methods on it
3) Finally, you can create GroovyScriptEngine and pass in objects as variables using binding. This runs the Groovy script as a script and passes in input using binding variables as opposed to calling explicit methods with arguments.
Note: This third option is for developers who want to embed groovy scripts into a server and have them reloaded on modification.
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
String[] roots = new String[] { "/my/groovy/script/path" };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("hello.groovy", binding);
System.out.println(binding.getVariable("output"));
Note: You must include the groovy_all jar in your CLASSPATH for these approaches to work.
Reference: http://groovy.codehaus.org/Embedding+Groovy

Categories

Resources