Planet Scala

Scala blogs aggregated

May 16, 2012

Lalit Pant

Recursive Drawing with Kojo

<img src="http://feeds.feedburner.com/~r/lalitpant/~4/gNfgMStxqdY" height="1" width="1"/>

by Lalit Pant (noreply@blogger.com) at May 16, 2012 04:33 AM

Coderspiel

implicit.ly: herald 0.5.0

implicit.ly: herald 0.5.0:

implicitly-notes:

Tumblr Integration

This version of Herald is ported to use the Tumblr API for posting and is configured to publish to notes.implicit.ly by default. The “notes” subdomain is the new home of implicit.ly release notes and redirects are in place.

Upgrade and Authorization

You can upgrade Herald…

The old switcheroo.

May 16, 2012 02:16 AM

May 15, 2012

Coderspiel

Light Table - a new IDE (by Chris Granger)

<iframe frameborder="0" height="225" src="http://player.vimeo.com/video/40281991" width="400"></iframe>

Light Table - a new IDE (by Chris Granger)

May 15, 2012 12:41 PM

implicit.ly

specs2 1.10

This version adds new features on top of 1.9:

  • added a skipAllUnless(condition) to skip examples unless a condition is verified
  • added a CommandLineArguments trait to access the command-line arguments and use them to build the specification or to specialize the examples behaviour
  • added a notoc argument to avoid generating a table of contents
  • added the possibility to add a css/specs2-user.css file to customize the display of the html documentation
  • a specification can be included in another one so that it will be executed at the same time but not displayed: include(childSpec.hide)
  • added the possibility to change the directory where the html documentation is generated: class S extends Specification { def is = "Guide".title.baseDirIs("guide") ^ end }
  • improved the error message when there is an Error thrown from an Example (see this StackOverflow question)

And some fixes:

  • issue 72: fixed a NullPointerException when receiving an AssertionError with a null message
  • issue 78: show the exception stacktrace when thrown from a ScalaCheck property

==========================

specs2 is a library for writing software specifications in Scala.

For more information visit: http://specs2.org.

via herald

Permalink

May 15, 2012 06:17 AM

May 14, 2012

implicit.ly

shapeless 1.2.2

A minor release of shapeless. The main changes include,

  • Scrap Your Boilerplate improvements

    • Data and DataT instances for any type with an associated HListIso, allowing any case class to be traversed/transformed with just the addition of a single one-line implicit declaration
    • Data and DataT instances for pairs generalized to arbitrary tuples
    • Added a SYB example which also illustrates the gains from using HListIso
  • Generalized toHList to anything viewable as a GenTraversable[_].
  • Added HList toArray.
  • Added infrastructure for lifting monomorphic functions to Poly1 and extending Poly1 domains to be universal.
  • HList unify and toList now properly handle empty HLists.

shapeless is an exploration of type class and dependent type based generic programming in Scala.

A series of articles on the implementation techniques used will appear here and it also has a mailing list.

via herald

Permalink

May 14, 2012 01:26 PM

May 11, 2012

implicit.ly

scalatra 2.1.0.M2

core

  • Support X-Http-Method-Override header.
  • Support mounting handlers by class as well as instance.
  • Support ActionResult class hierarchy to bundle status, headers, and body into one case class.
  • Returning an Int sets the status, just like Sinatra.
  • CsrfTokenSupport recognizes the 'X-CSRF-Token' header.
  • Cross build dropped from artifact ID. The same build runs for all Scala 2.9.x.
  • Dropped support for Scala 2.8.x.

fileupload

  • Deprecated in favor of native servlet handling. (Jetty users: requires >= 8.1.3.)
  • Exceptions now handled through standard error handler.

swagger

  • Support for route documentation with Swagger

test

  • Support for testing multipart requests.

Scalatra is a tiny, Sinatra-like web framework for Scala.

Permalink

May 11, 2012 03:05 PM

Tony Morris

SIP-18 is just another bad idea serving nobody

SIP-18 is a bad idea because it makes awful assumptions about what is in the interest of language newcomers. I have had no shortage of unsolicited advice of how to teach, most of it in layers of wrongness, so I am acutely aware of the sheer quantity of this kind of advice. Please refrain for now. This is only my opinion, because it has been asked of me more than twice.

SIP-18 (and the Scala collections library for that matter) is no different to Haskell’s (dreaded) monomorphism restriction (DMR). The DMR was introduced specifically because of another chronically bold over-estimate of one’s ability to understand the process of learning. It is now an undesired language issue that hinders all users, especially newcomers. In other words, it serves nobody’s interest, hinders everyone’s interest and especially, the interest of those for whom it was meant to serve. You need only spend a short period of time with newcomers to Haskell to be overwhelmed by the prominence of this fact.

I can hear the pragmatists in the background muttering something about trade-offs, not being so extreme and keeping it relevant to the real world and blah blah blah, <insert the usual pragmatist bullshit here>. There is nothing to be traded off when you offer to take $5 from me for the low cost of $10. Now stop it and get your head out of the clouds so I can talk to you sensibly.

Not only does SIP-18 not help newcomers at all, it helps nobody, hinders everybody and especially newcomers. It is not a trade-off, it is not a good idea; it is simply a bold, severely misguided assertion about how learning takes place — it’s not even an approximation. I have seen only scant pseudo-psychology to support its existence, which obviates its predictable failure.

Hopefully, the Scala guys will work this out, but if Scala’s remarkable precision to repeat historical mistakes is anything to go by, I do not hold high hopes.

Thanks for asking.

by Tony Morris at May 11, 2012 03:12 AM

May 10, 2012

scala-lang.org

Scala IDE 2.1 Special Edition for 2.10.0-M3 available now!

A few days back the Scala IDE team released an early preview of the Scala IDE V2.1 for Eclipse, based on the new milestone (M3) for the upcoming Scala 2.10. This release has all the new features in the Scala IDE M1, plus a few minor changes needed in order to support 2.10.

You can see the Release Notes for M1 to check the new features in the Scala IDE, and the Scala Change Log for what’s new in Scala 2.10. Read more...

by dotta at May 10, 2012 06:02 AM

May 09, 2012

Jesper Nordenberg

My Take on Haskell vs Scala

I've used both Haskell and Scala for some time now. They are both excellent and beautifully designed functional programming languages and I thought it would be interesting to put together a little comparison of the two, and what parts I like and dislike in each one. To be honest I've spent much more time developing in Scala than Haskell, so if any Haskellers feel unfairly treated please write a comment and I will correct the text.

This is a highly subjective post, so it doesn't contain many references to sources. It helps if the reader is somewhat familiar with both languages.

With that said, let's start the comparison.

Syntax

When it comes to syntax Haskell wins hands down. The combination of using white space for function and type constructor application, and currying makes the code extremely clean, terse and easy to read. In comparison Scala code is full of distracting parenthesis, curly bracers, brackets, commas, keywords etc. I find that I've started using Haskell syntax when writing code on a white board to explain something to a colleague, which must be an indication of it's simplicity.

Type Inference

The type inference in Haskell just works, and does so reliably. The type inference in Scala is clearly worse, but not too bad considering the complexity of the type system. Most of the time it works quite well, but if you write slightly complicated code you will run into cases where it will fail. Scala also requires type annotations in function/method declarations, while Haskell doesn't. In general I think it's a good idea to put type annotations in your public API anyway, but for prototyping/experimentation it's very handy to not be required to write them.

Subtyping

By being Java compatible, Scala obviously has subtyping, while Haskell has not. Personally I'm on the fence whether subtyping is a good idea or not. On one hand it's quite natural and handy to be able specify that an interface is a subtype of some other interface, but on the other hand subtyping complicates type system and type inference greatly. I'm not sure the benefits outweighs the added complexity, and I don't think I'm the only one in doubt.

Modules vs Objects

The Haskell module system is very primitive, it's barely enough to get by with. In contrast Scala's object/module system is very powerful allowing objects to implement interfaces, mixin traits, bind abstract type members etc. This enables new and powerful ways to structure code, for example the cake pattern. Of course objects can also be passed around as values in the code. Objects as modules just feels natural IMHO.

Typeclasses vs Implicit Parameters

Typeclasses in Haskell and implicit parameters in Scala are used to solve basically the same problems, and in many ways they are very similar. However, I prefer Scala's solution as it gives the developer local, scoped control over which instances are available to the compiler. Scala also allows explicit instance argument passing at the call site which is sometimes useful. The idea that there is only one global type class instance for a given type feels too restricted, it also fits very badly with dynamic loading which I discuss in a later section. I also don't like that type class instances aren't values/objects/records in Haskell.

Scala has more advanced selection rules to determine which instance is considered most specific. This is useful in many cases. GHC doesn't allow overlapping instances unless a compiler flag is given, and even then the rules for choosing the most specific one are very restricted.

Lazy vs Strict Evaluation

Haskell has lazy evaluation by default, Scala has strict evaluation by default. I'm not a fan of lazy evaluation by default, perhaps because I've spent much time programming languages like assembly and C/C++ which are very close to the machine. I feel that to able to write efficient software you must have a good knowledge of how the execution machine works and for me lazy evaluation doesn't map well to that execution model. I'm simply not able to easily grasp the CPU and memory utilization of code which uses lazy evaluation. I understand the advantages of lazy evaluation, but being able to get predicable, consistent performance is a too important part of software development to be overlooked. I'm leaning more towards totality checking, as seen in newer languages like Idris, combined with advanced optimizations to get many of the benefits of lazy evaluation.

Type Safety

In Haskell side effects are controlled and checked by the compiler, and all functions are pure. In Scala any function/method can have hidden side effects. In addition, for Java compatibility the dreaded null value can be used for any user defined type (although it's discouraged), often resulting in NullPointerException. Also exceptions are used quite often in Java libraries and they are not checked by the Scala compiler possibly resulting in unhandled error conditions. Haskell is definitely a safer language to program in, but assuming some developer discipline Scala can be quite safe too.

Development Environment

The development environment for Scala is, while not on par with the Java's, quite nice with good Eclipse and IntelliJ plugins supporting code completion, browsing, instant error highlighting, API help and debugging. Haskell doesn't have anything that comes close to this (and no, Leksah is not there :-) ). And I don't buy the argument that you don't need a debugger for Haskell programs, especially for imperative code a good debugger is an invaluable tool. The developer experience in any language is much improved by a good IDE, and Scala is way ahead here.
Update: The EclipseFP Eclipse plugin for Haskell looks promising.

