Saturday, July 9, 2016

How to deploy your project to Maven Central

So, you have finally got your project finialized, tested, and ready to go. You would probably want to make it available to users through their build system (Maven, Gradle,..). This post presents steps that you need to take to deploy your project to Maven Central.

1) Create a ticket in Sonatype for the creation of your Group ID:

  This can be done by creating an issue in Sonatype's tracker : https://issues.sonatype.org/. You usually get a response within one day.


2) Get your project ready to deploy:

   Before deploying your project, you need to make sure that your pom.xml contains a number of elements: project name, description, URL, license information, developer information, and SCM information. If you do not include these elements, your pom file will not be validated and you will not be able to deploy to Maven Central.

Here is a pom example: https://github.com/gwidgets/gwty-leaflet/blob/master/pom.xml

3) Snapshot Vs non snapshot :

If your release is a snapshot version, you need to include Sonatype's snapshots server. On deploy, Maven automatically detects if your version ends with -SNAPSHOT and deploys to the snapshot server.

<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
</distributionManagement>


4) Generating Javadocs and including sources:

Including javadocs and sources is also mandatory, and checked by Sonatype at release time. There are several ways you can do it, but the easiest way is to include Maven javadocs and sources plugins which automatically generates them for you on build time.

Maven javadoc plugin : https://maven.apache.org/plugins/maven-javadoc-plugin/
Maven source plugin:  https://maven.apache.org/plugins/maven-source-plugin/

5) Sign your jar and pom:

This is the trickiest part. To be able to successfully release your project to Maven central, you need to generate a signature using GPG which will be used by Sonatype to verify your articacts. First of all, you will need to install GPG. The next step is to generate a public/private key pair. This step is descibed in more details in GPG's manual. Aftewards, you need to distribute your public key to a key server. We use https://pgp.mit.edu/ which allows you to directly copy paste the key. There are plenty of servers, it's a matter of preference. You can refer once again to the manual for how to send your keys to the server. Once done, you can sign your artifacts, you will have to sign both the jar and the pom. You can either do it manually from the termnial using gpg or using maven gpg plugin: http://maven.apache.org/plugins/maven-gpg-plugin/

6) Prepare your deploy:

Before deploying you will need to configure the server and its access information:
<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
  <repository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  </repository>
</distributionManagement>

<settings>
  <servers>
    <server>
      <id>ossrh</id>
      <username>your-id</username>
      <password>your-pwd</password>
    </server>
  </servers>
</settings>

It's better to include these information in a build profile, so that they are not shared if you ever make your project source code open to public, and also to be able to reuse them for other projects.
It's also a good practice to include maven's source, javadocs, and gpg plugins in a build profile, to avoid having to include them in each project.

7) Deploy to staging:

deploying to staging can simply be done by invoking Maven's deploy goal:

mvn deploy

8) Relase your project to Maven Central:

At this stage, you will able to find your project on Sonatype. You need to go to https://oss.sonatype.org/ and click on staging repositories. After choosing your repository, you need to click on --> close, as shown below. Once the repository is closed, you can click on release and your project will be released to Maven Central.


Sunday, June 26, 2016

the Chain of Responsibility design pattern

The chain of responsibility is a fairly easy to use design pattern. Its main goal is to allow several objects to collaborate in order to solve a problem. Each object knows what it can do, and if the request does not fall into its scope of responsabilty, the objects passes it to the next one, and so on. The rationale behind using this pattern is to enforce separation of concerns and decouple a problem smaller sub-problems to make it easier to solve.

An analogy that might help understanding the pattern is when you call the customer support for your phone operator. When you call the support, you are asked about the category of your request, and then you are dispatched to the agent who has the skills to handle your request. If the agent sees that your request needs another set of skills, he forwards it to another agent, and so on until your request is fullfilled.

In this tutorial, we are going to implement the chain of responsability based on the example above.

First of all, we need an interface (or abstract class) that will constisturte the building block of our chain. Each object that implements the interface will either process the request or forwards it to the next object.

public interface RequestHandler {
 
 public void process(Request request);
 
