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.