Runtime System

I like the JVM, it's a very nice environment to run applications in. Besides the state of the art code optimizer and garbage collectors, there are lots of tools available for monitoring, profiling, tuning, load balancing for the JVM that just works out of the box with Scala. Being able to easily load and unload code dynamically is also useful, for example in distributed computing.

Haskell has a much more static runtime system. I don't have much experience with runtime tools for Haskell, but my understanding it doesn't have the same amount of tools as the JVM.

Performance

The compilers for Haskell (GHC) and Scala (scalac) are very different. GHC performs quite complex optimizations on the code during compilation, while scalac mainly just outputs Java bytecode (with some minor optimizations) which is then dynamically compiled and optimized by Hotspot at runtime. Unfortunately things like value types and proper tailcall elimination, which are supported by GHC, are currently not implemented in the JVM. Hopefully this will be rectified in the future.

One thing Haskell and Scala have in common is that they both use garbage collection. While this is convenient in many cases and sometimes even necessary, it can often be a source of unnecessary overhead and application latency. It also gives the developer very little control over the memory usage of an application. GHC supports annotation of types to control boxing, and Hotspot does a limited form of escape analysis to eliminate heap allocation in some cases. However there is much room for improvement in both environments when it comes to eliminating heap allocations. Much can be learned from languages like Rust, BitCATS and even C++. For some applications it's critical to be able to have full control over memory management, and it's very nice to have that in a high level language.

Final Words

Haskell and Scala are both very powerful and practical programming languages, but with different strengths and weaknesses. Neither language is perfect and I think there is room for improvements in both. I will definitely continue to use both of them, at least until something better shows up. Some new interesting ones on my radar are Rust, ATS and Idris.

by Jesper Nordenberg (noreply@blogger.com) at May 09, 2012 10:18 PM

May 08, 2012

implicit.ly

ScalesXml 0.3-RC6

This is a feature release, adding a the full set of useful XPath Axe, string based XPath evaluation - via a popular open source XPath library, useful equality testing, a lot of new documentation and many smaller improvements in syntax and usability.

This version has been built with xsbt 0.11.x and migrated to github. This releases documentation can be found here and provides many examples on how to use Scales Xml.

All the Axe you'll ever need

Scales 0.3 adds the following axe:

  • preceding-sibling (preceding_sibling_::)
  • following-sibling (following_sibling_::)
  • descendant (descendant_::)
  • following (following_::)
  • preceding (preceding_::)
  • ancestor (ancestor_::)
  • ancestor-or-self (ancestor_or_self_::)
  • descendant-or-self (descendant_or_self_::)

This provides all of the XPath 1 and 2 axe (namespace axis excluded).

Enhanced internal XPath queries

  • position() (pos)

    pos\_<, pos\_==, pos\_>
  • last() (last)

    last\_<, last\_==, last\_>
  • position() == last() (pos_eq_last)
  • Easier to extend and re-use queries and axe

    xfilter, xmap, xflatMap

String base XPath evaluation

  • Evaluate normal XPath 1.0 strings to XmlPaths
  • Evaluates to an Iterable[Either[AttributePath, XmlPath]] or,
  • get[T] a value directly from XPath 1.0 (e.g. get[String]("normalize(//*)"))
  • Allows querying for the few predicates and XPaths that Scales cannot process (and dynamic queries of course)
  • Optional dependency

New xpath.Functions

  • Unified interface for XPath function handling
  • text, QName and Boolean typeclasses
  • Implementations for all relevant Scales Xml types

    • string( attribute ) makes sense whilst string( QName ) does not

New XmlComparison framework (2.9.x only)

  • Compare Xml structures and types
  • Customisable comparison rules
  • Default Scalaz === Equal type classes
  • XmlComparison type classes provide full details of differences:

    • A QName based path to the difference
    • The objects which are different

