Check javascript function is defined from java applet - java

I am developing a Java applet where I call a javascript function:
boolean isAllowed = (boolean) win.eval("isPointMarkCreationAllowed()");
and I would like to check if that function exists, like we do in javascript:
if (isPointMarkCreationAllowed == 'function')
is there anyway to do that in Java?

Without actually having tried it, wouldn't
win.eval("typeof isPointMarkCreationAllowed == 'function'");
do exactly what you want and return a Boolean (true or false)?

You can use reflection to test if a method exists.
For example if you have an object foo, you can get all the methods declared in the class of that object in the following:
Method[] methods = foo.getClass().getMethods();
This returns an array of the methods declared in the class.
Then just use a for loop to check if a specific method exists in the array returned
for (Method m : methods)
{
if (m.getName().equals(someString))
{
//do something
}
}
someString is the name of the method you're looking for, which is "isPointMarkCreationAllowed" in your case.
Use the following site to learn about reflections in Java
http://docs.oracle.com/javase/tutorial/reflect/member/methodType.html

Related

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.

Proper usage of Optional.ifPresent()

I am trying to understand the ifPresent() method of the Optional API in Java 8.
I have simple logic:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));
But this results in a compilation error:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)
Of course I can do something like this:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}
But this is exactly like a cluttered null check.
If I change the code into this:
user.ifPresent(new Consumer<User>() {
#Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});
The code is getting dirtier, which makes me think of going back to the old null check.
Any ideas?
Optional<User>.ifPresent() takes a Consumer<? super User> as argument. You're passing it an expression whose type is void. So that doesn't compile.
A Consumer is intended to be implemented as a lambda expression:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));
Or even simpler, using a method reference:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);
This is basically the same thing as
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
#Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});
The idea is that the doSomethingWithUser() method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its void result to ifPresent().
In addition to #JBNizet's answer, my general use case for ifPresent is to combine .isPresent() and .get():
Old way:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}
New way:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})
This, to me, is more intuitive.
Why write complicated code when you could make it simple?
Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...
if (user.isPresent())
{
doSomethingWithUser(user.get());
}
This code has the advantages of being
readable
easy to debug (breakpoint)
not tricky
Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.
You can use method reference like this:
user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);
Method ifPresent() get Consumer object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user.
Or if this method doSomethingWithUser is in the User class and it is not static, you can use method reference like this:
user.ifPresent(this::doSomethingWithUser);
Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent() . Example:
list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());

php redeclaring function like in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php function overloading
I want to redeclare function such like this:
class Name{
function a(){ something; }
function a($param1){ something; }
}
but it returns
Fatal error: Cannot redeclare Name::a()
In java it just works. How can I do this in PHP?
Use default parameters:
class Name{
function a($param1=null){ something; }
}
If no parameter is passed to Name::a() it will assign a $param1 has a value of null. So basically passing that parameter becomes optional. If you need to know if it has a value or not you can do a simple check:
if (!is_null($param1))
{
//do something
}
You won't redeclare a function. Instead you can make an argument optional by assigning a default value to it. Like this:
function a($param1 = null){ something; }
Function arguments to not uniquely identify a function. In Java the arguments are strictly defined. This allows the compiler to know which function you are calling.
But, in PHP this is not the case.
function a()
{
$args = func_get_args();
foreach($args as $value)
{
echo $value;
}
}
It's possible to create function that has no arguments define, but still pass it arguments.
a("hello","world")
would output
hello world
As a result, PHP can't tell the different between a() and a($arg). Therefore, a() is already defined.
PHP programmers have different practices to handle this single function problem.
You can define an argument with default values.
a($arg = 'hello world');
You can pass mixed variable types.
function a($mixed)
{
if(is_bool($mixed))
{
.....
}
if(is_string($mixed))
{
.....
}
}
My preference is to use arrays with defaults. It's a lot more flexible.
function a($options=array())
{
$default = array('setting'=>true);
$options = array_merge($default,$options);
....
}
a(array('setting'=>false);
Unfortunately PHP does not support Method overloading like Java does. Have a look at this here for a solution: PHP function overloading
so func_get_args() is the way to go:

what does this code snippet mean

code snippet:
for( String token : tokens )
{
try
{
Url url = as("mycompany", "someapikey").call(shorten(token));
}
}
what do the 'as' and the 'call' mean. Are they keywords in java?
i was browsing and i found this code and i would like to understand what it means.
thank you in advance.
Looks like it's using the bit.ly library to shorten URLs. the for loop is iterating through strings in a collection, tokens. it then creates a shortened URL via the bit.ly library. These aren't keywords in Java, they are just method names.
android bit.ly library: http://code.google.com/p/bitlyj/
No, they are regular methods. The as() method should be in the class this is from (or a superclass), while the call() method is defined for the type returned by as().
It would be helpful to have a link back to the original source where you found this, as more context is often useful.
as and call are not keywords in Java.
It seems that as(String s1, String s2) is a method that returns an object that has a method call(..).
That method call(..) is invoked on the return value of as(..).
Maybe a static import?
For example, if class Foo has a static method as(), you can use
import static Foo.as;
{
//now can do this:
as(); //equal to Foo.as();
}

Can gmock mock static methods of Java classes? Alternative?

I could not get it to work. It's like the method is not mocked.
Are there alternative groovy testing frameworks that work better to mock static Java methods?
Update 02/Mar/2011: Adding code:
I am actually trying to mock the Scala XML.loadXml (I am trying Groovy for unit testing) class:
This is my test case:
// ContentManagementGatewayTest.groovy
class ContentManagementGatewayTest extends GMockTestCase
{
void testGetFileList()
{
// Preparing mocks code will go here, see below
play {
GetFileGateway gateway = new GetFileGateway();
gateway.getData();
}
}
}
// GetFileGateway.scala
class GetFileGateway {
def getData()
{
// ...
val xmlData = XML.loadData("file1.txt");
}
}
I tried testing using both gmock and metaClass:
// metaClass:
XML.metaClass.'static'.loadFile = {file ->
return "test"
}
// gmock:
def xmlMock = mock(XML)
xmlMock.static.loadFile().returns(stream.getText())
You can do this using Groovy (metaprogramming), you don't need any additional libraries. Here's a (stupid) example, that overrides Collections.max such that it always returns 42. Run this code in the Groovy console to test it.
// Replace the max method with one that always returns 42
Collections.metaClass.static.max = {Collection coll ->
return 42
}
// Test it out, if the replacement has been successful, the assertion will pass
def list = [1, 2, 3]
assert 42 == Collections.max(list)
Update
You mentioned in a comment that my suggestion didn't work. Here's another example that corresponds to the code you've shown in your question. I've tested it in the Groovy console and it works for me. If it doesn't work for you, tell me how your testing differs from mine.
Math.metaClass.static.random = {-> 0.5}
assert 0.5 == Math.random()
Scala doesn't have static methods, so it is no wonder you couldn't mock one -- it doesn't exist.
The method loadXml to which you refer is found on the XML object. You can get that object from Java with scala.XML$.MODULE$, but, since objects are singleton, its class is final.
Alas, loadXML is defined on the class XMLLoader, which the object XML extends, not on the object XML itself. So you can simply do a normal mock of XMLLoader. It will lack a few methods, but perhaps it will do all you need.
The documentation for GMock seems to show that you can just do:
Mocking static method calls and
property call is similar to standard
method calls, just add the static
keyword:
def mockMath = mock(Math)
mockMath.static.random().returns(0.5)
play {
assertEquals 0.5, Math.random()
}

Categories