 public void setNext(RequestHandler handler);

}
Next we need to define the handlers that implements our interface.

public class SecurityRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.SECURITY){
   System.out.println("Your request" + request.description + " is being handled by the security departement");
  }else if (nextHandler != null){
   System.out.println("Your request is being forwarded to another departement");
   nextHandler.process(request);
  }
  
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }
public class InfrastructureRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.INFRACSTRUCTURE ){
   System.out.println("Your request: " + request.description + " is being handled by the financial departement");
   }else if (nextHandler != null){
    System.out.println("Your request is being forwarded to another departement");
    nextHandler.process(request);
   }
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }

}


public class FinancialRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.FINANCIAL ){
  System.out.println("Your request " + request.description + " is being handled by the financial departement");
  }else if (nextHandler != null){
   System.out.println("Your request is being forwarded to another departement");
   nextHandler.process(request);
  }
  
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }

}
For illustration purposes the Request POJO looks like:


public class Request {
 
 String description;
 
 int criticityLevel;
 
 public Request(String description, int clearanceLevel) {
  this.description = description;
  this.criticityLevel = clearanceLevel;
 }

 public String getDescription() {
  return description;
 }

 public int getCriticityLevel() {
  return criticityLevel;
 }

}
Finally, we can chain our handlers according to their level of responsibility.

public class Main {
 
 public static void main(String[] args){
  
  RequestHandler handler1 = new SecurityRequestHandler();
  RequestHandler handler2 = new InfrastructureRequestHandler();
  RequestHandler handler3 = new FinancialRequestHandler();
  
  
  
  handler1.setNext(handler2);
  handler2.setNext(handler3);
  
  Request request = new Request("Error in the last month bill", CriticityLevel.FINANCIAL);
  Request request2 = new Request("Poor network coverage", CriticityLevel.INFRACSTRUCTURE);
  
  System.out.println("--------------Request1");
  handler1.process(request);
  
  System.out.println("--------------Request2");
  handler1.process(request2);
  
  
  
 }

}
Result:






Tuesday, June 7, 2016

Introduction to Rx Java.


It took me lots of reading to get my head around Rx Java, so I decided to write something to simplify it for beginners. Rx Java is a framework or an extention of the Java language that introduces a new way of designing applications called reactive programming. Reactive programming involves a number of principles, but for simplicity sake let's just say that it is about developing applications that reacts quickly and effectively to changes in state. Rx Java can also be defined as advanced form of the gang of four Observer pattern. Rx Java was first developed for internal use of Netflix, and was then open sourced. There are two very important notions to retain while working with Rx Java: Observables, and Subscribers.

Observables are the main concept of Rx Java. They are entites that can be observed by a number of subscribers, and that notifies all of them when a change in state occurs.

A subscriber receives updates from Observables and takes actions. On subsription, a subscriber defines three things: what it will do with the data, what it will do in case of an error, and what he will do on completion.

Let's go through a first example:

List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());

 Observable observable = Observable.from(list);

 observable.subscribe(new Observer<Integer>(){
   public void onCompleted() {
    System.out.println("Completed");
   }

   public void onError(Throwable arg0) {
    // Do something on error
   }

   public void onNext(Integer arg0)   {
    System.out.println(arg0 + " ");
   }
   });
Result:

In this example, we created an observable from an iterable. The observable provided the values to the subscriber as a stream. The observable printed each value on reception and printed the word "Completed" on completion.  

Let's explore another way of creating Observables. Suppose we have a service that monitors traffic in an intersection, and sends  updates to a terminal station as the state of traffic changes, we can create our observable using the create() method, and defining what we send to our observers inside the call() method. 

Observable<String> trafficStream = Observable.create(new OnSubscribe<String>() {
  @Override
   public void call(Subscriber<String> sub) {
     //Simulation of a stream  
      while(true){
         sub.onNext(trafficState[random.nextInt(3)]);
      } 
   }
  })

Notice that we used the onNext method to send the data to our subscriber.

Once we subscribe to our observer :