Extra Fun

  • Forwards and Backwards Path Iterators (used by following and preceding)
  • DuplicateFilter now works with the Scalaz Equal typeclass
  • Using AttributeQNames with the tuple arrow now creates QNames as you'd expect
  • DslBuilder allows direct manipulation of trees via folding
  • Simplify the Builder usage why /(<(Elem(... ) when you can just /(Elem)?
  • Java 1.7 JAXP implementation checks - Schema validation is optimised (no serialization)

How To Use

Scales 0.3 moves to Sonatype under the organisation org.scalesxml, with support for 2.8.1, 2.8.2, 2.9.1 and 2.9.2. As such add:

libraryDependencies ++= Seq(
  // just for the core library
  "org.scalesxml" %% "scales-xml" % "0.3-RC6"
  // or, use this instead for String based XPaths (Jaxen, also includes the core)
  "org.scalesxml" %% "scales-jaxen" % "0.3-RC6"
)

to your xsbt builds or use scales-xml_2.9.2 as the id when using Maven.

Scales Xml is an alternate xml library for Scala providing a coherent model, querying and manipulation via an XPath like syntax, better performance, highly customisable equality framework and an Iteratee based pull api.

via herald

Permalink

May 08, 2012 05:54 AM

sbt-buildinfo 0.1.2

Minor enhancements

  • sbt 0.11.3
  • Adds buildInfoBuildNumber. #2

sbt-buildinfo is a plug-in for sbt to generate Scala source from your build definitions.

via herald

Permalink

May 08, 2012 03:14 AM

sbt-assembly 0.8.1

minor enhancements

sbt-assembly is a plug-in for Simple Build Tool that creates a single jar of your project including all of its dependencies.

via herald

Permalink

May 08, 2012 02:54 AM

May 07, 2012

implicit.ly

scalariform 0.1.2

  • Revamp command-line tool with more intuitive behaviour
  • Add --quiet, --recurse, --stdin, --stdout options to command-line tool
  • FIX: Scaladoc comment formatting could break nested comments (issue #36)
  • Tidy up, optimise lexer code
  • FIX: Parse 5.f, 5.d as floating points, unless in Scala 2.11+ mode
  • FIX: Bug with line-per-annotation style
  • Add support for String interpolation
  • Add support for macros
  • Add --scalaVersion=<version> flag to command-line tool
  • Support expr[T1, T2][T3, T4] and g()[String] syntaxes
  • Fix AST selection for prefix expression

Scalariform is a source code formatter for Scala.

via herald

Permalink

May 07, 2012 09:20 PM

Coderspiel

implicit.ly

Configrity 0.10.1

Small maintenance release, including:

  • When loading a configuration from the classpath, a FileNotFoundException is thrown (issue #8) -- Martin Konicek
  • Looking for a non existing key will throw a NoSuchElementException with a message clearly refering to the missing key (issue #11) -- Jussi Virtanen
  • List values are sanitized by adding quotes when needed (issue #12)
  • Artefacts for Scala 2.9.2

If you wish for extra features, feel free to ask.

Configrity is a simple, immutable and flexible Scala API for handling configurations.

via herald

Permalink

May 07, 2012 08:02 AM

unfiltered 0.6.2

New Features

Multipart POST support for Netty

This substantial contribution by g-eorge handles file of uploads of arbitrary size, as previously supported only for filter plans. See the netty-uploads readme for details.

Migration Note: If you were using the unfiltered-uploads module before, you should now depend on unfiltered-filter-uploads. The former now serves as a base implementation for the filter and netty upload modules.

Kits

  • unfiltered.kit.Secure redirects HTTP requests to HTTPS.
  • unfiltered.kit.Auth requires basic auth for matching requests.
  • unfiltered.kit.AsyncCycle — removed this promise/future-aware kit for the time being

Extractors

Response Functions

Fixes

  • Issue 110 Keymanagers loaded redundantly for Netty bindings
  • Issue 111 TLS contexts created redudantly for Netty bindings
  • Issue 119 NoSuchElementException for parameterValues
  • Issue 123 Find path suffix only from path part of uri
  • Issue 126 Tiny fix in url generation for Jetty Https Server

Unfiltered is a toolkit for servicing HTTP requests in Scala.

via herald

Permalink

May 07, 2012 04:47 AM

May 06, 2012

Quoi qu'il en soit

Java, PowerMock and the slow death of pointless Interfaces


Back in the day, say around 2000, the use of Java interfaces were pushed as the one true way (tm) for expressing dependecies between classes. The established wisdom was that if one class needs another then it should be expressed as a dependency on an interface. There are two advantages to expressing dependencies via interfaces: (1) you can have a test implementation of the interface so you can unit test a class without using the real dependency (2) you can have multiple implementations of the interface, which might be chosen at runtime. In practice, (2) happens quite rarely, but  remains a completely valid case for interfaces use.


And so, the wisdom went, you were condemned to eternal damnation called a static method on another class. A call to a static method is hard wired like concrete and steel. No way to stub it out for unit testing.


Enter PowerMock in about 2008/2009 which works with EasyMock or Mockito and which allows you to mock pretty much anything:


"PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more. By using a custom classloader no changes need to be done to the IDE or continuous integration servers which simplifies adoption. Developers familiar with the supported mock frameworks will find PowerMock easy to use, since the entire expectation API is the same, both for static methods and constructors. PowerMock aims to extend the existing API's with a small number of methods and annotations to enable the extra features. Currently PowerMock supports EasyMock and Mockito."


I have seen PoweMock used a lot in several organizations. It just works(tm). I have noticed that it simplifies the way people write code. 


So, with PowerMock in hand, here is some advice for writing Java, that goes against established wisdom.


1) Don't write to interfaces unless you really need multiple implementations! Why create an interface and a class when just a class will do? If you find you really need an interface later then create one and use it. But remember most of the time, YAGNI for unit testing thanks to PowerMock. (where YAGNI means "you ain't gonna need interfaces" as opposed to the more traditional "you ain't gonna need it".)


2) Use EasyMock or Mockito for unit testing and the extras that PowerMock gives you if you need to. (I have nothing against JMock, and perhaps JMock has the equivalent features that PowerMock provides. )


3) Do not be afraid to use static methods if appropriate. When is appropriate? Now there's a question Rich Hickey would be happy to answer. 


Thanks to PowerMock, we are free to use interfaces where they are really needed.





by Tim Azzopardi (noreply@blogger.com) at May 06, 2012 10:17 PM

Coderspiel

flatMap Oslo (May 15, 16) is Norway’s first Scala...



flatMap Oslo (May 15, 16) is Norway’s first Scala conference, and the first anywhere to have such exciting light fixtures. (Good speaker lineup, too.)

May 06, 2012 02:39 PM

May 05, 2012

Quoi qu'il en soit

Examples of Java calling Oracle PLSQL anonymous blocks


Why would you do this? Answer: Developement agility

An Oracle DBA might say that Java should not use anonymous plsql blocks as (a) it embeds embeds database logic into Java code,  and (b) is bad for performance as a stored procedure would have a precompiled execution plan.

But in the organization where I am currently consulting:
  •  iBatis and hibernate (arguably)  embed database logic into Java applications. In theory its done in a "portable" way that is not tied to the database implementation. Like thats ever going to change!
  • Logistically and bureaucratically, it takes weeks to get a packaged stored procedure created and installed. In my experience this is typical of most large organizations that separate Java developers from database developers and dbas. The human communication in itself between the teams, creates a bottleneck.
  • The PLSQL blocks are stored in seperate files and loaded from files. Database gurus tweak the SQL and hand it over for complex queries and updates. 
  • Performance is actually not bad, because Oracle bind variables are used in the plsql. This means that oracle sees the same text every time and reuses execution plans.
  • Over time, if found to be durable, the PLSQL can be converted to a stored procedure and the anonmous plsql files are replaced with simple procedure calls.


Example 1: Call an anonymous PLSQL Block with one input string and one output string parameter :
  
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

public class CallPLSQLBlockWithOneInputStringAndOneOutputStringParameter {

// Warning: this is a simple example program : In a long running application,
// exception handlers MUST clean up connections statements and result sets.
public static void main(String[] args) throws SQLException {

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

final Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
String plsql = "" +
" declare " +
" p_id varchar2(20) := null; " +
" begin " +
" p_id := ?; " +
" ? := 'input parameter was = ' || p_id;" +
" end;";
CallableStatement cs = c.prepareCall(plsql);
cs.setString(1, "12345");
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();

System.out.println("Output parameter was = '" + cs.getObject(2) + "'");

cs.close();
c.close();
}
}
Java: Call an anonymous PLSQL Block with one input string and one output string parameter and one output cursor (query result) parameter :
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;

import oracle.jdbc.OracleTypes;

public class CallPLSQLBlockWithOneInputStringAndOneOutputStringParameterAndOneOutputCursorParameter {

public static void main(String[] args) throws Exception {

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

final Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
String plsql = "" +
" declare " +
" p_id varchar2(20) := null; " +
" l_rc sys_refcursor;" +
" begin " +
" p_id := ?; " +
" ? := 'input parameter was = ' || p_id;" +
" open l_rc for " +
" select 1 id, 'hello' name from dual " +
" union " +
" select 2, 'peter' from dual; " +
" ? := l_rc;" +
" end;";

CallableStatement cs = c.prepareCall(plsql);
cs.setString(1, "12345");
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, OracleTypes.CURSOR);

cs.execute();

System.out.println("Result = " + cs.getObject(2));

ResultSet cursorResultSet = (ResultSet) cs.getObject(3);
while (cursorResultSet.next ())
{
System.out.println (cursorResultSet.getInt(1) + " " + cursorResultSet.getString(2));
}
cs.close();
c.close();
}
}  

Example:  Call an anonymous PLSQL Block with one input string array and one output string parameter and one output cursor (query result) parameter :

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;

import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;

public class CallPLSQLBlockWithOneInputStringArrayAndOneOutputStringParameterAndOneOutputCursorParameter {

public static void main(String[] args) throws Exception {

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

// Warning: this is a simple example program : In a long running application,
// error handlers MUST clean up connections statements and result sets.

final Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
String plsql = "" +
" declare " +
" p_id string_array := null; " +
" l_rc sys_refcursor;" +
" begin " +
" p_id := ?; " +
" ? := 'input parameter first element was = ' || p_id(1);" +
" open l_rc for select * from table(p_id) ; " +
" ? := l_rc;" +
" end;";

String[] stringArray = new String[]{ "mathew", "mark"};

// MUST CREATE THIS IN ORACLE BEFORE RUNNING
System.out.println("(This should be done once in Oracle)");
c.createStatement().execute("create or replace type string_array is table of varchar2(32)");

ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor( "STRING_ARRAY", c );

Array array_to_pass = new ARRAY( descriptor, c, stringArray );

CallableStatement cs = c.prepareCall(plsql);
cs.setArray( 1, array_to_pass );
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, OracleTypes.CURSOR);

cs.execute();

System.out.println("Result = " + cs.getObject(2));

ResultSet cursorResultSet = (ResultSet) cs.getObject(3);
while (cursorResultSet.next ())
{
System.out.println (cursorResultSet.getString(1));
}
cs.close();
c.close();
}
}

Example: Call an anonymous PLSQL Block with one input structure array and one output string parameter and one output cursor (query result) parameter :

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;

public class CallPLSQLBlockWithOneInputStructureArrayAndOneOutputStringParameterAndOneOutputCursorParameter {

public static void main(String[] args) throws Exception {

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

// Warning: this is a simple example program : In a long running application,
// error handlers MUST clean up connections statements and result sets.

final Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
String plsql = "" +
" declare " +
" p_id student_array := null; " +
" l_rc sys_refcursor;" +
" begin " +
" p_id := ?; " +
" ? := 'input parameter first element was = (' || p_id(1).id_num || ', ' || p_id(1).name || ')'; " +
" open l_rc for select * from table(p_id) ; " +
" ? := l_rc;" +
" end;";


// MUST CREATE ORACLE TYPES BEFORE RUNNING
setupOracleTypes(c);

StructDescriptor structDescr = StructDescriptor.createDescriptor("STUDENT", c);
STRUCT s1struct = new STRUCT(structDescr, c, new Object[]{1, "mathew"});
STRUCT s2struct = new STRUCT(structDescr, c, new Object[]{2, "mark"});
ArrayDescriptor arrayDescr = ArrayDescriptor.createDescriptor( "STUDENT_ARRAY", c );
Array array_to_pass = new ARRAY( arrayDescr, c, new Object[]{s1struct, s2struct} );

CallableStatement cs = c.prepareCall(plsql);
cs.setArray( 1, array_to_pass );
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, OracleTypes.CURSOR);

cs.execute();

System.out.println("Result = " + cs.getObject(2));

ResultSet cursorResultSet = (ResultSet) cs.getObject(3);
while (cursorResultSet.next ())
{
System.out.println (cursorResultSet.getInt(1) + " " + cursorResultSet.getString(2));
}
cs.close();
c.close();
}

private static void setupOracleTypes(final Connection c)
throws SQLException {
System.out.println("(This should be done once in Oracle)");
try {
c.createStatement().execute("drop type student_array ");
} catch (Exception e) {
// ignore
}
c.createStatement().execute("create or replace type student as object (id_num integer(4), name varchar2(25))");
c.createStatement().execute("create or replace type student_array is table of student");
}
}

by Tim Azzopardi (noreply@blogger.com) at May 05, 2012 09:09 PM

implicit.ly

robot-vision 0.0.2

  • Better recording handling #1
  • Removed Pesky timeout errors when in jpeg mode #2
  • Page title is now the machine hostname #3
  • Added clipboard setting and retrieval of host machine 231200
  • Added popout interface for quality and scaling remote image d09140
  • Added Swing UI 4b3ae9
  • More js keycodes handled 86355b

Upgrading

CLI users can upgrade using cs by running the following command:

` cs philcali/robot-vision `

Robot Vision Control (RVC) is an embedded unfiltered web server allowing remote control over the host machine similar to RDP and VNC, except control is handled at the http transport layer.

RVC's source is hosted on github. Detailed installation and usage information can be found in the project's README.

Chrome browsers and Chromebooks can take advantage of the extension for subvert control connections and managing host URL's. Conveniently install the extension at the Chrome webstore.

via herald

Permalink

May 05, 2012 06:50 AM

May 04, 2012

Detering Dirk

Functors, Monads, Applicatives – different implementations

In the previous blog post I claimed that Functors, Monads and Applicatives can be presented in an easily comprehensible way:

a) ( A=>B )      => ( C[A]=>C[B] )   | Functor
b) ( A=>C[B] ) => ( C[A]=>C[B] )   | Monad
c) ( C[A=>B] ) => ( C[A]=>C[B] )   | Applicative

Thus they are perceived  as transformations/conversions from some function type involving an A and a B to the type C[A]=>C[B] .

We then created a container MyBox, which can keep a value of some type, and some functions which implemented the above mentioned signatures.

For example the Functor transformation was implemented as a standalone function named map :

def map[A,B]( rawfunc:A=>B ) : MyBox[A]=>MyBox[B] = (a:MyBox[A]) => new MyBox( rawfunc(a.value) )

But what I want you to understand in this post, is that this -map as a function taking a function- is only one possible implementation, and that there are very different ways to structure the concept represented by the function map . This is much more true for Scala, which is a feature rich hybrid OO-FP language. To demonstrate this, let’s stay with Functors and the shown map function. What you see here will be applicable for the other concepts, Monad and Applicative, too.

First, let us again have a look at the signature of map:

( A=>B ) => ( MyBox[A]=>MyBox[B] )

According to this signature, map takes a function of type A=>B and returns a function which takes a MyBox[A].  In the end the result is of type MyBox[B]. The second pair of parens can easily be left out:

( A=>B ) => MyBox[A] => MyBox[B]

What we now see is a curried form that we can transform back into a multi-parameter function:

((A=>B), MyBox[A]) => MyBox[B]

We now have a function taking two parameters -a function A=>B and a MyBox[A]- and resulting in MyBox[B]. In such a case the order of the parameters isn’t really important, so we can change that easily to

( MyBox[A],(A=>B)) => MyBox[B]

what in curried form again is

MyBox[A] => (A=>B) => MyBox[B]

Let’s take our first implementation and adapt that according to this signature:

def map[A,B](a:MyBox[A]): (A=>B)=>MyBox[B] = (rawfunc:A=>B) => new MyBox( rawfunc(a.value) )

Now map first takes the container to work on and then returns a  function that is bound to that container, but  expects as parameter the bare typed function which shall be applied to produce the result.

This is a signature for map that you will also find in articles, either as a primary way to implement it, or as a helper function, delegating to  the other signature (like here).

