Edi Weissmann

I code for fun /* and profit */

Free Private Maven Repository Hosting

Apache Maven

This article will show how to host a private Maven repository for free using Dropbox.

A foreword about privacy of the repository created using this solution: it’s not completely private. It’s private enough. If somebody guesses the name you gave to your repository and the name of the artifacts, then they could get access to them. For me that’s not a problem. Just name your repository something very random, like a good strong password.

If you don’t need a private Maven repository, you should probably know the nice people at Sonatype offer free public Maven repository hosting for open source projects. Read more about it here.

To start, get a Dropbox account. Inside it, in the Public folder, you’ll be storing the maven artifacts.

Then you’ll also need the Dropbox desktop client for uploading the files from the local filesystem to the Dropbox servers.

With the Dropbox desktop client setup, you should have a path on your local filesystem where the Public folder is synchronized to. Mine is /Users/edi/Dropbox/Public.

All we need to do now is to tell Maven to deploy the artifacts of the project to this path:

1
mvn deploy -DskipTests=true -DaltDeploymentRepository=dropbox::default::file:///Users/edi/Dropbox/Public/repository

If you prefer a more permanent solution, just add the following lines to your pom.xml:

1
2
3
4
5
6
<distributionManagement>
      <repository>
          <id>dropbox.repo</id>
          <url>file:///Users/edi/Dropbox/Public/repository</url>
      </repository>
  </distributionManagement>

That’s it. After deploying you’ll need to wait few minutes for Dropbox to upload all the files to the cloud.

To get the url of your private maven repository, log into Dropbox, select your Public folder and click Copy public link. You should get something similar to https://dl.dropboxusercontent.com/u/123456/repository.

Done, your new Maven repository is ready to use! And remember, it’s not completely private. Use it only if for you it’s private enough.


Note: The Dropbox links in this article contain referral information. If you sign up using that link we’ll both get 500 MB of bonus space.

Yammer Metrics and Playframework

Yammer metrics logo

I love the Yammer metrics library. It’s so handy easy to use and comes with friendly scala wrappers.

Typically I would setup access to a web application’s metrics by dropping the default MetricsServlets into web.xml and mapping them to an unsecured /metricsFtw! url.

With Playframework this servlet/web.xml approach would not work, so here’s the alternative setup I found to work nicely for me.

First, we add the dependencies to Build.scala

1
2
3
4
5
6
7
  val metricsVersion = "2.1.2"
  val metricsCore = "com.yammer.metrics" % "metrics-core" % metricsVersion
  val metricsScala = "com.yammer.metrics" %% "metrics-scala" % metricsVersion

  val appDependencies = Seq(
    /* other deps */ metricsCore, metricsScala
  )

Second, we add code to our components to gather runtime metrics:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package controllers

import play.mvc.Controller
import play.api.mvc.Action
import com.yammer.metrics.scala.Instrumented

object DownloadController extends Controller with Instrumented {

  // measure downloads
  val downloadsCounter = metrics.counter("downloads")

  def download(uuid: String) = Action {
  
  downloadsCounter += 1
  /* actual downloading */
  }
}

Now, we should be able to see the metrics by connecting with jconsole to the sbt-launch.jar run process locally.

To access the metrics data via HTTP, we’ll create a MetricsController that reports the metrics by using the provided ConsoleReporter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package controllers

import play.api.mvc._
import com.yammer.metrics.reporting.ConsoleReporter
import java.io.{PrintStream, ByteArrayOutputStream}

object MetricsController extends Controller {

  def index = Action {

    def metricsAsString() = {
      val baos = new ByteArrayOutputStream()
      val ps = new PrintStream(baos)
      new ConsoleReporter(ps).run()

      ps.flush()
      ps.close()

      new String(baos.toByteArray)
    }

    Ok(metricsAsString())
  }
}

And registered this url in routes.conf

1
2
# Metrics
GET     /metricsFtw!/                   controllers.MetricsController.index()

And that’s it.

Minify .js and .css During Maven Build

Pagespeed logo

I want to minify static js and css files for a website. I want to combine all files into one js file and one css file. And I want to do that during the Maven build.

One solution is a combination of minify-maven-plugin and maven-replacer-plugin

Since it’s Maven based, there’s tons of xml configuration involved. Thankfully, this guy from Stockholm created a sample project on github showing how all plugins are configured together. It’s pretty easy to follow his setup and that’s what I did.

I had some issues about the order in which the .js files were included in the minified bundle: my app’s dependencies should have appeared before my app’s sources. They didn’t.

