08 September, 2019

InteliJ: IDEA error: Can't find resource for bundle java.util.PropertyResourceBundle, key kotlin.gradle.testing.enabled

Lately I faced IDEA error Can't find resource for bundle java.util.PropertyResourceBundle in IntelliJ IDEA/To fix this issue you can: 
  • find util.jar file in Idea/lib folder
  • extract registry.properties file from misc folder and add required property


03 December, 2014

ScalaForms. Form with password confirmation

Problem:

Create register form with password confirmation and validation messages next to field as shown on image below.

Solution:
There are many solutions to this problem. I chose tuple transformation. It provides me error on tuple level, instead of globalErrors.
First step is to create model object: User
case class User(login: String, password: String)
then define form in controller for User case class
  val registrationForm: Form[User] = Form(
    mapping(
      "login" -> nonEmptyText.verifying("user.registration.userExists", User.findByLogin(_) == None),
      "passwordWithConfirmation" -> tuple(
        "password" -> text(minLength = 6, maxLength = 30)
          .verifying("user.registration.passwordOneDigit", name => {
          (name + "A").split("\\d").size > 1
        }),
        "confirmation" -> text
      ).verifying("user.registration.passwordDontMatch", verifyPassword(_)).transform(
      { case (password, confirmation) => password},
      (password: String) => ("", "")
      )
    )(User.apply)(User.unapply)
  )

  def verifyPassword(passwordWithConfirmation: Tuple2[String, String]): Boolean = passwordWithConfirmation match {
    case (password: String, confirmation: String) => password.equals(confirmation)
  }
The form contains passwordWithConfirmation which is tuple mapping for password and confirmation inputs. For this tuple I added verification rule, checking if both fields are equal. Last thing to do is to convert tuple into data that will be stored in User entity. For this purpose transform function is used. The transformation works both ways:
  • from form to object { case (password, confirmation) => password}
  • from object to form (password: String) => ("", "")
Second conversion returns tuple of empty strings, because I don't want password and its confirmation to be loaded into form.
Play template for the Form object may look like this:
@(registrationForm: Form[model.User])(implicit flash: Flash)

@import helper.twitterBootstrap._
@import helper._

@main {
    <h2>@Messages("user.registration.registerAccount")</h2>

    @helper.form(action=routes.UserCtrl.register) {
        <fieldset>
            @inputText(registrationForm("login"))
            @inputPassword(registrationForm("passwordWithConfirmation.password"))
            @inputPassword(registrationForm("passwordWithConfirmation.confirmation"))

        </fieldset>
        <input class="btn btn-primary" type="submit" value="@Messages("user.registration.register")" />
    }
}

Last thing that I need to do is to show error message for unmatched passwords. This will not work automatically, because there is no passwordWithConfirmation element in my form.
            @if(registrationForm.hasErrors) {
                @registrationForm.error("passwordWithConfirmation") match {
                    case Some(err:FormError) => {<span class="help-inline">@Messages(err.message)</span>}
                    case _ => {}
                }
            }

08 July, 2014

Comparison with constants in pattern matching

   Today I faced scala.MatchedError: 0 (of class java.lang.Integer) in overridden renderComponent method of scala.swing.Table, when I tried to add rows.
    val table = new Table(0, 2) {
      override protected def rendererComponent(sel: Boolean, foc: Boolean, row: Int, col: Int): Component  = {
        col match {
          case 1 => tcr.componentFor(this, sel, foc, "bar", row, col)
        }
      }
    }
It turned out that I need a match for all possible values. In this particular case for 0, because I have two columns. So adding undermentioned code solved the problem
          case 0 => super.rendererComponent(sel, foc, row, col)
At the beginning I was confused by the error message and thought that there might be some casting problem. So I tried to store 1 into value
    val table = new Table(0, 2) {
      override protected def rendererComponent(sel: Boolean, foc: Boolean, row: Int, col: Int): Component  = {
        val columnIndex: Int = 1
        col match {
          case columnIndex => tcr.componentFor(this, sel, foc, "bar", row, col)
        }
      }
    }
Ta-dah! Program compiles, adding rows to table works, it seemed that I fixed the problem, but in fact I just made one of the most common mistakes that Scala beginners do. It is the second time when I fall into this trap, that is why I chose to mention about it on my blog.

In this situation columnIndex inside match is not the same columnIndex that was defined in first line of the function. It is variable initialized with col value. As there is no condition check just an assignment, the expression to the right of the arrow is always executed and each column contains component that I only wanted to appear in second one.