So far the class MyBox and the function map are only loosely related, i.e. the function map can be located anywhere in our code base. To organize it better and document the relationship of map with MyBox, we could possibly declare it as a method on a companion object:

object MyBox {
 def map[A,B](a:MyBox[A]): (A=>B)=>MyBox[B] = (rawfunc:A=>B) => new MyBox( rawfunc(a.value) )
}

Much more, if we have a function that takes an instance of some class as its first parameter, this is only a functional way to describe a method, which in classical OO would belong to the class itself. So the signature

(MyBox[A],(A=>B)) => MyBox[B]

is a hint, that maybe map should be implemented like this:

class MyBox[A](val value:A) {
 def map[A,B](rawfunc:A=>B) = new MyBox( rawfunc(this.value) )
}

So now we can call map directly on an instance of MyBox:

val n = new MyBox("hello")
n.map( (a:String)=>a.length ).value // -> 5

This is a nice way to implement Functors and Monads in case you are the class’ author and have such features already in mind. As you may know, Scala’s for-comprehension is only syntactic sugar for calls to map and flatMap on instances. Therefore our class can be used inside such expressions too.
Another Scala-typical way to provide methods on objects although their class does not implement them are wrapper classes and implicit conversions. How this would look like for our MyBox, you see below, including also the Monad method flatMap.

class MyBox[T](val value:T) {
   override def toString() = "MyBox("+value+")"
}

class MyBoxWrapper[T](w:MyBox[T]) {
    def flatMap[R](f:T=>MyBox[R]) = map(f).value
    def map[R](f:T=>R) = new MyBox(f(w.value))
}

object TestMonadWrapper {
    implicit def myBoxToWrapper[S](mb:MyBox[S]) = new MyBoxWrapper[S](mb)

    def main(args:Array[String]) {
        val ma = new MyBox("hello world")
        println ( ma.map((a) => a.length) )

        val res = for {
                    a <- ma
                  } yield a.length + 2

        println(res)

        val mb = new MyBox("hola mundo")

        val res2 = for {
                     a <- ma
                     b <- mb
                   } yield a.size + b.size

        println (res2)
    }
}

This is an extended example, so let’s have a walk-through.  Class MyBox implements a toString Method to allow for convenient printing on console, so we don’t have to call .value to see what the value is. MyBox does not implement the methods map and flatMap itself, but we have a wrapper class MyBoxWrapper that implements them for us. Our application object TestMonadWrapper contains some tests in the main method, and an implicit conversion that wraps a MyBox instance into a MyBoxWrapper whereever the methods map and flatMap are called on a MyBox instance. This is the case for ma and mb inside the for-comprehensions.

Last but not least Scala also knows typeclasses -not as a language feature but as a pattern-, which are just another way to provide function implementations for specific types, a concept taken from Haskell. I don’t want to dive into that matter here now. To see Monads implemented as a typeclass, have a look into Daniel Spiewak’s article Monads are not metaphors , where the concept Monad is shown as a trait, implemented by two implicit objects for different types, or at Eric Torreborre’s article The Essence of the Iterator Pattern, where he demonstrates Functor and Applicative as typeclasses right from the beginning.

In my examples you have so far always seen the functions named map, flatMap and apply. The first two match with how the Scala standard library is implemented and the for-comprehension works. But the name apply must be taken with care, as this is in Scala a conventional method to use object references like functions.

Indeed, other languages implement the concepts of Functor, Monad and Applicative too but use other names for the functions. Namely in Haskell, the source of those ideas, the methods are named differently and sometimes confusingly for a Scala developer. So is the method map named fmap there, not to be confused with Scala’s flatMap, which is named bind in Haskell. Beside that, Haskell uses even symbolic names for the functions.

Another blog post which I found recently and which presents Functors, Monads and Applicatives in a similar reduced way like my first post, is Functors, Applicative Functors, and Monads aren’t that scary. The author took the Haskell function names for Scala too.

All in all, the names are of no importance.  Much more, have a look at the signatures to recognise the patterns shown in the first post, even when they are mutated, like seen in this post.

In the next post we will look at the three function signatures of the first post again, and think about how it comes that we would need flatMap and apply.


Filed under: FunctionalProgramming, Scala

by thedetdev at May 04, 2012 08:49 PM

Mirko Socker

Detecting and Naming Boolean Parameters

After a recent discussion on the Scala-Internals mailing list on the pros and cons of methods that take boolean arguments, the consensus was that they should always be passed as named arguments. The compiler doesn’t enforce this, so it’s up to us IDE and tools developers to provide a solution. The code-analysis branch for the Eclipse Scala IDE can now warn you of such boolean arguments that are passed to Scala methods:

The warning comes with a quick-fix that inserts the parameter name:

Of course, the competition isn’t sleeping either, the IntelliJ Scala plug-in just got a bunch of new Intentions.

<g:plusone href="http://misto.ch/detecting-and-naming-boolean-parameters/"></g:plusone>

by Mirko Stocker at May 04, 2012 06:00 PM

May 03, 2012

implicit.ly

markwrap 0.5.4

  • Added Scala 2.9.2 to the list of cross-built versions.

The MarkWrap library (pronounced "mark wrap" or "more crap", depending on your preference) is a Scala library that provides a unified API for using various underlying lightweight markup APIs. Currently, it supports:

See the MarkWrap web site for more details.

via herald

Permalink

May 03, 2012 05:20 PM

classutil 0.4.6

  • Added Scala 2.9.2 to the set of crossbuilds.

The org.clapper.classutil (ClassUtil) library is a Scala package that provides various class location and class generation capabilities, including:

  • Methods to locate and filter classes quickly, at runtime--more quickly, in fact, than can be done with the JVM's runtime reflection capabilities.
  • Methods for converting Scala maps and objects into Java Beans, on the fly--which can be useful when generating data for use with APIs (e.g., template APIs) that accept Java Beans, but not maps.

See http://software.clapper.org/classutil/ for details.

via herald

Permalink

May 03, 2012 05:10 PM

grizzled-slf4j 0.6.9

  • Added Scala 2.9.2 to list of cross-compiled targets.

The Grizzled SLF4J package provides a very thin Scala-friendly layer on top of the SLF4J (Simple Logging Facade for Java) API.

via herald

Permalink

May 03, 2012 05:02 PM

avsl 0.4

  • Added Scala 2.9.2 to the set of cross-built versions.

AVSL is a very simple logger, written in Scala. AVSL implements the Simple Logging Facade for Java (SLF4J) API, allowing applications to be written to the SLF4J API, for portability. It uses a simple, non-XML configuration file.

via herald

Permalink

May 03, 2012 04:52 PM

argot 0.4

  • Added Scala 2.9.2 to the set of cross-built versions.

Argot is a command-line parser library for Scala, supporting:

  • single-value and multi-value options
  • single-value and multi-value parameters
  • flag and non-flag options
  • GNU-style long options, (i.e., "--option")
  • POSIX-style short options, (i.e., single "-" lead-in), with option grouping (e.g., "tar -xcf foo.tgz")
  • automatic parameter conversion (i.e., values with non-string types, with automatic conversion)
  • the ability to supply your own conversion functions

You can find complete details, including usage information, on the Argot home page.

via herald

Permalink

May 03, 2012 04:36 PM

grizzled-scala 1.0.13

  • Cross-compiled for Scala 2.9.2.

The Grizzled Scala Library contains a variety of miscellaneous utility classes and objects. Basically, whenever I find myself writing something that's general-purpose, I put it in here, so I can easily use it in multiple projects.

via herald

Permalink

May 03, 2012 04:26 PM

May 02, 2012

implicit.ly

shapeless 1.2.1

A minor release of shapeless. The main changes include,

  • Added HList flatMap.
  • Various small tweaks to accommodate both Scala 2.9.x and Scala >= 2.10.0-M3.
  • Restructured project as an aggregate of a core and an examples project.
  • Generated and example source now included in source artifact.
  • Improved build configuration,

    • Updated to SBT 0.12.0-Beta2.
    • Added SBT cross build for 2.10.0-M3

shapeless is an exploration of type class and dependent type based generic programming in Scala.

A series of articles on the implementation techniques used will appear here and it also has a mailing list.

via herald

Permalink

May 02, 2012 09:48 PM

treehugger 0.1.3

bug fixes and minor enhancements

  • Fixes when TYPE_TUPLE(type) is called with one element. #14 reported by @psnively
  • Adds TYPE_EITHER(typ1, typ2), TYPE_LEFT(typ1, typ2), TYPE_RIGHT(typ1, typ2).
  • Adds RIGHT(tree) and LEFT(tree).

treehugger.scala is a library to code Scala programmatically.

via herald

Permalink

May 02, 2012 09:20 PM

May 01, 2012

Jim McBeath

Git Rebase Across Many Commits

Not all git merge conflicts are real.

Contents

The Scenario

In both my personal and my work projects I prefer to use git rebase to keep my commit histories simple and readable. To make this work in a team setting, we never work on the master branch, instead always working on a feature branch in our local repositories. Our process flow looks something like this:
$ git branch feature           #create the working branch
$ git checkout feature          #do all development work on that branch
#Edit files, etc.
$ git commit -m "Implement Feature"
#Repeat the above as desired during development.
#When ready to merge to master, do the following:
$ git checkout master
$ git pull                      #update master from shared repository
$ git checkout feature
$ git rebase master             #optionally with -i if squashing is desired
$ git checkout master
$ git merge feature
$ git push origin master
$ git branch -d feature
Because we never use our local master branch for development, the git pull on master is always a fast-forward merge. Likewise, because we have just rebased the feature branch against the master right before we merge that feature branch back into master, that merge is also always a fast-forward merge. Looking at it another way, we don't have any merge conflicts when updating or merging master because we resolve all of the merge conflicts when we rebase the feature branch against the latest master.

The Problem

At work, we have a large codebase and a handful of active developers who typically merge feature branches to the master using the above workflow multiple times each day. Sometimes somebody has a feature branch that takes a long time to finish, so that between the time that branch was started and the time it is ready to go into master, there may have been 40 or 50 other commits made to master. In general in this situation we will occasionally rebase our local feature branch against the latest master a few times during feature development, but inevitably there are occasions when a large rebase across many commits ends up being done.

