How do I convert a String to date in velocity template? - java

I want to convert $departureFromDate (format:yyyy-MM-dd) to date object so that I can perform increment operations on it. I have been trying to do it the following way:
#set($departureFromDate = "{{jsonPath request.body
'$.departureFromDate'}}")
#set($dateObj = $date.toDate('yyyy-MM-dd',"$departureFromDate"))
#set($calendar = $date.getCalendar())
$calendar.setTime($dateObj)
$calendar.add(6,5)
The above code works if give an actual date like:
#set($dateObj = $date.toDate('yyyy-MM-dd',"2018-09-22"))
But does not work when I try to use $departureFromDate

There are several problems in your code. First, as user7294900 noted, the right value of the first assignation seems quite weird. Then, you don't need to instanciate yourself a calendar (plus, you can write $date.calendar instead of $date.getCalendar(), and you don't need double quotes around string arguments).
#set($body = '{ "departureFromDate" : "2018-03-01" }')
$json.parse($body)
#set($departureFromDate = $json.departureFromDate)
#set($dateObj = $date.toDate('yyyy-MM-dd', $departureFromDate))
#set($calendar = $date.toCalendar($dateObj))
$calendar.add(6, 5)
The above code uses a JSON parsing tool, whose parse() method renders a json wrapper, that you shall provide in your context.
As a final advise, if you hadn't already thought of it, be sure to print $obj and $obj.class.name in your context as a trivial debugging technique if you don't understand what happens.

Related

How to get requestUri out of Cocoon into my Java function?

I inherited some old Cocoon code, if it's obvious, please tell me where in the docs I could find it.
I have a function to clean up some page parameters. I want to hand over the content to that function, but I can't manage to get there.
This is the original code, the value must pass my "cleanPath" function.
<jdbp:page-param name="pageToLoad" value="${{request.requestURI}}/../{#page}"/>
Attempt 1:
<jdbp:page-param name="pageToLoad" value="cleanPath(${{request.requestURI}}/../{#page})"/>
My attempt was to add the function in and leave everything like that, but it's not working.
My next attempt is these nice xsp:logic blocks, where I can't get the requestURI. "request.requestURI" is unknown, evaluate complains
"Type mismatch: cannot convert from Object to String".
<xsp:logic>
String input2 = evaluate("${{request.requestURI}}", String.class);
String input = "/../<xsl:value-of select="#page"/>";
putVariable("Hase","Test "+input);
</xsp:logic>
<jdbp:page-param name="pageToLoad" value="${{request.requestURI}}/../{#page}"/>
<jdbp:page-param name="Hase" value="${{Hase}}"/>
It's easy to just call request.getRequestURI();. No need for complicated wrappers.

Splitting string with similar starting pattern

So, I've been trying to split something I'm reading from a file. But everything that I've tried does not give me only the part that I want.
What I have as string is this:
Scenario:
Bunch of stuf here
Just typing stuff for the example...
Scenario:
More stuff here
A lot more stuff here
XX123
I want to get everything from 'Scenario:' to 'XX123'
Like this:
Scenario:
More stuff here
A lot more stuff here
XX123
The file that I'm reading from have a lot of those 'Scenarios:' and using Pattern from java doesn't give me only the part that I want. Instead it gives from the first 'Scenario:' it finds until 'XX123'
I also tried to use StringUtils.substringBetween, same result.
Thanks in advance
The old-fashioned way to do it would look something like this:
String inputText;
String END_MARKER = "XXX123";
int indexOfEnd = inputText.indexOf(END_MARKER);
// search in reverse
int indexOfScenario = inputText.lastIndexOf("Scenario", indexOfEnd);
String result = inputText.substring(indexOfScenario,
indexOfEnd + END_MARKER.length());

Java- Getting variables from method into other method

I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.
Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];
JTextField input_day =new JTextField(DateDay);
// input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);
and in the other method I need these variables:
input_datum.setText(reportDate);
if(check_datum.isSelected()){
CustomDateFinal[0] = datumvar;
input_datum.setText(CustomDateFinal[0]);
}
Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)
EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE
Are these methods in the same class? If so, why don't you declare the variables outside the method? That way their scope is across all methods. If not, you could create getters/setters for each variable.
It's a design problem:
The objet containing the methods createFields and customKeyEvent has to exchange some values between those.
Then, you could create a structure (class) return by createFields, that contains your created field and the values customKeyEvent needs.
Or, you could externalize values and create type's properties. During the call of createFields, set the properties value, and after, you could get it from customKeyEvent. But take care of possibly multithreading access: choose the good accessibility of your properties for your problem.
I think the second choice is the best ; these solution respect the role suggested by the name of createFields method.
It could be a good practice to you to learn about design patterns. That's some classics of basic design problem resolution.
It still helps me every day.

Java - generating conditions from string

I'm trying to generate some conditions using string i get as input.
For example, i get as in put the string "length = 15" and i want to create from that the condition:
length == 15.
To be more specific, i have an int in my program called length and it is set to a specific value.
i want to get from the user a conditon as input ("length < 15" or "length = 15"....) and create an if statement that generates the condition and test it.
What is the best way of doing that?
Thanks a lot
Ben
Unless you're talking about code-generation (i.e. generating Java-code by input strings) you can't generate an if-statement based on a string.
You'll have to write a parser for your condition-language, and interpret the resulting parse trees.
In the end it would look something like this:
Condition cond = ConditionParser.parse("length = 15");
if (cond.eval()) {
// condition is true
}
Use a string tokenizer. The default method to distinguish between tokens (or the smallest parts of the input string) is white space, which is to your benefit.
check out javadocs for details:
http://docs.oracle.com/javase/1.3/docs/api/java/util/StringTokenizer.html
Depending on what restrictions you can place on your input format, you could consider using Rhino to embed Javascript. Your 'conditions' then just have to be valid JavaScript code. Something like this (disclaimer: haven't compiled it):
import javax.script.*;
public bool evalCondition (Object context, String javascript) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Object result = engine.eval(javascript);
Boolean condTrue = (Boolean)result;
return condTrue;
}
See the Embedding Rhino Tutorial for more details.

Create a string with the result of an expression and the expression that originated the value. Is it possible?

Like
String r = SomeThing.toExecString("new Object().toString()");
And when executed the value of r would be:
"new Object().toString() = java.lang.Object#c5e3974"
Is this even possible at all? Would it need a bunch of reflection? A built in compiler maybe?
ScriptEngine engine = new ScriptEngineManager().getEngineByName("beanshell");
Object result = engine.eval("new Object().toString();");
System.out.println(result);
You may get close to what you want using BeanShell. I ran the above code with Java 6 with BeanShell 2.0b4 and the JSR 223-based bsh-engine.jar engine on the classpath.
There is a great post here:
Generating Static Proxy Classes - http://www.javaspecialists.eu/archive/Issue180.html
Part one is enough for what you asked, I think
Don't know if you really wanted this. But your problem would be solved with this method:
String toExecString( String code ) {
return String.format(
"\"%s\" = %s#%x",
code,
code.getClass().getName(),
code.hashCode()
);
}

Categories

Resources