trafficStream.subscribe(new Observer<String>(){
   @Override
   public void onCompleted() {
    
   }
   @Override
   public void onError(Throwable arg0) {
    
   }
   @Override
   public void onNext(String arg0) {
    System.out.println("Traffic state : " + arg0);
   } 
    
   });
We get:

Composing Observers

There are situation where developpers would need to compose several observers into one to be able to subscribe to all of them at once. Rx Java provides several ways of composing observables.

For composing observables of the same type, Rx Java provides the merge() method:

Observable.merge(observable1, observable2)
   .subscribe(new Observer<Integer>(){
   @Override
   public void onCompleted() {
    // Merged completion action
    
   }

   @Override
   public void onError(Throwable arg0) {
    // Merged error handling
    
   }

   @Override
   public void onNext(Integer arg0) {
    // Merged completion action
    System.out.println(arg0);
   }
    
    
   });

For composing observables of different types, Rx Java provides the zip() method:

Observable.zip(observable, observable2, new Func2<Integer, Double, Map<Integer, Double>>(){
    @Override
    public Map<Integer, Double> call(Integer arg0, Double arg1) {
     // TODO Auto-generated method stub
     Map<Integer, Double> map = new HashMap<Integer, Double>();
     map.put(arg0, arg1);
     return map;
    }
     
     
    }).subscribe(new Observer<Integer, Double>(){

    @Override
    public void onCompleted() {
     // TODO Auto-generated method stub
     
    }

    @Override
    public void onError(Throwable arg0) {
     // TODO Auto-generated method stub
     
    }

    @Override
    public void onNext(Map<Integer, Double> arg0) {
     // TODO Auto-generated method stub
     arg0.forEach((k, v) -> System.out.println(" " + k + " " + v ));
     
    }
     
    });

Interesting videos that explains core concepts of reactive programming:
https://www.youtube.com/watch?v=dwP1TNXE6fc
https://www.youtube.com/watch?v=7D9QfMj_KwI

Tuesday, May 17, 2016

Spring boot quick overview


If there is a word they care about at Pivotal, it is production. Deploying apps and services to production effectively is what companies strive for, sometimes without finding the perfect formula. Spring Boot is meant to overcome this challenge, for Spring framework users. Imagine you have a genie that grants your software developement wishes before you even know them,  or, using a more serious definition, a framework that helps you get rid of all the boiler plate code and configuration, and focus on things that matter. It uses your build system (Maven or Gradle) to predict the things that you can possibly do with your application, and auto configure them for you. For example, if you include a Spring Web dependency, Spring Boot gently includes an embedded Tomcat server with an 8080 default port in your jar, no need to deploy, it's already done for you. Another wonder of Spring boot is database configuration. Once you include a database driver, it auto configures the data access layer for you. It also picks up any schemas or data files (.sql) and executes them on start up. Impressive, ha? This is only a drop in the bucket of what Boot could do.
 Spring Boot has some downsides as well. Additional effort is required by the developper to modify the default configuration if  needed, which is not always easy. In any case, let's give it a try.

In this tutorial, we will go through an example of how to quickly build a Rest application with an embeded database using Spring Boot.

We will start first by using SPRING INITIALIZR to quicky bootstrap our app.






There is a bunch of options to choose from. In our case, we chose: Web, JPA, and H2 database dependencies. We can now click on generate to download the project, and import it into an IDE ( eclipse for this tutorial).

We will then take care of the data access by creating our model object and the corresponding data access object (dao) to perform operations on the database.

 @Entity(name="users")
public class User {
 
 @Id @GeneratedValue
 int id;
 String userName;
 String firstName;
 String lastName;
 
 
 public User(){
  
  
 }

//.. getters & setters

}

Using Spring data, there is no need to programtically implement the operations, all we need to do is to extend CrudRepository.

public interface UserDao extends CrudRepository{
      public User findByUserName(String userName);
}
Notice that we have added a findByUserName method, which is also automatically implemented by Spring Data (based on the name of the method). For those, not familiar with Spring data this what this framework is about.

Next we can start implementing our Rest endpoints:



@Controller
public class UserController {
 
 @Autowired UserDao userdao;
 