Even if there are many commits on the master branch, if none of those commits touched any of the same code as the commits on the feature branch, then there should be no merge conflicts when rebasing the feature branch against the updated main branch. However, in my experience this has not always been the case. Sometimes git rebase reports merge conflicts when I think there should not be any. Since I don't generally know exactly what code the other team members have edited, I can't immediately tell if the merge conflicts make sense.

The normal advice for how to handle merge conflicts is to edit the named file, look for the conflict markers, inspect the conflicting code fragments, determine what to keep, edit out what is not being kept along with the conflict markers, git add the repaired file, and git rebase --continue to let it tell you about the next merge conflict.

That's a lot of work, and it might all be completely unnecessary.

The Solution

It seems that git sometimes just gets confused when doing a rebase across a large number of commits. Sometimes if you rebase in smaller steps, git will happily rebase each smaller step with no merge conflicts, until you have stepped all the way up to the latest master, at which point your rebase is done.

You could rebase against every single commit and work your way up to master, but that, too, is a lot of work. Here's what I do when the initial rebase of the feature branch against the latest master tells me there are merge conflicts.

When the initial git rebase reports a merge conflict, I immediately do git rebase --abort to undo that rebase attempt. Using gitk --all to view the commit tree, which lets me see the master branch and the commit at which my feature branch branches off the master branch, I select a commit on the master branch about half way between those two commits. I copy the commit ID and paste it into a rebase command that looks something like this:
$ git rebase 8bc85584989e4435c2d98b13447bcab37648ba7f
If this rebase reports no merge conflicts, then I try rebasing against master and repeat the process.

If there are merge conflicts, then I abort the rebase and pick another commit half way again to the branch point. I repeat this until either the rebase succeeds or I am trying to rebase across a single commit. At that point, if there are still merge conflicts, they are real and I address them in the normal way. Since the conflict is only across a single commit, it is easier to see the cause of the conflict and to resolve it.

After resolving the conflict across that one commit, I go back to the first step and try rebasing against master again, repeating the process.

I have followed this process a number of times. I think that a majority of these times I binary-divide my commits a few times and end up piecemeal stepping through the commits until I have rebased against master without ever having to resolve any conflicts. The other times I typically have to resolve one or two small conflicts, after which I can rebase against master.

The next time you do a rebase across more than one commit and git tells you there are merge conflicts, try this approach. You might save yourself a lot of work.

by Jim McBeath (noreply@blogger.com) at May 01, 2012 05:40 AM

April 30, 2012

Coderspiel

scala-lang.org

Scala 2.10.0 Milestone 3

A new milestone release for Scala is now available. This release is cut directly from current development and is not intended for production environments, but is a great chance to try out the up and coming features for Scala 2.10.0. The milestone 2.10.0-M3 includes many fixes and improvements, listed below.

by admin at April 30, 2012 12:15 PM

April 29, 2012

implicit.ly

giter8 0.4.5

This release improves support for github OAuth. The previous release did not request the proper scope for private repositories. If you already obtained a token, or wish to switch from name and password auth, then run g8 with your github name and password separated by a : character:

g8 --auth yourname:yourpass

If successful, this command stores an access token in ~/.g8/config which is used for all future g8 invocations. You can revoke tokens at any time in your github account settings.

To upgrade giter8 using Conscript:

cs n8han/giter8

giter8 is a command line tool to apply templates defined on github

via herald

Permalink

April 29, 2012 07:28 PM

scallop 0.3.8

This version includes the following improvements:

  • added cross-publishing for Scala 2.9.2
  • fixed bug with help and version info printing
  • added reading of options from stdin or from file
  • fitted ScallopOption to be usable in for-comprehensions
  • Removed the need to call verify at the end of each ScallopConf object - it now happens auto-magically

Scallop is a simple (yet powerful) command-line arguments parsing library for Scala.

via herald

Permalink

April 29, 2012 07:01 AM

April 28, 2012

Detering Dirk

Functors, Monads, Applicatives – can be so simple

When I started trying to get into these weird topics named “functors” and “monads” and so on, which came up in the Scala mailing list, I was more than slightly confused [1]. I read some articles (in the beginning not many existed), listened to mails, consulted book chapters, and even started learning Haskell to consult the very fine “Learning a Haskell for great good” chapters on that matters. Different authors use different ways to explain -and implement!- these concepts, what in the end is helpful. You can read an article, think, read some other perspective, come back to the first article again, a.s.o.

But it took some time to realise how darn simple it all can be in principle (and took more time to finally write about it). I worked with and restructured some examples until the simplicity of it all became obvious. So let me now present you my perspective on it, and perhaps it will help you to get into these seemingly strange things:

Given some type constructor C[_] and two types A and B, we want to apply functions of type C[A]=>C[B] .
Unfortunately we have only functions of types A=>B,  A=>C[B] and C[A=>B] at hand, so we need adequate transformations for them:

a) ( A=>B ) => ( C[A]=>C[B] )
b) ( A=>C[B] ) => ( C[A]=>C[B] )
c) ( C[A=>B] ) => ( C[A]=>C[B] )

All these are transformations of some given functions into the function type we need, and all these transformations even have names.

a) ( A=>B )      => ( C[A]=>C[B] )   | Functor
b) ( A=>C[B] ) => ( C[A]=>C[B] )   | Monad
c) ( C[A=>B] ) => ( C[A]=>C[B] )   | Applicative

That is the pattern we have to learn by heart and keep in mind. All other is simply applying that pattern, present it in different forms and implementations [2].

Too fast? Too abstract?
Ok, now that you surely have learned this scheme by heart and can reproduce it without spiking into this article, we’ll have a closer look at how and why that works.
It all starts with a container of some type C, which is able to hold one or more values of some type A. So we have C[A] to start with.
The container itself can serve different purposes. We will come back to that in a  follow-up post.
To keep things easy for now, let’s start with the most simple: A box.

class MyBox[T](val value:T)

Then we can put a value of some type into such a box, for example a string.

val boxedstring:MyBox[String] = new MyBox("Hello")

Now we want to apply some computation or transformation on the value (type A) in C, without leaving C. That means, the result value of some type B shall also be in a C. In other words: We want to apply functions of type C[A]=>C[B].

In our example: Let’s assume we want to compute the length of the string in MyBox, and get the result again in MyBox. This would need a function of type MyBox[String] => MyBox[Int], which would calculate the lenght but somehow stay inside the box:

def lengthOf( a:MyBox[String]) : MyBox[Int] = ....

The problem is that we already have some interesting computations -like the length of a string- at hand, but they are not of the correct type. They are of much more functions on the raw types A=>B, or functions of type A=>C[B] or even the raw functions already wrapped in C, resulting in C[A=>B] (Why that is, we talk about later).

In our example, we have a function:

def rawLengthOf(a:String) : Int = a.length

We can see, that we need to transform it. So let’s write a transformation for it:

def map[A,B]( rawfunc:A=>B ) : MyBox[A]=>MyBox[B] = (a:MyBox[A]) => new MyBox( rawfunc(a.value) )

Let’s look closer into it: map is a function that takes another function of the raw types A=>B as parameter and returns a new function that takes a MyBox[A], applies the raw function, and wraps the result in a MyBox again.

Now let us put all these things together:

class MyBox[T](val value:T)

def map[A,B]( rawfunc:A=>B ) : MyBox[A]=>MyBox[B] = (a:MyBox[A]) => new MyBox( rawfunc(a.value) )
 val boxedstring:MyBox[String] = new MyBox("Hello") // a boxed value

def rawLengthOf(a:String) : Int = a.length // the raw function we want to use

val transformedLenghtOf = map(rawLenghtOf) // applying the transformation, so we get our new function

val result:MyBox[Int] = transformedLengthOf( boxedstring ) // applying the new function

So we have a MyBox[_], and we have a map function for MyBox. Congratulations, this is your first Functor!

The other two examples work similarly.

We start with our boxedstring again, but then we have:

def lengthOf(a:String) = new MyBox( a.length ) // a function which takes a raw type but boxes the result itself

Why such things can happen, we will see later.

So we need a new transformation:

def flatMap[A,B]( func:A=>MyBox[B] ): MyBox[A]=>MyBox[B] = (a:MyBox[A]) => func( a.value )

flatMap is a function that takes a semi-raw function of type A=>MyBox[B] -e.g. String=>MyBox[Int]-, and returns a new function that takes a MyBox[A], applies the semi-raw function and simply returns its result.

The rest now looks almost the same:

val transformedLenghtOf = flatMap(lenghtOf) // applying the transformation, so we get our new function

val result:MyBox[Int] = transformedLengthOf( boxedstring ) // applying the new function

Again: We have a MyBox[_], and we have a flatMap function for MyBox.
This, my dear, is a Monad!

The third pattern shouldn’t be much of a problem here.

Again we start with our boxedstring, but now we found our rawLengthOf again, surprisingly itself boxed in a MyBox:

val boxedLengthOf:MyBox[String=>Int] = new MyBox( rawLengthOf _ )

But this is no problem, we only need another converter, this time without any “map” in its name.

def apply[A,B](b:MyBox[A=>B]): MyBox[A]=>MyBox[B] = (a:MyBox[A]) => new MyBox(b.value(a.value))

apply now is a function that takes a boxed raw function and returns a new function that takes a MyBox[A], applies the unboxed raw function to its unboxed value, and returns the result in a new box.

val transformedLenghtOf = apply(boxedLenghtOf) // applying (*haha*) the transformation, to get our new function
val result:MyBox[Int] = transformedLengthOf( boxedstring ) // applying the new function

Applicative on stage!

Let’s sum it up by listing all these transformations together. All transformations result in MyBox[A]=>MyBox[B], so I will leave this type away:

class MyBox[T](val value:T)

//Functor
 def map[A,B] ( rawfunc:A=>B ) = (a:MyBox[A]) => new MyBox( rawfunc(a.value) )

// Monad
 def flatMap[A,B]( func:A=>MyBox[B] ) = (a:MyBox[A]) => func( a.value )

// Applicative
 def apply[A,B] ( b:MyBox[A=>B] ) = (a:MyBox[A]) => new MyBox(b.value(a.value))

So far for the basic stuff. In the next article we will talk about alternative ways to implement such concepts in Scala, so we are able to recognise them, no matter how they are implemented or how the transformation functions are named.