I learned that I could solve this by creating two .js bundles: one for my dependencies and one for my app.

1
2
3
4
5
6
7
8
9
10
<-- deps bundle: include all .js libs except my app -->
<jsSourceIncludes>
  <jsSourceInclude>**</jsSourceInclude>
</jsSourceIncludes>
<jsSourceExcludes>
  <jsSourceExclude>**/application.js</jsSourceExclude>
</jsSourceExcludes>
<jsFinalFile>myapp-dep-${maven.build.timestamp}.bundle.js</jsFinalFile>

<-- add another bundle that just contains my app's js files: application.js -->

Now each time mvn package is run, the css and js files are minified.

If I need to debug the .js in original formatting, I launch the website from the IDE, and the mvn goal to minify is not invoked.

Design Patterns and Scala

Scala logo

Overview

A design pattern sometimes represents a language failing. The term “pattern” implies a solution to some kind of recurring problem. Stronger languages can resolve these duplications more easily by using language features and not secondary constructs such as patterns. For a developer accustomed to design patterns in Java, I think it would be an interesting exploration to see how Scala solves same problems using language constructs.

Singleton Pattern

The Singleton pattern describes a way to ensure that only one instance of an object exists.

Scala provides a language construct, the object keyword, to achieve that.

1
2
3
object SantaClaus {
  // there's only one Santa
}

Strategy pattern

The strategy pattern describes a way to select algorithms behavior at runtime.

In Java, a typical way to implement this would be to use classes to encapsulate algorithms.

Scala treats functions as first class citizens, so they can be passed as parameters themselves.

1
2
3
4
5
6
7
8
9
10
type Average = Seq[Int] => Int
class Metrics (values: Int*)  {
  def compute (fn: Average)  = fn (values)
}

def arithmeticMean(values: Seq[Int]) = values.sum / values.size
def harmonicMean(values: Seq[Int]) = values.size / (values reduce (_ + 1/_))

new Metrics(1,2,3).compute (arithmeticMean)
new Metrics(1,2,3).compute (harmonicMean)

Visitor pattern

The purpose of the visitor pattern is to separate the algorithm from the structure it operates on.

For most purposes, in Scala this can be implemented using case classes and pattern matching.

1
2
3
4
5
6
7
8
9
10
sealed trait Read
case class Magazine (title:String, editor: String) extends Read
case class Book (author: String, publisher: String) extends Read
case class Blog (author: String) extends Read

def contactPerson (read: Read) = read match {
  case Magazine(_, editor) => editor
  case Book(author, _) => author
  case Blog(author) => author
}

Template method pattern

The template method pattern defines the main skeleton of an algorithm, allowing parts to be specified or redefined, ensuring that the overarching algorithm is still followed.

This can be implemented in Scala using partially applied functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
trait Closeable {
  def close()
}

def using (resource: Closeable)(block: => Unit) {
  try {
      block
    } finally {
      resource.close()
  }
}

val inputStream = new FileInputStream(/*…*/)
using(inputStream) {
  // do something with the input stream
  // but don't worry about closing it
}

Command pattern

The command pattern describes a way to encapsulate in an object all the information needed to call a method at a later time.

Scala’s closures can be used as lightweight command objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class RemoteControl {
  def execute(command: => Unit) {
    command
  }
}

object Example {
  val mediaPlayer = new MediaPlayer
  val remote = new RemoteControl

  def playCmd = mediaPlayer.play()
  def pauseCmd = mediaPlayer.pause()

  remote.execute(playCmd)
  remote.execute(pauseCmd)
  remote.execute({
    mediaPlayer.stop()
  }) // inline
}

That’s it for now. Hope you enjoyed it. To be distilled and maybe continued.

Configuring a Play 2.0 App Using MongoDB Salat Plugin for Cloudfoundry

1
2
3
4
5
6
7
8
9
10
# comment out the existing configuration for local development
# mongodb.default.db = "mydb"

# add configuration that will use the VCAP_SERVICES environment variables from Cloudfoundry
# assumes that you have provisioned a mongodb service called 'mongodb-appname' for your app
mongodb.default.db = ${?cloud.services.mongodb-appname.connection.db}
mongodb.default.host = ${?cloud.services.mongodb-appname.connection.host}
mongodb.default.port = ${?cloud.services.mongodb-appname.connection.port}
mongodb.default.user = ${?cloud.services.mongodb-appname.connection.username}
mongodb.default.password = ${?cloud.services.mongodb-appname.connection.password}