 @RequestMapping(value="/users", method=RequestMethod.GET)
 public @ResponseBody List<User> getAllUsers(){
  return (List<User>) userdao.findAll();
 }
 
 @RequestMapping(value="/users", method=RequestMethod.POST)
 public ResponseEntity<Void> addUser(@RequestBody User newUser){
     if(newUser != null){
       if( userdao.save(newUser) == null){
         return new ResponseEntity<Void>(HttpStatus.SERVICE_UNAVAILABLE);
       }else{
        return new ResponseEntity<Void>(HttpStatus.CREATED);
       }
     }else{
      return new ResponseEntity<Void>(HttpStatus.CONFLICT);
     }
 }
 
 @RequestMapping(value="/users/{userName}", method=RequestMethod.DELETE)
 public ResponseEntity<Void> deleteUser(@PathVariable String userName){
  User searchedUser = userdao.findByUserName(userName);
  if(searchedUser != null){
   userdao.delete(searchedUser);
   return new ResponseEntity<Void>(HttpStatus.OK);
  }else{
   return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
   
  }
  
 }

}

We defined three endpoints: for listing, adding, and deleting. For demonstration purposes, I added some sample data in /resources forlder, which is also automatically picked by Spring Boot and applied to the database on startup.

insert into users values (1, 'user1', 'john', 'doe');
insert into users values (2, 'user2', 'long', 'beard');
insert into users values (3, 'user3', 'zakaria', 'amine');


Finally, we can launch our app by simply executing the Main class :

 
@SpringBootApplication
public class SpringbootDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringbootDemoApplication.class, args);
 }
}
Our Rest API is all set. If we go to /users on a browser we get:


I created a html page with some Angular Js code to test the operations. Since the page was named "index.html",  Spring Boot automatically picked up the name and defined it as a welcome page.

I will not say more on the front end part since it is not the focus of this tutorial. You can find the source code here.

Total time in building all this and deploying it: less than 10mins.

Spring Boot is new way of getting things quickly into production, and it keeps on getting better with every release.

The whole application is available here:  https://github.com/zak905/springboot-demo.git

Tuesday, April 26, 2016

Introduction to Java 8 Streams Part 2 - Parallel Streams



We have seen in the first part of this series how to use streams which are considered one of the key features of Java 8. In this post, we will walk through a particular feature of streams: Parallel streams. To give a rather simplistic definition, parallel streams involves doing the work in parallel using more resources to finish faster. They can be used by calling a magic method: parallel(). Java 8 hides all the complexity behind dividing the work and parallelizing it which relieves the developer from carring about things like threads and concurrency. However, many have reservations about using parallel streams for several reasons. Before going into the pitfalls of parallel streams, let's go through a quick example that illustrates their "good" side. Suppose we want to sum all even integers from 1 to one billion, one way of doing it using streams would be:

 static long sum = 0;
    
    public static void main(String[] args){
        
      IntStream.rangeClosed(1, 1000000000)
                .filter(e -> e % 2 == 0)
                .forEach(e -> addToSum(e));
                
    }
    
    public static void addToSum(int num){
      sum += num;
        
    }
The excution time gives:


adding paralllelization to our stream:

static long sum = 0;
    
    public static void main(String[] args){
        
      IntStream.rangeClosed(1, 1000000000)               
                .parallel()
                .filter(e -> e % 2 == 0)
                .forEach(e -> addToSum(e));
                
    }
    
    public static void addToSum(int num){
      sum += num;
        
    }

The excution time gives:

Notice that using parallel(), we have reduced the execution from 27 seconds to 18 seconds which seems like a legitimate advantage in the favor of parallel streams. Let's try and print the result sum for both cases :

Without parralel(): 250000000500000000
With parralel() (try 1): 144666330514402188
With parralel() (try 2): 146443671692846754
With parralel() (try 3): 142515120769803018


Any thoughts? We have gained on excution time, but the result is wrong, and it is not anywhere closer to the correct result. Why is that? The main reason why this occurs is that multiple threads are trying to access a shared variable in parallel. 