[1] “A Monad is a monoid in the category of endofunctors” became a popular term of debate about the usefulness of such explanations.
[2] Well, there may be more about the theoretical concept of Functors, Monads and Applicatives -and Category Theory- but that is all you need to know to start.


Filed under: FunctionalProgramming, Scala

by thedetdev at April 28, 2012 05:37 PM

April 25, 2012

Detering Dirk

y ( is ( 6 afraidOf 7 ) )

Or: What happens when a simple number joke meets a bored Scala developer …

Save the following code into a file, e.g. named Fears.scala.

type Reason = () => String

class ReasonedState(val state:Boolean, val reason:Reason)

case class True(why:Reason)  extends ReasonedState(true, why) {
   override def toString() = "yes"
}
case class False(why:Reason) extends ReasonedState(false, why) {
   override def toString() = "no"
}

class Fears(value:Int) {
   def afraidOf(other:Int) = (value,other) match {
      case (6,7) => True (() => (7 to 9).toList.map(_.toString).reduce(_+" "+_))
      case _     => False(() => "nothing to fear")
   }
}

implicit def numbersFears(nu:Int) = new Fears(nu)

def is(rs:ReasonedState) = rs
def y (rs:ReasonedState) = rs match {
    case rs:True => "because "+rs.reason()
    case _       => "wrong question"
}

Then open the Scala REPL in the same directory as the file you saved and type:

scala> :load Fears.scala

Now type:

scala > y ( is ( 6 afraidOf 7 ) )

…and enjoy the result.

Tip: If you don’t already know it, read the input and the result aloud (in english).


Filed under: Scala, Uncategorized

by thedetdev at April 25, 2012 05:49 PM

scala-lang.org

Scala Training

Many Scala training courses are now available, reflecting the constantly growing interest in the Scala programming language and its ecosystem. The courses that are now on offer include a range of introductory as well as advanced Scala training courses, as well as courses on Akka and Play, delivered by Typesafe and partners, by Underscore Consulting, by tune-it, Escalate Software, and others. You can find below a detailed list of opportunities to get professional Scala training close to your location.

by cunei at April 25, 2012 03:47 PM

April 19, 2012

Coderspiel

@jorgeO Parachuted into into enemy territory



@jorgeO Parachuted into into enemy territory

April 19, 2012 05:36 PM

April 17, 2012

Coderspiel

At first I was worried Viktor did not have a funny t-shirt but...



At first I was worried Viktor did not have a funny t-shirt but then he took off his Akka hoodie.

April 17, 2012 10:38 AM

April 15, 2012

Coderspiel

robot-vision 0.0.1 - implicit.ly

robot-vision 0.0.1 - implicit.ly:

Robot Vision Control (RVC) is an embedded unfiltered web server allowing remote control over the host machine similar to RDP and VNC, except control is handled at the http transport layer.

The client is a Chrome extension. This is rad.

April 15, 2012 02:18 AM

April 14, 2012

Mirko Socker

Quickfix to Expand Case-Class Bindings in Pattern Matching

When writing Scala code that involves pattern matching I often work with (nested) case classes and sequences of case classes. I usually start with a simple binding like this

case class Person(firstName: String, lastName: String)

List(Person("Mirko", "Stocker")) match {
  case person :: Nil =>; ...
}

and then when I need to access members of the matched class convert it to use the extractor:

List(Person("Mirko", "Stocker")) match {
  case Person(firstName, lastName) :: Nil => ...
}

What’s tedious about that step is that one needs to know how many arguments there are and name all the bindings. But not for much longer! I wrote a quick-fix for the Scala IDE that does this for you:

Ctrl+1 brings up the available quick fixes:

And this is what happens when the binding you’re expanding is used in the pattern’s body:

It also works if you use a typed pattern where the type is a case class:

This feature isn’t in the recently released Milestone 1, but it should be part of the next one (or one of the upcoming nightly builds). Suggestions for a better wording – expand case class binding – are welcome :-)

<g:plusone href="http://misto.ch/expand-case-class-bindings-in-pattern-matching/"></g:plusone>

by Mirko Stocker at April 14, 2012 08:03 PM

April 13, 2012

scala-lang.org

Scala IDE 2.1 Milestone 1 available now!

Today we released an early preview of the Scala IDE V2.1 for Eclipse! While the goal of V2.0 was to provide a reliable environment for your Scala coding, with V2.1 we want to bring your Scala development experience to a whole new level.

In this milestone there are a whole lot of new features for you to try out: implicit highlight, move refactoring, scala debugger and semantic highlight are the most exciting ones. If you are like us, once you start using them you will no longer be able go back. They are simply too addictive!

Read more...

by dotta at April 13, 2012 03:19 PM

Scala 2.9.2 final

A new stable release of Scala is available for download! Many thanks to all our contributors and testers. You can find the new Scala 2.9.2 on our Download Page. This new release addresses several bugs, and introduces additional improvements; you can find the full description below.

by admin at April 13, 2012 02:35 PM

April 09, 2012

Coderspiel

Making Meetup: Meetup Futurism

Making Meetup: Meetup Futurism:

makingmeetup:

There are some features on Meetup that, while valuable, are enhancements to the core experience. We wouldn’t want these sometimes memory- and processor-intensive features to prevent someone from doing something as important as RSVPing to a Meetup. Because of this, these features have been…

Everybody needs a ListenableFuture interface.

April 09, 2012 05:28 PM

giter8 0.4.2 - implicit.ly

giter8 0.4.2 - implicit.ly:

Because github is terminating its v2 APIs on May 1, 2012 and these are used by all earlier versions of giter8, you must upgrade in order to continue using the software.

Go ahead and upgrade now, before you forget and github terminates the APIs and you open a bug against giter8 and I get even more annoyed about this whole situation.

April 09, 2012 03:24 AM

April 05, 2012

scala-lang.org

Scala 2.9.2 RC3

A new Release Candidate in the Scala 2.9.x series is now available for download: 2.9.2 RC3. This release includes many bugfixes, as well as backported documentation and scaladoc improvements from the community.

This RC3 release candidate is made available for testing purposes only and is not intended for production environments: a final 2.9.2 release will follow at the end of the RC cycle. Please help us with the testing of this candidate, and let us know of any issues that you may encounter.

by admin at April 05, 2012 02:12 PM

April 01, 2012

Coderspiel

Testing Scala Libraries

In the course of developing some Scala libraries that have stuck around, I’ve generally found it helpful to users if I release artifacts compatible with the two most recent major versions of Scala. So at the moment I support everything between 2.8.0 and 2.9.1-1.

Binary compatibility across minor Scala versions can lessen the burden, but as long as the language continues to evolve there will be transition periods where libraries must support more than one major version. Instead of scrambling to handle multiple publishing targets every time this happens, it’s safer and easier to handle them always with the automation known as cross-building. This feature of sbt runs a build against a set of Scala versions and publishes distinctive artifacts, so that sbt can also retrieve artifacts that are compatible with a particular version of Scala.

The same is true, it would seem, for test frameworks. You need to run tests against your own library for all the versions of Scala you claim compatibility with. If you can’t use your test framework with a Scala version, you’re out of luck—and so are your users.

~~~

Since I’m starting fresh with Dispatch reboot I’m also starting fresh on its tests. There’s a lot of interesting efforts going on in testing Scala and I thought, surely, I could find one that is built for the different versions of Scala I support. But that’s just not the case. I tried the usual suspects, as well as every upstart Scala testing framework I could find, and none of them are being dependably cross-published.

I was almost ready to switch to JUnit, which I have never actually used for anything—but hey, it works for Foursquare. Then I remembered to ask Josh Cough what to do. And he told me (as he told me a few years ago when I wasn’t ready to listen) to just use ScalaCheck.

Obviously, ScalaCheck is not cross-built and published for every version of Scala that I support but it has one big advantage: no dependencies. You can generally build it without a lot of drama. And that made me realize that the answer has been there since sbt 0.10: source dependencies.

In their local form, source dependencies are unarguably practical. I’ve never had a better workflow for developing both a library and client application at the same time: you save one file in the library and all dependent sources in both projects are recompiled.

The remote form of source dependencies is more ambitious, and also trickier. In the most common case you specify a git URL that references a specific commit and sbt will clone that project and build it locally. The tricky part is that although the project is okay to build in sbt, it’s in a strange new world when it comes to distribution.

You can’t publish the project’s binaries to a Maven repository. And if you’re building a WAR or a JAR or something else, it’s unlikely that the source dependency’s classes are going to end up in that archive without some gnashing of teeth your sbt build definition. About the only thing you can do in a straightforward way is have your project be used as a source dependency by something else, which is neat but unpopular.

With test dependencies, we just don’t have the problem. Test artifacts aren’t meant to be distributed, they’re meant to be run locally by the project contributors. After the compiled tests pass, you don’t worry about them or their dependencies. Your work is done.

So using test frameworks with a library is the perfect use case for source dependencies, and ScalaCheck with its uncomplicated build the perfect source dependency. I did have to fork the repo to make some superficial changes. Incompatibilities with Scala 2.8 were introduced at some point, so I rewound to the last version tag before that and back-ported the sbt 0.11 build definition, which took all of five minutes. I pushed my changes to a fork on github and that was it.

But the configuration for this on the client library side is not-obvious, and I went though a few ugly iterations of it before I came up with something fairly short and sweet. Here’s the crux of it:

lazy val ufcheck = Project(
  "ufcheck", file("ufcheck")
).dependsOn(scalacheck % "test->compile")

lazy val scalacheck = RootProject(
  uri("git://github.com/n8han/scalacheck.git#1.8cc")
)

(If it looks weird it’s because it’s doing something amazing that you can’t do any other way.) ufcheck is some test code that I use in other modules, but you can pretend it’s a library module that just needs to use ScalaCheck. Its dependsOn clause sets a test dependency on the compile classpath of ScalaCheck, which is exactly what we need to do.

The scalacheck reference points to my fork and a tag “1.8cc”, which is my way of saying it’s version 1.8 with a build that cross-compiles.

And that’s it. Dispatch reboot is testable for life. No matter what happens in the future, it can be tested against different versions of Scala without asking anybody to publish anything.

Since Scala 2.10 is right around the corner I can start thinking about dropping support for 2.8 and updating this source dependency to a newer tag of ScalaCheck, if I feel like it. Or I can support 2.8 through 2.10—whatever! My build is flexible, that’s the whole point.

If only the same trick worked on everything.

