Monday, August 20, 2012

Getting object from calling method in Java

This is hardly production scenario, but at some point I wanted to find value of a variable from a caller class. Looks like this is not trivial task and is much more complicated than it should be (for some reason), however still possible.
Finding method and class name is easy via Thread class, but accessing real objects seems to be only possible with Java Debug Interface. For this purpose, application must be executed in debug mode (for grails it is with grails-debug command). There is no need for any additional library as everything is included into JDK and probably is used by JDK debugger.
General scenario is as folows:
  • connect with debugger provided with JDI via socket (there are other options, but sockets seems default for most tools)
  • spawn new thread where you will wait to do whatever you want to do with data on stack trace
  • suspend application at point where you want to do it
  • at the end of your work - continue application
There is example:


def att = com.sun.jdi.Bootstrap.virtualMachineManager().attachingConnectors().find{it instanceof com.sun.tools.jdi.SocketAttachingConnector}
Map arguments = att.defaultArguments()
com.sun.jdi.connect.Connector.Argument hostArg = arguments.get("hostname").setValue("localhost")
com.sun.jdi.connect.Connector.Argument portArg = arguments.get("port").setValue("5005")
com.sun.jdi.VirtualMachine vm = att.attach(arguments);
def thread = vm.allThreads().find {it.name()=='main'}
def runnable = new Runnable() {
  void run() {
 while (!thread.isSuspended() ) {
   Thread.sleep(100)
 }
 def frames = thread.frames().findAll {it.location().toString() =~ /grails.plugin.spock.test.listener.PerSpecRunListener:.*/}
 frames.each {frame->
   def res = frame.thisObject()
   def field = res.type().fieldByName("failureCount")
   if (field) {
       def countref = res.getValue(field).toString()
        ...
      }
   }
     thread.resume()
  }
}
new Thread(runnable).start()
thread.suspend() 



Monday, June 18, 2012

IntelliJ IDEA Select In view with specific view

Intellij IDEA has a lot of great shortcuts, but for some reason there is no special shortcut when you need to find file in specific view, for example Grails view. Normal way to do it, is to press shortcut for "Select In..." (Alt+F1) and select your view (or press number with this view). This is basically 2 shortcuts and not too convenient.
Fortunately it is possible to make it easier by recording a Macro, and assigning it new shortcut. Just go to Edit > Macros > Start Macro recording, press "Select In..." shortcut and select your view.

Thursday, May 31, 2012

Downloading URL with login and password

In javadoc there is no clear way on how to download page that requires Basic Authentication, for example like:


  def result = new URL("http://www.requireslogin.com/").getText()


Fortunately, this is still very possible and not too complicated, just add this somewhere before calling URL:


  java.net.Authenticator.setDefault(new java.net.Authenticator() {
    protected java.net.PasswordAuthentication getPasswordAuthentication() {
      return new java.net.PasswordAuthentication("user", "password".toCharArray());
    }
  });


Possibly it would be better to have login and password as parameters, but this still works.

Saturday, May 19, 2012

Adding Ant optional task to Grails

Since version 2 Grails does not include Sshexec with built-in Gant libs, so it broke some of my deployment scripts. Fortunately it is easy to fix with nothing more than few Grapes annotations added to your Gant script:


...

@Grapes([
  @Grab(group ="org.apache.ant", module = "ant-jsch", version ="1.8.1"),
  @Grab(group ="com.jcraft", module = "jsch", version ="0.1.48"),
  @GrabConfig(systemClassLoader = true)
])

...

Possibly, there are other options like adding libs to some magic folders, but I found this one best as it avoids additional configuration, is self explanatory and hard to skip or forget as it is in script itself.

Thursday, April 19, 2012

Groovy Eval slow performance

Groovy Eval is nice feature, unfortunately it does not have great performance. Recently, I had to calculate values on a bunch of objects and got quite dramatic performance issue. After quick investigation, I pinpointed problem to be with Eval, which can be summarized to:


def t = System.currentTimeMillis()
1000.times {
  Eval.x(44, 'x>3')
}
println (System.currentTimeMillis() - t)
7281
I tried to check if there is other solution that could do the same and I found that there is similar native Java function. In similar test I got:


import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings

def t = System.currentTimeMillis()
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
1000.times {
  engine.eval('x>3', new SimpleBindings([x:44]))
}
println (System.currentTimeMillis() - t)
250

Obviously, it will not be absolutely the same in general and I assume Eval provides much more (and looks less ugly), but ScriptEngine is good enough for my case and it performs almost 30 times faster.

Tuesday, April 3, 2012

Accessing request parameters from UserDetailsService in Spring Security

If you need to use several properties to authenticate user with Spring Security, for example, by login and domain, there is no built-in way to do it. Even when you override UserDetailsService it only calls method with one username parameter.
Fortunately, there is easy way to access request context with Grails, so it is possible to extract any parameter you need, like:


import org.springframework.web.context.request.RequestContextHolder

class UserDetailsService implements GrailsUserDetailsService  {

  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    def otherParameter = RequestContextHolder.requestAttributes.params.other
       ...
  }
}