So think twice before using parallel stream. Because you can parallelize, it does not mean you should. Questions that the developer needs to ask before making using this construct are: is the collection/environement thread safe? is the problem large enough to be worth parralelizing? Are the resources enough? Hoping that this brief example shed light on what happens behind the curtains when using parallel(). 




Monday, April 18, 2016

Google Code Jam 2016: comments and problem solutions.



Progamming contests are a good measure of how great you are as a programmer. Besides from the broad and theoritical questions of job interviews, contests can be an accurate determinant of one's programming ability. Google Code Jam is a global contest that challenges programmers around the world to solve puzzles with different levels of difficulty. This year was my first participation, and I have to say some problems were tough. Although I did not qualify to the second round because of time consideration (out of the 27 hours given, I only programmed 12 hours),  it was a good programming experience overall.  I used Groovy for its scripting capabilities, and its dynamic typing. I advice programmers to participate in next year's edition. Here are links for two of the problems that I could solve on time.

Problem A: Counting Sheep.

Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.

Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows:

  • N = 1692. Now she has seen the digits 1, 2, 6, and 9.
  • 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9.
  • 3N = 5076. Now she has seen all ten digits, and falls asleep.

What is the last number that she will name before falling asleep? If she will count forever, print INSOMNIA instead.

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a single integer N, the number Bleatrix has chosen.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the last number that Bleatrix will name before falling asleep, according to the rules described in the statement.

Limits

1 ≤ T ≤ 100.

Small dataset

0 ≤ N ≤ 200.

Large dataset

0 ≤ N ≤ 106.

Sample


Input
 

Output
 
5
0
1
2
11
1692

Case #1: INSOMNIA
Case #2: 10
Case #3: 90
Case #4: 110
Case #5: 5076


In Case #1, since 2 × 0 = 0, 3 × 0 = 0, and so on, Bleatrix will never see any digit other than 0, and so she will count forever and never fall asleep. Poor sheep!

In Case #2, Bleatrix will name 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The 0 will be the last digit needed, and so she will fall asleep after 10.

In Case #3, Bleatrix will name 2, 4, 6... and so on. She will not see the digit 9 in any number until 90, at which point she will fall asleep. By that point, she will have already seen the digits 0, 1, 2, 3, 4, 5, 6, 7, and 8, which will have appeared for the first time in the numbers 10, 10, 2, 30, 4, 50, 6, 70, and 8, respectively.

In Case #4, Bleatrix will name 11, 22, 33, 44, 55, 66, 77, 88, 99, 110 and then fall asleep.

Case #5 is the one described in the problem statement. Note that it would only show up in the Large dataset, and not in the Small dataset.


My Solution: https://github.com/zak905/googlecodejam/blob/master/2016/Qualifying%20Round/CountingSheep.groovy


Problem B: Revenge of the Pancakes.

The Infinite House of Pancakes has just introduced a new kind of pancake! It has a happy face made of chocolate chips on one side (the "happy side"), and nothing on the other side (the "blank side").
You are the head waiter on duty, and the kitchen has just given you a stack of pancakes to serve to a customer. Like any good pancake server, you have X-ray pancake vision, and you can see whether each pancake in the stack has the happy side up or the blank side up. You think the customer will be happiest if every pancake is happy side up when you serve them.
You know the following maneuver: carefully lift up some number of pancakes (possibly all of them) from the top of the stack, flip that entire group over, and then put the group back down on top of any pancakes that you did not lift up. When flipping a group of pancakes, you flip the entire group in one motion; you do not individually flip each pancake. Formally: if we number the pancakes 1, 2, ..., N from top to bottom, you choose the top i pancakes to flip. Then, after the flip, the stack is i, i-1, ..., 2, 1, i+1, i+2, ..., N. Pancakes 1, 2, ..., i now have the opposite side up, whereas pancakes i+1, i+2, ..., N have the same side up that they had up before.
For example, let's denote the happy side as + and the blank side as -. Suppose that the stack, starting from the top, is --+-. One valid way to execute the maneuver would be to pick up the top three, flip the entire group, and put them back down on the remaining fourth pancake (which would stay where it is and remain unchanged). The new state of the stack would then be -++-. The other valid ways would be to pick up and flip the top one, the top two, or all four. It would not be valid to choose and flip the middle two or the bottom one, for example; you can only take some number off the top.
You will not serve the customer until every pancake is happy side up, but you don't want the pancakes to get cold, so you have to act fast! What is the smallest number of times you will need to execute the maneuver to get all the pancakes happy side up, if you make optimal choices?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a string S, each character of which is either + (which represents a pancake that is initially happy side up) or - (which represents a pancake that is initially blank side up). The string, when read left to right, represents the stack when viewed from top to bottom.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the minimum number of times you will need to execute the maneuver to get all the pancakes happy side up.