April 01, 2012 11:03 PM

March 30, 2012

scala-lang.org

Scala 2.9.2 RC2

After some additional backporting, a new Release Candidate in the Scala 2.9.x series is now available for download: 2.9.2 RC2. This release includes many bugfixes, as well as backported documentation and scaladoc improvements from the community.

This RC2 release candidate is made available for testing purposes only and is not intended for production environments: a final 2.9.2 release will follow at the end of the RC cycle. Please help us with the testing of this candidate, and let us know of any issues that you may encounter.

by admin at March 30, 2012 12:55 PM

Scala IDE 2.0.1 RC2 available now!

We are very happy to announce a new release candidate for the next maintenance release of the Scala
IDE for Eclipse: Scala IDE 2.0.1 RC2 is available now!

The only change with respect to 2.0.1 RC1 is the bundled Scala version, which is now Scala 2.9.2-RC2.

What is new in 2.0.1?

Builder, Compiler and Editor improvements. And both Eclipse 3.6 (Helios) and Eclipse 3.7 (Indigo) are now officially supported! Read more...

by dotta at March 30, 2012 08:37 AM

March 29, 2012

Coderspiel

"There’s one obvious way to define a set of named, type-safe fields: write a scala trait. Your config..."

“There’s one obvious way to define a set of named, type-safe fields: write a scala trait. Your config file can then just be a scala file that you compile and evaluate when the server starts.”

- Why Config?

March 29, 2012 01:10 PM

March 28, 2012

Coderspiel

On LINQ, Standards, Databases and Fruit | stmts

On LINQ, Standards, Databases and Fruit | stmts:

What’s left seems like low-hanging fruit. I have heard nearly nothing about it, but I’ll be damned if twenty people aren’t sitting around working on it somewhere right now: There needs to be an object/node/graph database built explicitly on LINQ-like principles and in a way as to optimize for LINQ-based usage patterns. The data conforms to object patterns instead of its own designs. The kind of queries you send it informs a dynamic query analyzer, rebuilding and maintaining indexes for optimal access. You don’t have to worry, really, about primary keys, but more about references to other things.

March 28, 2012 02:12 AM

March 27, 2012

Coderspiel

"The Java Platform group is looking for an experienced, passionate and highly-motivated Software..."

“The Java Platform group is looking for an experienced, passionate and highly-motivated Software Engineer to join our world class development effort. Our team is responsible for delivering the Java Virtual Machine that is used by millions of developers.”

- the OpenJDK group at Oracle is growing (John Rose @ Oracle)

March 27, 2012 08:56 PM

Eric Torreborre

Coming full circle

In this post I want to show a few of the upcoming features in specs2-1.9 and also take a step back on how specs2 features and implementation unfolded since I started the project one year ago.

Why would you want to rewrite from scratch?

Good question, that seems to be very masochistic :-). Not only because of the sheer amount of features to re-implement but more importantly because of the difficulty to move users to a new version.

I explained in details the reasons why I thought the rewrite was necessary, how it would benefit users and how to migrate in a previous blog post. What I want to emphasize here is the compromise I decided to make at that time:

  • more concurrency and reliability
  • less practicality

The main reason for this compromise was immutability. Forcing myself to immutability had opened the gates of robust and concurrent software but at the same time I had to cut back on the syntax I had proposed for the original specs1 project. For example it wasn't possible anymore to write:

    // this example can only be "registered" if there are side-effects
"hello must have 5 letters" in {
"hello" must have size(5)
}
"world must have 5 letters" in {
"world" must have size(5)
}

Instead, I proposed to write:

    // examples are "linked" together with the ^ operator
"hello must have 5 letters" ! e1 ^
"world must have 5 letters" ! e2

def e1 = "hello" must have size(5)
def e2 = "world" must have size(5)

The feed-back was immediate. Some developers who were sent a preview liked it but others told me: "NEVER I would use this horrible syntax". Ok, fair enough, I can't blame you, it's a bit ugly on the right.

I decided then that I would relax my constraints a little bit and add one, just one, var. It would only be used to accumulate examples when building the specification, to enable the good old specs1 style. This was also, at least partially, solving the migration problem since a full rewrite of the specifications was not necessary.

Not everything was as cool as in the original specs1 tough. In particular the super-easy "isolated" execution model was missing. Until...

Lightbulb

... Until it struck me, just one month ago, that reintroducing this mode of execution was less than 10 lines of code!

Because I had chosen the functional paradigm of "executing a Specification" <=> "interpreting a data structure" it was really easy to change the interpretation to something declaring: "for each example, execute the code in a clone of the Specification so that all local variables are seen as fresh variables".

In terms of product management, it was a "magic" feature almost for free! To me, this is the illustration of a principle of Software: "if code is a liability, maximise your return on investment".

Maximize the ROI

I'm sure you've already read something like: "features are an asset, code is a liability". But I haven't yet read the logical consequence of it: "Maximize the ROI: extract as many features as you can from your existing code". Indeed every time we write a piece of code, it's worth wondering:

  • how can this be put to a better use?
  • can I add something slightly different to provide a new useful feature?
  • can I generalize it a bit to make sense of it in another context?
  • can I make it composable with an existing feature to get a new one?

That's exactly what happened with the "isolated" feature above. Here's another example of this principle in action.

IO and serialization are not cheap

A few months ago, I developed a feature to create an index page. On this index page I had to show the status of specifications which had been executed as part of the previous run. This meant that I had to store somewhere, on the file system, the results of each specification execution.

In terms of feature price, this is not a particularly cheap one. Everytime there is some IO interaction and some kind of serialization, the number of possible issues to consider is not so small. In a way that was really an "iceberg" feature: not a lot of functionality on the surface, but a lot of machinery under the water. So I wondered how I could improve my ROI on this. Hmm... since I'm writing status information to the disk there might be a way to reuse it!

Indeed, I can use this information to selectively re-run only the failed examples, or the skipped ones, or... And so on. From there, a new "feature space" opens, and the initial investment starts making sense.

It is also possible to maximize the ROI on existing features. A feature is an "asset". Perhaps, but it's not completely free either. You have to explain it, to promote it, to show when and how it interacts with the rest of the software. This is why maximizing the ROI of features makes sense as well.

That's exactly what happened with the brand-new "isolated" feature.

All expectations

Year after year I'm looking at the specifications that people are writing with specs/specs2. Kind of my hallway usability test for open-source libraries... I usually see several "styles" of specifications and one style is pretty frequent:

    "This is an example of building/getting/processing a datastructure" >> {
// do stuff
val data = processBigData

// check expectations
data must doThis
data must haveThat
data.parts must beLikeThis
// and so on...
}

In that style of specification, there is usually one action and lots of things to check. It is very unfortunate that most of the testing libraries out there will stop at the first failure. Because it really makes sense to collect all of them at once instead of having to execute the specification multiple times to get to all the issues.

Is there a way to "collect" all the failures in specs2-1.8.2? Not really. You can try use "or" with the expectations:

       (data must doThis) or
(data must haveThat) or
(data.parts must beLikeThis)

And that will collect all the failures up to the first success, and then it will stop executing the rest. Besides, the "or" syntax with all the parenthesis is not so nice.

After a while I realized that the only way to make this work was to use yet another mutable variable to silently register each result. But then I'd be back to the old specs1 problem. What about concurrency? How can I prevent each concurrent example to step on another example results?

Well, that's easy, I have the "isolated" feature now! Each example can run in its own copy of the specification and the mutable variable will only collect the results from that example safely. The result is a feature that's easy to implement but also easy to use because it's just a matter of mixing a trait to the specification!

Coming full circle

Can I go further with the same thinking? Why not?!

From the beginning of specs2, I liked the fact that the so-called "Acceptance specification" style allowed me to write a lot of text about what my system behavior and then annotate it with the actual code. The price to pay was all the symbols on the right of the screen which appeared utterly cryptic to some people (to say it nicely).

Then, last week, I realized that I could rely on something which exists in most code editors: code folding! In a classical JUnit TestCase, specs1 specification or specs2 mutable specification if you fold the code, you're left with only the text, forming a narrative for your system. If you see it like that, any specs2 mutable specification can be turned into an acceptance specification, just a few features are missing:

Not a lot to implement really. Most of the machinery is already provided by the org.specs2.Specification trait. This means that, for a very reasonable "price", you can now use "mutable" specifications in specs2 with a great deal of expressivity (nothing's perfect though, there are small issues due to semi-column inference for example, see here for variations around the "Stack" theme).

Full circle and blurred lines

To me, it really feels that I've come full circle:

  1. I rebuilt from scratch the "Specification" concept from specs1, throwing away the syntax
  2. I reintroduced some mutability very carefully to get some of that syntax back
  3. I built upon all the immutable code to finally end up with exactly what I would have liked to have in specs1!

My only concern now is that newcomers might feel lost because the library is not really prescribing a specific style: "should I use a 'unit' style or an 'acceptance' style? And what are the differences between the 2 anyway?". I hope that they'll realize that this is actually an opportunity. An opportunity to try out different ways of communicating and then choosing the most efficient or pleasing.

by Eric (noreply@blogger.com) at March 27, 2012 12:05 AM

March 26, 2012

Robey Pointer

Why Config?

<p>When I first started playing with scala in 2008, I was dismayed by the state of server configuration in the java world. A lot of java servers were still using property files, or worse, XML. XML is meant to be easily parsed by computers, but is really hard for humans to read and edit, and tends to hide useful information in baroque syntax and line noise. The python world was still clinging to Windows-era &ldquo;INI&rdquo; files, and the ruby world had invented something called YAML, with its own odd syntax.</p> <p>[Alex Feinberg pointed out that the use of the term &ldquo;config&rdquo; can be overly general. In this post, I&rsquo;m talking specifically about configuration used to bootstrap a cluster of machines all running the same server code. Shared configuration required by multiple server clusters is a different problem, and obviously not well-served by any solution that only works on the JVM.]</p> <p>We had gone through many iterations of config file formats at my previous job, as we moved from perl to C++ to java, but it was a very private company, terrified of open source, so we shared none of what we learned. I thought it was time to spead some best-practices around, so I wrote &ldquo;configgy&rdquo; lazily over a couple of months as I learned scala.</p> <h2>Configgy</h2> <p>The core ideas behind &ldquo;configgy&rdquo; were:</p> <ul> <li><p>A config file should be a text file, primarily readable by humans. It should be unambiguous and have minimal syntax.</p></li> <li><p>A server&rsquo;s configuration should really just be a set of (string) keys and values. The values can be bools, ints, strings, lists of strings.</p></li> <li><p>You should be able to take blocks of these key/value sets and nest them, so subsystems can have their own isolated configuration.</p></li> <li><p>The API should be similarly minimal, like a typesafe hashtable, and should allow subsystems to &ldquo;subscribe&rdquo; to configuration values and get notified if they&rsquo;ve changed.</p></li> </ul> <p>The end result was pretty successful, and we used it at Twitter for several years. An example chunk of a config file might look like this:</p> <pre><code>port = 22133 timeout_msec = 100 log { filename = "/var/log/kestrel/kestrel.log" roll = "daily" level = "info" } </code></pre> <p>Unfortunately, I had gone in the wrong direction, and it took a while for the mounting evidence (and my coworkers) to convince me.</p> <h2>What&rsquo;s wrong</h2> <p><img src="../../../images/rodent.jpg" style="float:right" /></p> <p>Some of the problems with configgy show up in the config file example I pasted above:</p> <ul> <li><p>There&rsquo;s no schema. &ldquo;port&rdquo; should be an int, but there&rsquo;s no place to declare that. There&rsquo;s no definition for what should be in the config file at all. What are the keys? What do they do? You have to document it separately in a text file, if you&rsquo;re really ambitious.</p></li> <li><p>The available types aren&rsquo;t sufficient. Durations are really common in server configuration because they specify timeouts, and there&rsquo;s no real support for them. You have to drop sly hints in the field names (like &ldquo;msec&rdquo; for milliseconds) and hope people are paying close attention.</p></li> <li><p>Extending the available types will never cover all cases. The &ldquo;roll&rdquo; field above can only have a few possible values, but there&rsquo;s no simple way to define a new enumerated type like that.</p></li> </ul> <p>Other problems only show up in daily use:</p> <ul> <li><p><em>validation</em>: How do you validate that the config file won&rsquo;t cause a server crash hours after it starts? There&rsquo;s nothing forcing &ldquo;timeout_msec&rdquo; to be an int, so it may throw an exception minutes later, when the code first tries to call <code>.toInt</code> on it.</p></li> <li><p><em>defaults</em>: What is the default timeout? Is there one? Configgy supported providing a default value in the API, but how do you know what that is when you&rsquo;re editing the config file &mdash; especially if you didn&rsquo;t write the original code?</p></li> </ul> <p>One of the biggest faults should get its own section, because I have a lot to say about it.</p> <h2>Reloading config files</h2> <p>Configgy had a lot of code to support reloading config files on the fly, allowing a server to &ldquo;subscribe&rdquo; to a key and change its behavior if a config file was reloaded. It seemed really clever at the time, but experience taught me and my coworkers that it&rsquo;s a really bad idea in practice.</p> <p>How often do you change a config file on the fly and ask the server to reload it? And more importantly, when? Murphy&rsquo;s Law tells us the answer: when something is broken, it&rsquo;s the middle of the night, and it needs to be fixed immediately.</p> <p>But because we only did this in a crisis, the code was <em>effectively untested</em>. If you aren&rsquo;t regularly using some part of a server, you can&rsquo;t trust it enough to depend on it in a crisis. In a crisis, I want only tools that I&rsquo;ve used before and am confident in. It only takes a couple of incidents where reloading a config file doesn&rsquo;t <em>actually</em> fix the server&rsquo;s behavior before your policy becomes: Fix the config file offline, then restart the server.</p> <p>The ability to reload configuration became just another moving part: something you had to think about, but would never actually use in a crunch.</p> <p>This could probably be solved by adding automated testing that changes your config file, asks the server to reload, and then re-runs a suite of tests. But it just didn&rsquo;t seem worth it. As a practical matter, the server needs to startup cleanly after any kind of unclean shutdown (&ldquo;kill -9&rdquo; or a fire) &mdash; and must be tested to do so &mdash; so you don&rsquo;t need any other feature for reloading the config file. Just change the file and kill the server. Now it&rsquo;s running with the new config!</p> <h2>How to fix it</h2> <p>If you read my <a href="http://robey.lag.net/2011/04/30/dissolving-patterns.html">post from last year about patterns</a>, you know where this is heading. There&rsquo;s one obvious way to define a set of named, type-safe fields: write a scala trait. Your config file can then just be a scala file that you compile and evaluate when the server starts.</p> <p>Your config trait should be a builder that creates a server from config, like this:</p> <pre><code>trait ServerConfig extends (() =&gt; Server) { var port: Int = 9999 var timeout: Option[Duration] = None def apply(): Server = new Server(port, timeout, ...) } </code></pre> <p>The <code>apply</code> method assembles a <code>Server</code> from the configuration. After that, your config file can be:</p> <pre><code>new ServerConfig { port = 12345 timeout = 250.milliseconds } </code></pre> <p>The important lines look just like the configgy version, and are executed as part of the constructor.</p> <p>Now you have a schema (the config trait), and every field has a type, declared in the trait and enforced by the scala compiler. If you need a specialized type, like an enum, you can make one. I especially like how readable timeouts become. It&rsquo;s unambiguous that the duration is specified in milliseconds, and you could use seconds if you want.</p> <h2>How does it work?</h2> <p><img src="../../../images/statue.jpg" style="float:right" /></p> <p>The key is <code>Eval</code>, a component of <code>util-eval</code> that makes it easier to compile and execute scala code from inside the JVM. Scala already exposes this functionality &mdash; the scala compiler runs on the JVM, after all, and the REPL needs to do line-by-line compilation &mdash; but the API is arcane and marked with a &ldquo;No serviceable parts inside&rdquo; label. The <code>Eval</code> class simplifies it to:</p> <pre><code>scala&gt; val eval = new Eval() eval: com.twitter.util.Eval = com.twitter.util.Eval@1df5973b scala&gt; eval[Int]("3 + 4") res0: Int = 7 </code></pre> <p>The result of evaluating a config file is a new <code>ServerConfig</code> object (or similar), and calling <code>apply</code> on that will return a fully-initialized <code>Server</code> object, so loading the config file and starting the server boils down to:</p> <pre><code> val eval = new Eval() val config: ServerConfig = eval[ServerConfig](new File("...")) val server: Server = config() server.start() </code></pre> <p>If you add some exception handling to log errors, you end up with the code inside <code>RuntimeEnvironment</code> in <a href="https://github.com/twitter/ostrich">ostrich</a>, which we use to bootstrap server startup from config files in a deployed server.</p> <h2>Sleight of hand</h2> <p>There are two problems I listed above that aren&rsquo;t solved by this simple solution: validation and default values. So you have to add a little bit of code to finish up.</p> <p>If a config file can be compiled and executed, then it&rsquo;s valid. The result of the evaluation is a config object (<code>ServerConfig</code> in this example) that doesn&rsquo;t have any side-effects and can be safely evaluated at compile time. So that&rsquo;s what we do: the last phase of a build executes the server jar with a special <code>"--validate"</code> option that compiles the config files and exits. If that succeeds, the config files are valid and they won&rsquo;t crash the server in production.</p> <p>In the example above, all the fields had default values, which is not always what you want. For those cases, we defined a <a href="https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/Config.scala">basic <code>Config</code> trait</a>. It allows you to mark a field as <code>required</code> with no default value, or optional, or lazily computed.</p> <pre><code>trait ServerConfig extends Config[Server] { var port = required[Int] var timeout = optional[Duration] } </code></pre> <p>Implicits handle the conversion from a normal type to a &ldquo;required&rdquo; or &ldquo;optional&rdquo; type (optional types just use scala&rsquo;s <code>Option</code> class), so the config file looks the same.</p> <p>The <code>Config</code> trait fits completely in one file, with less than 100 code lines (according to <a href="http://cloc.sourceforge.net/">cloc</a>). That&rsquo;s an incredible improvement over configgy.</p> <h2>Postscript</h2> <p>This post is a little overdue, but better late than never. :&ndash;)</p> <p>I wrote this because it was important to me to share the knowledge, not because i did all (or even most) of the work. I carefully avoided naming coworkers while writing this post, because it disturbed the flow, but they all deserve callouts:</p> <p>John Kalucki first spelled out for me why the implementation of default values was bad. Matt Freels and Ed Ceaser implemented the first draft of the <code>Config</code> class and pulled me in to help iterate on it. Nick Kallen opened my eyes to the dangers of depending on a server&rsquo;s &ldquo;shutdown&rdquo; and &ldquo;reload&rdquo; behavior.</p> Flattr this

March 26, 2012 07:00 AM

March 22, 2012

Eishay Smith

fetching ember.js Handlebars templates with jsonp from Scala on Play!

As a setup I should mention that our ember.js javascript application is hosted on a third party page. Since we're using ember.js, the best templating solution is to use Handlebars. The trivial use case of handlebars is to embed the templates in the page itself via a script tag of type="text/x-handlebars". In our case, we're hosted so we can't really control the host page and even if we could, we shouldn't litter it with our templates. Moreover, there are many templates we would use in edge usecases, fetching them all on load will not be a good idea.
The solution we came up with is to fetch the templates on demand or pre-fetch if we see the need coming. Its best to keep the templates as stand alone files, its easier to revision and A/B test with variation of them. On top of that, we must handle the cross domain issue. In our case we decided to go with jsonp instead of CORS. On the javascript side: <script src="https://gist.github.com/2156608.js"> </script> Note that in the response, the function gets the template html as a string and pass it onto the Ember.Handlebars.compile function to compile it to a handlebars template. Ember.js makes the template globally accessible from code or as an embedded view via the Ember.TEMPLATES map. When creating an ember.js view one should simple point to the template id as in: <script src="https://gist.github.com/2156614.js"> </script>
On the server side we use Play Framework 2.0. Over there we have a rout in the routes file as in: <script src="https://gist.github.com/2156658.js"> </script> It basically passes the name of the template from the path and name of the jquery's jsonp callback from the url args.
On the scala side things look pretty simple. Naturally you would like to check for security properties, string injections and A/B testing groups. <script src="https://gist.github.com/2156645.js"> </script> [plug] QWallet is hiring!

by Eishay Smith (noreply@blogger.com) at March 22, 2012 04:07 PM