To fix this issue I need to use stable identifier, which in Scala must either start with uppercase letter
    val table = new Table(0, 2) {
      override protected def rendererComponent(sel: Boolean, foc: Boolean, row: Int, col: Int): Component  = {
        val ColumnIndex: Int = 1
        col match {
          case ColumnIndex => tcr.componentFor(this, sel, foc, "bar", row, col)
        }
      }
    }
or be surrounded by backticks
    val table = new Table(0, 2) {
      override protected def rendererComponent(sel: Boolean, foc: Boolean, row: Int, col: Int): Component  = {
        val columnIndex: Int = 1
        col match {
          case `columnIndex` => tcr.componentFor(this, sel, foc, "bar", row, col)
        }
      }
    }
The first solution seems to be much better as it is agreeable with Scala's naming convention, according to which constants names should start with capital letter.

Please notice that you cannot define columnIndex as variable. Changing val to var in last two snippets will produce compile error.

22 March, 2014

Lazy initialization by Joshua Bloch

   The most natural way to add lazy initialization is to create method checking if object's field was initialized and if not then do it.
    private SomeObject obj;

    public SomeObject getObject() {
        if (obj == null)
            obj = computeObjectValue();
        return obj;
    } 
Such a code is pretty simple, but requires synchronization in case of concurrent access. Adding synchronized keyword to getObject method is sufficient to avoid repeated initialization for instance and static fields, but harms performance. That's why it is good to use several idioms proposed by Joshua Bloch.

Single-check idiom
    private volatile SomeObject obj;
    
    public SomeObject getObject() {
        SomeObject result = obj;
        if(result == null) 
            obj = result = computeObjectValue();
        return result;
    }
When to use:  if an instance field can tolerate repeated initialization
Why field needs to be volatile:  it adds synchronization on the field; in case of primitives other than long or double volatile can be removed, but in this situation we will face more repeated initializations caused by caching field value by VM
Why to use additional local variable result:  access to volatile field is slower than to this variable

Double-check idiom
    private volatile SomeObject obj;

    public SomeObject getObject() {
        SomeObject result = obj;
        if (result == null) {
            synchronized (this) {
                result = obj;
                if (result == null)
                    obj = result = computeObjectValue();
            }
        }
        return result;
    }
When to use:  if an instance field should be initialized only once.
Why double check field:  in this solution we postpone synchronization to the very last moment, first check is outside synchronized block, so we need to do it again.

Holder class idiom
    public static SomeObject getObject() {
        return FieldHolder.obj;
    }

    private static class FieldHolder {
        private static final SomeObject obj = computeObjectValue();
    }
When to use:  if you want to lazy initialize static field
Why to use additional class:  it is guaranteed that classes will not be initialized until it is used. VM synchronize field access only to initialize the class. When field is subsequently accessed VM patches the code, so no testing or synchronization is involved.

11 February, 2014

Access Modifiers in Scala for Java programmers

   Today I’m going to concisely compare Scala's access modifiers with these used in Java. For more detailed description please refer to this post.

Java access modifiers:

Scala access modifiers:


Additionally in Scala private and protected access modifiers can be qualified with a name of a package or class. This is done using square brackets e.g.
For class defined in package a.b.c 
  • protected[c] will be the same as protected in Java
  • private[c] will be the same as default in Java
You can also use other packages that are available in class’s package tree:
  • protected[a] will be visible in subclasses and in packages a, b and c (package a and all its subpackages)
  • private[b] will be visible in packages b and c
  • for class defined in package a.b it is not allowed to define private[c] or protected[c]
Inner class in Scala has access to private members of enclosing class, but enclosing class doesn’t have access to private members of inner class.
class Enclosing {
 private val x = 5
 new Inner().z // value z in class Inner cannot be accessed in Enclosing.this.Inner 
 class Inner {
   private val z = 9
   def out = x + z // no problem
 }
}
If you want to make it work similarly to Java you need to add enclosing class qualifier.
   private[Enclosing] val z = 9

The last scope introduce in Scala that is worth to mention is the object private:
   private[this] val member = 1
which stipulates that the member can only be seen by members called on that same object, not from different objects, even if they are of the same type.

27 January, 2014

Scala Dependency Injection techniques

   Lately I was checking different solutions for dependency injection in Scala (code available here in pl.mariusz.marciniak.di package). Scala DI is vastly described in Real World Scala Dependency Injection artice, so I will just put short summary for each of techniques that I used:

Implicits
   The most obvious solution for injecting dependencies is to add parameters to object’s constructor (you can also do it by defining properties, but in that case your object becomes mutable). Additionally Scala provides you implicit parameters, which can be automatically supplied.
  class Calculator (implicit val dataProvider:DataProvider, implicit val operation:Operation) {
    def calculate(): Int = operation.exec(dataProvider.nextArgument, dataProvider.nextArgument)
  }
  val calc = new Calculator

