torsdag 26. november 2009

Scala - learning notes

Plan

Do it standing, about same mix of slides and coding as before, handouts.

Slide: Tom Waits + install
Slide/Code: fire up scala and show off syntax (REPL)
Slide: motivation
Slide: My verdict + References
Slide/Code: Bonus section

Presentation

“Your hands are like dogs, going to the same places they’ve been. You have to be careful when playing is no longer in the mind but in the fingers, going to happy places. You have to break them of their habits or you don’t explore; you only play what is confident and pleasing. I’m learning to break those habits by playing instruments I know absolutely nothing about, like a bassoon or a waterphone.”—Tom Waits

(Picture from flickr / Conor Lawless).

Install

Download zip-file, unzip, set SCALA_HOME and add to PATH.
Then: install plugins for NetBeans (6.7+, prefer 6.8) and eclipse (3.5+).
I did best letting NetBeans handle project (not Maven).

Syntax / REPL

scala.bat: Quick Read Evaluate Print Loop



































Code Points
to make

class PhoneNumber( val kind: String, var no: String ) {

override def toString(): String = {
no + " (" + kind + ")"
}
}

switch to name: type

val / var / def

primary constructor

Concise

object PhoneNumber{

def apply( kind: String, no: String ) : PhoneNumber = {
new PhoneNumber( kind, no )
}
}

object, no statics

apply is "default method"

val phonebook = Map(

"Tommy mobil" -> PhoneNumber( "cell", "92012201" ),
"ICE Medisinsk" -> PhoneNumber( "work", "113" )
)

Expressive
println( phonebook("Tommy mobil" ).no ) Concise
phonebook.foreach(tuple => println( tuple._1 + ":" + tuple._2 )) High-level

functional iteration
1.1.+(2.2)

1 until 10
Pure OO

operator mode for methods

val xmlE = <a href="index.html"> {3 + 4} </a>

(xmlE \ "@href").text

Pragmatic

.

Motivation

Evolution, not revolution: Java-like, interoperates with java (seamlessly).
  • can extend java classes
  • can implement java interfaces
  • understands java generics
  • uses java primitives
Leads you into functional programming.
Easy to do easy stuff, AND facilitates the hard stuff.
More up2date language - builds on java lessons, adds:
  • Facilitates DSL with several short-hand notations
  • Traits (~multiple inheritance)
  • ++
One vision (Martin Odersky), not designed by comitee
Pragmatic



"I can honestly say if someone had shown me the Programming Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy." — James Strachan

"If I were to pick a language to use today other than java, it would be Scala" — James Gosling (from before he left Oracle)

My verdict: lead me into...

Wonderful way of coming from Java to Functional programming. I started out writing java-like OO, but wolfed out by the end of my second 3-hour session.
The book fuelled this transformation.
Scala feels very good so far, I now like Java less...

References

Scala site.

Book "Programming in Scala" (Odersky++) is very good for learning, not so for reference.

The busy Java developer's guide to Scala: articles on DeveloperWorks

From JavaZone 09:

Bonus section

Start with Java Discovery and refactor a suitable class:
  • common.ServiceDescription (for properties and basics) NB! keep scala-code for equals / canEqual
Show off in code
Code Points to make
TestServer object and main
client.v2.Notifier operators
client.ServiceBrowser:
  • class extends with
  • tryto
  • getReplyDescriptor
traits
Function is first-class object
Option + match
sclanb.Main.recurse2 Closures, and how crazy I got
sclanb.Main
client.ServiceBrowserListener abstract, no interface
FirstSwingApp. DSL, Swing
Code from ch30 Actors


fredag 30. oktober 2009

Grails - learning notes

Hello Grails!

Trailer.
Download and unpack Grails, set GRAILS_HOME environment variable and update PATH. It works

grails create-app mapp
cd mapp
grails create-domain-class mapp.site.Site
grails create-controller mapp.site.Site

Import project into Eclipse or NetBeans (Grails creates Eclipse project)
Add fields and toString() to model
Add dynamic scaffold property to controller (def scaffold=Site)
grails run-app
Run and show off dynamicity by adding fields to model, and index-method.

grails generate-all mapp.site.Site

Step back and explain:
  • CoC: Show mapping url -> controller+view
  • MVC: Jump to "Domain Model", "Controller", "GSP"
  • Configuration: Set up database: store and update
Code a test

Why?
No configuration, zero overhead, immediate turnaround.
High-productivity web MVC framework for the Java platform
  • CoC: easy to find your way to domain-objects, controllers, services, views
  • Ready-to-use development environment (+test and production)
  • Scaffolding (even dynamic): quick-start
  • Familiar: On the shoulders of Java eco-system, Hibernate, Spring, Groovy, SiteMesh
  • GORM: DAO-layer implemented by MOPing
  • Good Ajax-support
  • Small stuff: test support, generating (web-)services. flash-scope, Web-flow, filters
  • Easily extensible, 312 Plugins at last count. Grails main function is plugin management.

