Get the first value from map using expression - java

I am trying to get the first value of a map by following
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("key1","value1");
myMap.put("key2","value2");
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());
its working for me writing in Java
In same i am using expression in jsf like following
${criterion.variableBindings.firstEntry.getValue()}
In this scenario I didn't get the value.

Please # for the calling method or variable of a bean class..
#{criterion.variableBindings.firstEntry.getValue()}
If you didn't get for for above
create a variable inside bean class setter and getter then access that variable in jsf file.
In bean
private String first ;
first = myMap.firstEntry().getValue();
//setterand getter
in jsp
#{bean.first}

You're trying to invoke the method firstEntry, so you need to use method invocation syntax, which has parentheses after the method name:
${criterion.variableBindings.firstEntry().getValue()}
If the method had been named getFirstEntry you could have accessed it as a property as well, but since it does not start with get you need to access it as a method.

Related

Instance method not called when declaring a Class-type instance variable and call an instance method in Esper

I'm writing an application that has an instance of a class that contains the esper engine. There are a number of instance variables that I would like to read and set using instance method calls from the EPL in the engine. I don't get any compilation errors and the code runs. But the instance method is not called.
epl statements:
module myModule;
create variable com.tp.main.MyClass myClass;
select myProperty from MyEvent unidirectional, method:myClass.getMyProperty() as myProperty;
A hint could be that if I don't use the method: key word in front of the method call I get an error that myClass.getMyProperty class could not be found. The documentation sometimes uses the method: key word and sometimes not in the examples for calling instance methods from Class-type variables.
I have also tried using the addVariable method in the API with the same results.
code for the method.
public Result getMyProperty() {
Result result = new Result();
result.setResult("propertyValue");
logger.info("This method was called");
return result;
}
The class Result is a POJO with getter and setter for a string.
public class Result {
private String result;
public String getResult() {
return result;
}
public void setResult(String str) {
result = str;
}
}
What am I missing?
You could look at a regression test class. The specific one you may want to look at is ExecFromClauseMethodVariable. Maybe your code does not assign a value to the variable?
Github:
https://github.com/espertechinc/esper/blob/3e396d77308532b202ee452100eaaf9e7a044906/esper-regression/src/test/java/com/espertech/esper/regression/epl/fromclausemethod/ExecFromClauseMethodVariable.java
Problem solved and I thought it might be useful to share the solution. Credit to user650839 who pointed me in the right direction. Here is what ended up fixing the problem.
I reverted back to declaring the variable in the runtime configuration API. I found that I must register the variable class, initialize it with the instance object (this) and finally import the class. Here is the snippet of code that does this configuration in the runtime configuration API.
Configuration configuration = new Configuration();
configuration.addVariable("myClass", com.tp.main.MyClass.class, this);
configuration.addImport(com.tp.main.MyClass.class);
epService = EPServiceProviderManager.getProvider(trade.getTradeName(), configuration);
It seems there is a limitation when declaring the Class variable in the EPL. You cannot initialize it with the instance object you want to use. In the runtime configuration API I was able to initialize it with "this" instance of the object which contains all of the instance variables I want to access from the EPL.
The EPL statement did not change. However, it does seem that you must use the key word method: in front of the method call or you get an error "cannot find class..."

How to write an interceptor which logs the arguments and return value?

I am trying to write an interceptor using javax interceptor api. It has to log the arguments passed to a method and the return value of the method.
Below is a sample code snippet which logs the arguments
for(final Object object: context.getParameters()) {
final Methods[] methods = object.getClass().getMethods();
for(final Method method: methods){ if(method.getName().startsWith("get")) {
LOGGER.info(method.getName() + ":" + method.invoke(object));
}
}
}
I am having trouble logging complex/user-defined types.
Let's say there is a getter method which returns students address of type Address. My code does not check if the invoke method returns primitive or user defined type. So it prints hash code of Address when getAddress method is invoked.
I know that I have to write some kind of recursive code by checking the return type of the getter method. If the getter method returns user defined type then I will again use reflection to find all getter method and then print them.
To do this I have to use a if else condition something like below
Pseudo code:
type =method.getReturnType().getSimpleName();
if type != string or int or char or boolean and so on
then
Call the recursive method which again does the above
I want to know if there is a better solution. How do I solve this problem?
use method.getReturnType().isPrimitive()
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isPrimitive%28%29
you can find some other is...() methods that can be useful to you
May be we can use Jackson Mapper api and just pass the instance to the mapper and print the result to the log.
I think this is the easiest way.

The Method values() is undefined for the type String Error

I am currently experimenting in Spring MVC, and right now I'm trying to create a class of constants to populate a drop down list. The enum method is fine, but in my controller I get an error
"The method values() is undefined for the type String.
List<Job> jobList = new ArrayList<job>(
Arrays.asList(job.values()));
mav.addObject("jobList", jobList);
The error appears directly underneath .values() I have imported java.util.Enumeration so it's not that. Any ideas what it could be?
You want the values of the enum class Job, not call the values method on the job variable which in your case seems to be of type String.
Try:
List<Job> jobList = Arrays.asList(Job.values());

fx.prp.file.name to string

I'm having trouble understanding one of the guidelines set by my instructor:
• A public static final String that is assigned the value fx.prp.file.name. This is the context initialization parameter key for the relative path to the property file /WEB INF/fxCalc.prp
While using the code
public static final String codes = "fx.prp.file.name";
i get the error
cannot find symbol
symbol: variable codes
location: class SimplifiedJSPServlet
when i call it from the java file to the jsp file
EDIT:
After this, i have to call it back on a JSP
Inside of jspInit you can use the getServletContext method to get a ServletContext object. This object is available to all JSPs. The object has a method call getInitParameter that allows you to retrieve a param-value if you give it a param-name. The param-name, fx.prp.file.name, should be a
public final static String constant inside of FxDataModel. Do not hard-code anything.
It's going to act as a reference, simply surrounding the words in quotes doesn't seem to work
Make it
public static final String codes = "fx.prp.file.name";
if you want to assign literal value "fx.prp.file.name" to referencecodes

Using for a hashtable value the name of a method?

I have created a hash table that will keep as a key a string that will represent the name of the method that the user will give, and as value the actual method call, as string too. The code I am using is the one here:
public void getMethod(String givenMethod){
Map<String, String> methods = new HashMap<String, String>();
methods.put("length", "length();");
methods.get(givenMethod);
}
From the main method I call objectX.getMethod("length");, but the method length(); is not executed. Can someone help me please?
You are getting the method but you are not invoking it. You'll have to do something like this:
Method yourMethod = objectX.getClass().getDeclaredMethod("yourMethodName"); //This is the string that represents the name of the method.
Then you invoke the method. All this through reflection:
yourMethod.invoke(YourObject);
The parameter of the invoke method is first the object, and then the attributes.
You can also get the return type of the method and cast the result, since the invoking the method will result in an Object type method:
yourMethod.getReturnType(); //This line gives you the type returned by your method.
Use Java **reflection to call method by its name (as you said you are storing method name in map).
For more detail read following article :
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
You need to use reflection to call a method by name. So your data structure would look more like
Map<String, Method> meth = new Hashmap<String,Method>();
Where Method is an actual object.

Categories