Here Calculator’s constructor has two arguments marked as implicit. This means that they can be omitted if default objects of the same type are defined. Above implementation will generate compilation error, because these defaults are missing. To provide them we can for example define and import configuration object.
  object AdditionFromFakeDbDataConfig {
    implicit val operation: Operation = new Addition 
    implicit val dataProvider: DataProvider = new FakeDbDataProvider
  }
  import AdditionFromFakeDbDataConfig._
  val calc = new Calculator

Structural typing
   This is Scala feature to provide duck typing in a type-safe manner. Duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. In Scala you can achieve that by replacing data type with code block containing all required methods and properties.
Calculator(dataProvider: { val x: Int; val y: Int}, operation: { def exec(a: Int, b: Int): Int}) { ... }
Calculator class requires two arguments to be passed to its constructor. First needs to define two values x and y, and the second one must contains function exec taking two integers and returns integer. For example you can pass two objects:
  object Data {
    val x = 5
    val y = 3
  }
  object Avg {
    def exec(a: Int, b: Int): Int = (a + b) / 2 
  }
This solution gives us opportunity to aggregate all required resources into one object and pass that object into constructor. It is good to remember that Scala's structural typing uses reflection, so one can face some performance problems when he is using this solution vastly. Additional information about Structural Typing can be found on this site.

Cake Pattern
   Cake Pattern is the last method that I want to mention about in this post. Cake Pattern combines few Scala features:
  1. Trait with abstract value
  2. First of all you need to create a namespace using trait, containing all classes that you need to inject e.g. Addition and Multiplication are containted in Operations namespace, additionally there is abstract value defined that need to be instantiate in non-abstract object.  
      trait Operations {
        val operation: Operation
        trait Operation {
          def exec(a: Int, b: Int): Int
        }
    
        class Addition extends Operation {
          def exec(a: Int, b: Int): Int = a + b
        }
    
        class Multiplication extends Operation {
          def exec(a: Int, b: Int): Int = a * b
        }
      }
    

  3. Self type
  4. Self type can be used to access fields or functions of other type which implementation will be mixed in later e.g. CalculatorComponent requires two traits DataProviders and Operations, both of them are in fact namespaces with abstract values: dataProvider and operation, that is why they can be accessed in Calculator class  
      trait CalculatorComponent { this: DataProviders with Operations =>
        val calculator = new Calculator
        class Calculator {
          def calculate(): Int = operation.exec(dataProvider.nextArgument, dataProvider.nextArgument)
        }
      }
    
  5. Mixins
  6. Last step is to combine all components in one object. 
      object AdditionFromFakeDbDataConfig extends CalculatorComponent with Operations with DataProviders {
          val operation = new Addition
          val dataProvider = new FakeDbDataProvider
      }
Additional links

26 September, 2013

SimpleMessageListenerContainer autoStartup and connectLazily properties

   Lately after replacing DefaultMessageListenerContainer with SimpleMessageListenerContainer I spotted that the second one ignores autoStartup setting.
Spring documentation states that SimpleMessageListenerContainer creates a fixed number of JMS sessions at startup and uses them throughout the lifespan of the container, but why this happens before checking the autoStartup flag. I chose to explore source code for an answer.
   Initialization of MessageListenerContainers is done automatically when context starts up, as they implement the Lifecycle interface. It is worth to remember that lazy-init flag is ignored for lifecycle beans.
 Let’s look how the initialization flow looks like:
  • constructor
  • set properties (here auto start-up flag is set)
  • post construct method – if defined
  • doInitialize
  • doStart
Execution of doStart method depends on autoStartup flag which is checked in DefaultLifecycleProcessor.startBeans. Both containers use AbstractJmsListeningContainer’s doStart implementation:
  • default container doesn’t override it at all
  • simple container executes it and after that initializes consumers
  • @Override
    protected void doStart() throws JMSException {
          super.doStart();
          initializeConsumers();
    }
    
doStart establishes shared connection and resume all defined tasks. Default container task creates connection, session and consumer. Simple container doesn’t define any asynchronous tasks, instead it creates all these JMS components synchronously in its doInitialize method. So consumers initialization in doStart method is redundant in this case.

Since Spring 3.1 SimpleMessageListenerContainer has additional property connectLazily,that can be used to skip initialization of JMS components in doInitialize method. When this flag is set to true and autoStartup to false, then message listener container needs to be started manually.