Domain Model
You write POGOs, GORM provides DAO-functionality through mixins:
  • get, list, save, delete
  • findByName, findBy...And...
Validation provided.
Error container provided: siteInstance.errors
Command Object: domain object that is not persisted

Controllers
Scaffolding: CRUD generated. Provides a nice starting point.
Comment on first Controller generated:
  • list(): where did Site.list() come from?
  • list(): return statement optional.
  • show(): what is flash-scope?
  • show(): Model passed to view: Controller properties or returned map [key:value].
  • edit(): same as show() but different view (by convention)
  • update(): siteInstance.properties = params
  • index(): will be default action if not overridden by eg. defaultAction = 'list';

View (GSP)
JSP works, but GSP takes advantage of Groovy, and is remarkably similar
GSP taglib similar to Struts2 + jstl

Services
Transactional boundaries, automagicaly injected.

Google app-engine
Fra http://grails.org/plugin/app-engine og http://www.morkeleb.com/tag/grails/
sørge for at domeneklasser ligger under en pakke
grails install-plugin app-engine
(valgte jpa)
grails install-plugin gorm-jpa
La til annotasjoner (@Entity)

grails app-engine run
grails set-version 1
grails app-engine package

(første gang $APPENGINE_HOME/bin/appcfg.sh update ./target/war)

grails app-engine deploy

Go 2 http://nerdetom.appspot.com/

IDE Support
Approaching acceptable, maybe good if my PC was working fine.
NetBeans: syntax colored, some autocomplete, access to grails-commands, direct junit debug
Eclipse: some syntax colored, some autocomplete, debug of junit-tests.
IDEA: supposedly best-of-breed.
Debugging: remote (grails-debug run-app) on port 5005

Recommended reading
http://grails.org
http://www.morkeleb.com/tag/grails/
Book: "The Definitive Guide To Grails" 2nd edition by Graeme Rocher and Jeff Brown. Comprehensive and readable guide, details Enterprise integration issues.
Mastering Grails on DeveloperWorks.
Agile Enterprise Development with Groovy and Grails: From JavaZone 09

Outro.

søndag 7. juni 2009

OSX Java


Apple provides different integration code for different Java versions, see OSXAdapter or integration guide for Java >= 1.4.

MRJAdapter provides OSX-integration for several Java-versions

torsdag 14. mai 2009

Struts2: Quick and easy Wizard

Use a wizard to fill in data piecewise. Spring web-flow (plugin) is recommended. An alternative is to use scope and ModelDriven interceptors together and have them use the same object. Here's the idea coded:




public class SomeAction extends ActionSupport implements ModelDriven<somemodel> {
private SomeModel model;
public SomeAction ( ... ) {
model = new SomeModel( ... );
}
/** @see ModelDriven */
public SomeModel getModel() {
return model;
}
/** for scope interceptor */
public SomeModel getSessionModel() {
if ( ! clearSession )
return model;
clearSession = false;
return null;
}
public void setSessionModel( SomeModel newValue ) {
if ( newValue == null )
model.reset();
else
model.copyFrom( newValue );
}

}

NB! we're stuck with the object returned by getModel(), so we should only change it's content, not the object reference.

Action setup:

<action name="someAction" class="SomeAction">
<interceptor-ref name="scope">
<param name="session">sessionModel</param>
<interceptor-ref name="defaultStack" />

<result name="page1">/WEB-INF/jsp/page1.jsp</result>
<result name="page2">/WEB-INF/jsp/page2.jsp</result>

</action>


Scope-interceptor will call setSessionModel() with session data before other calls to Action (getModel, execute, validate), and after execute() returns getSessionModel() is called to get a new value to put in session.

fredag 24. april 2009

JZ08

Exception handling

Se foredrag her.


























TypeHandleFix and update appTry again?
Application ExceptionPossibleNoNo
System ExceptionNoNoPossible
Programming ExceptionNoyesNo


Rammeverk: distribuert Exceptionhierarki (mange klasser)
Applikasjon: sentralisert Exceptionhierarki (1 klasse med felt for id og map for kontekstuell info).

tirsdag 21. april 2009

Google App Engine

Java on App Engine
See App Engine Java Overview.

SDK (ref Google):
I downloaded the SDK, unzipped it and added to my PATH.
I used Ant to build the app in demos\guestbook
I then ran the local test-server with command (path from demos dir):
dev_appserver.cmd guestbook\war

I must wait for activation before I can upload app

Dashboard.

Groovy on App Engine
I impported the code for the Groovy AppEngine HelloWorld, but that does not run locally due to a bug in the SDK. I commented out the line that tries GroovyShell().evaluate("3*4"), and it ran, but it seems that Groovlets are based on being able to evaluate scripts.

Next up: get rss from Blogger and delicio.us.