Monday, June 01, 2020

Salesforce Layout - Clickable Address Field

Address field on an object can be made clickable to open the address in Google maps by enabling the Maps and Location service.

To enable it - follow Setup -> Build -> Customize -> Maps and Location -> Maps and Location Settings.

Maps and Location service uses Google Maps to display maps on standard address fields, enables creation of Visualforce maps, and helps users enter new addresses with autocomplete.

Saturday, April 23, 2016

Unit Testing Log Statements

Sometimes asserting on a log statement might be the only way of validating a method call. One way of asserting log statements is to create a custom appender and attaching it to the logger to capture the logs. log4j-api provides the framework to create a custom appender.

import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class CustomAppender extends AbstractAppender {

    private List messages = new ArrayList<>();

    public CustomAppender(String name, Filter filter, Layout layout) {
        super(name, filter, layout);
    }

    public CustomAppender(String name, Filter filter, Layout layout, boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
    }

    @Override
    public void append(LogEvent event) {
        byte[] data = getLayout().toByteArray(event);
        messages.add(new String(data).trim()); // optional trim
    }

    @Override
    public void stop() {
        
    }

    public List getMessages() {
        return messages;
    }

}
Following method adds the custom appender to the logger:
private void setUpLogHandler() {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();

        // Create and add the appender
        customAppender = new CustomAppender("Custom", null, PatternLayout.createDefaultLayout());
        customAppender.start();
        config.addAppender(customAppender);

        // Create and add the logger
        AppenderRef[] refs = new AppenderRef[]{AppenderRef.createAppenderRef("Custom", null, null)};
        LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, ClassUnderTest.class.getCanonicalName(), "true", refs, null, config, null);
        loggerConfig.addAppender(customAppender, null, null);
        config.addLogger(ClassUnderTest.class.getCanonicalName(), loggerConfig);
        ctx.updateLoggers();
    }
Below is an example test method which asserts on a method that logs:
    @Test
    public void logTest() {
        setUpLogHandler();
        ClassUnderTest ct = new ClassUnderTest();
        ct.methodThatLogs();
        assertThat(customAppender.getMessages(), hasItem("new log message"));
    }

Thursday, April 21, 2016

Git - Rewriting Commit

Git provides an option to modify the last commit. For staging follow the normal method:

git add .
After staging the files, use the --amend option to staged files to the last commit:
git commit --amend
If no commit message is provided with -m option the previous commit message will be prompted by default. On the other hand to amend a commit without changing its commit message use the --no-edit option.

Wednesday, April 20, 2016

Parameterized JUnit Tests

JUnitParams provides a runner - JUnitParamsRunner, to add parameterized tests in a test class. With this runner parameterized and non-parameterized test methods can be combined in the same class.

@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    @Parameters({"1, true", "2, false"})
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}
To pass in objects or null values, a separate method can be setup, which then can be added to the @Parameters annotation.
@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    private Object[] params() {
        return $(
                $(1, true),
                $(2, false)
        );
    }

    @Parameters(method = "params")
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}

Wednesday, April 13, 2016

Maven Auto Increment Version

Maven update-versions is a handy goal to increment version number of a project. This is especially useful for large multi-module maven projects.

mvn release:update-versions
The above command prompts for the new version for each module in the project. The prompts can be avoided by using the option autoVersionSubmodules. This will set each module version to be same as the parent POM.
mvn releae:update-versions -DautoVersionSubmodules=true
The goal can be run in non-interactive mode using batch-mode.
mvn --batch-mode release:update-versions
Above command will auto increment the version without prompts. A specific version can also be specified:
mvn --batch-mode release:update-versions -DdevelopmentVersion=1.1-SNAPSHOT

Saturday, September 07, 2013

Abstract Factory

The Abstract Factory pattern provides an interface that delegates creation calls to one or more concrete classes in order to deliver specific objects. Following is the definition provided for the pattern in the GoF book on Design Patterns:

Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Abstract factory relies on object composition – i.e. object creation is implemented in methods exposed in the factory methods. The intent of the pattern is to create families of related objects without having to depend on their concrete classes.

First we define the interface and implementation of the object that we want to create:

public interface Car {

    

    public void setDescription(String description);


 

    public void refuel();

}


 

public class EVCar implements Car {


 

    @Override

    public void setDescription(String description) {

        // set description

    }


 

    @Override

    public void refuel() {

        // electric charging

    }


 

}


 

public class HybridCar implements Car {


 

    @Override

    public void setDescription(String description) {

        // set description

    }


 

    @Override

    public void refuel() {

        // refuel with gas

    }


 

}


 

Now we define the factories, starting with an abstract factory:

public interface AbstractCarFactory {

    public Car createCar();

}


 

Next the actual implementations of the factory:

public class EVCarFactory implements AbstractCarFactory {


 

    @Override

    public Car createCar() {

        EVCar evCar = new EVCar();

        return evCar;

    }

}


 

public class HybridCarFactory implements AbstractCarFactory {


 

    @Override

    public Car createCar() {

        HybridCar hybridCar = new HybridCar();

        return hybridCar;

    }


 

}


 

Now let's test drive this factory:

public class AbstractFactoryTest {

    AbstractCarFactory abstractCarFactory = null;

    

    @Test

    public void evCarFactoryTest() {

        abstractCarFactory = new EVCarFactory();

        abstractCarFactory.createCar();

    }

    

    @Test

    public void hybridCarFactoryTest() {

        abstractCarFactory = new HybridCarFactory();

        abstractCarFactory.createCar();

    }

}


 

While the pattern hides the implementation details from the client, there is always a chance that the underlying system will need to change – for example new attributes might be added to Car or AbstractCarFactory, which would mean a change to the interface that the client was relying on, thus breaking the API.

Tuesday, August 13, 2013

Priority Queue


 

  • A priority queue is an abstract data type for storing a collection of prioritized elements that supports arbitrary element insertion but supports removal of elements in order of priority, that is, the element with first priority can be removed at any time
  • Other data structures like stacks, queues, lists and trees store elements at specific positions, which are often positions in a linear arrangement of the elements determined by the insertion and deletion operations performed
  • The priority queue ADT stores elements according to their priorities, and exposes no notion of position to the user
  • A priority queue has a mechanism to determine which item has the highest priority and provides access to the largest item in the queue at any given time


     

  • A priority queue needs a comparison rule that will never contradict itself
  • In order for a comparison rule to be robust in this way, it must define a total order relation, which is to say that the comparison rule is defined for every pair of keys and it must satisfy the following properties
    • Reflexive property – k <= k
    • Antisymmetric property – if k1 <= k2 and k2 <= k1, then k1 = k2
    • Transitive property- if k1 <= k2 and k2 <= k3, then k1 <= k3


     

  • A priority queue is a collection of elements, called values, each having an associated key that is provided at the time the element is inserted
  • A key-value pair inserted into a priority queue is called an entry of the priority queue
  • The name priority queue comes from the fact that keys determine priority used to pick entries to be removed
  • The two fundamental methods of a priority queue are as follows
    • insert (k, x) – insert a value x with key k
    • removeMin() – return and remove an entry with the smallest key