Limits

1 ≤ T ≤ 100.
Every character in S is either + or -.

Small dataset

1 ≤ length of S ≤ 10.

Large dataset

1 ≤ length of S ≤ 100.

Sample


Input
 

Output
 
5
-
-+
+-
+++
--+-

Case #1: 1
Case #2: 1
Case #3: 2
Case #4: 0
Case #5: 3

In Case #1, you only need to execute the maneuver once, flipping the first (and only) pancake.
In Case #2, you only need to execute the maneuver once, flipping only the first pancake.
In Case #3, you must execute the maneuver twice. One optimal solution is to flip only the first pancake, changing the stack to --, and then flip both pancakes, changing the stack to ++. Notice that you cannot just flip the bottom pancake individually to get a one-move solution; every time you execute the maneuver, you must select a stack starting from the top.
In Case #4, all of the pancakes are already happy side up, so there is no need to do anything.
In Case #5, one valid solution is to first flip the entire stack of pancakes to get +-++, then flip the top pancake to get --++, then finally flip the top two pancakes to get ++++.
My Solution: https://github.com/zak905/googlecodejam/blob/master/2016/Qualifying%20Round/RevengeOfPancakes.groovy
Contest main page: http://code.google.com/codejam/

Tuesday, April 5, 2016

Introduction to testing with Mockito


Mocking helps alleviate the burden of initiliazing and setting up classes prior to the start of a test. While using a mocking framework is not something indispensable, mocking promotes modularity and can make the life of a developer much easier. There are several mocking Java frameworks that can be coupled with a test framework. Some of the well know ones are: Mockito, EasyMock, and JMockit. In this tutorial, we will go through some basic use cases of mocking. We will be using Mockito and JUnit for demonstration purposes.

Mocking objects and method calls


Account account = Mockito.mock(Account.class);

when(account.getUsername()).thenReturn("opencode");
when(account.getPassword()).thenReturn("password1");

//Test successful
assertEquals(account.getUsername(), "opencode");
assertEquals(account.getPassword(), "password1");

//.....

//Lists can be mocked as well using @Mock
@Mock
List<Profile> profileList;

Profile profile1 = Mockito.mock(Profile.class);
Profile profile2 = Mockito.mock(Profile.class);
  
when(profile1.getDescription()).thenReturn("profile1");
when(profile2.getDescription()).thenReturn("profile2");
  
  
when(profileList.get(0)).thenReturn(profile1);
when(profileList.get(1)).thenReturn(profile2);

//Test successful
assertEquals(profileList.get(0).getDescription(), "profile1");
assertEquals(profileList.get(1).getDescription(), "profile2");


Verifying method invocation and the frequency of invocation


//...

System.out.println(account.getUsername());
//verfies that getUsername() is called -- success 
 verify(account).getUsername();

 //verfies that getUsername() is called twice -- failed
 verify(account, times(2)).getUsername();

         

Testing exceptions


//Junit 4.7 or higher
@Rule
public ExpectedException exception = ExpectedException.none();

@Mock
List<Profile> profileList;

when(profileList.get(2)).thenThrow(NullPointerException.class);

//.....
            
 @Test 
public void testException(){
   //result -- success
     exception.expect(NullPointerException.class);
     profileList.get(2);
     }


There are off course more advanced possiblities offered by Mockito, and other frameworks as well.