12/09/2018

[Java8] Supplier Functional Interface

From wikipedia

  • Manufacturer, uses tools and labour to make things for sale
    • Processor (manufacturing), converts a product from one form to another
  • Wholesaler, sells goods or merchandise to retailers
  • Merchant, a professional dealing with trade

From java definition

Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked.

Here are some test cases.
Gets a result.

   @Test
   public void testGetCurrentDate()
   {
      //when
      Supplier<LocalDateTime> dateTimeSupplier = () -> LocalDateTime.now();

      //verify
      Assertions.assertNotNull(dateTimeSupplier.get());
   }

12/07/2018

[Java8] Function interface

Function interface has an abstract method "apply" which take argument of type T and must returns a result of type R.

Java definition

Represents a function that accepts one argument and produces a result.

public interface Function<T, R> {
    R apply(T t);
    ...
}

Here are some test cases.
Applies this function to the given argument.

    @Test
   public void testFuncApply()
   {
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Assertions.assertEquals(Integer.valueOf(100), sqrt.apply(10));
   }

A composed function that first applies the function to its input, and then applies this to the result.

 @Test
   public void testFuncCompose()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<String, Integer> input = sqrt.compose(((s) -> Integer.parseInt(s)));
      //when
      Integer result = input.apply("9");
      //verify
      Assertions.assertEquals(Integer.valueOf(81), result);
   }

A composed function that first applies this function to its input and the applies the function to the result.

   public void testFuncAndThen()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<Integer, Integer> times = sqrt.andThen((num) -> num * num);
      Function<String, Integer> input = times.compose(((s) -> Integer.parseInt(s)));

      //when
      Integer result = input.apply("10");

      //verify
      Assertions.assertEquals(Integer.valueOf(10000), result);
   }

A function that always returns its input argument.

   @Test
   public void testIdentity()
   {
      //given
      Map<String, String> result =
         Arrays.asList("a", "b", "c")
            .stream()
            .collect(Collectors.toMap(Function.identity(), str -> str));
      //verify
      Assertions.assertTrue(result.size() == 3);
      Assertions.assertEquals(result.get("a"), "a");
      Assertions.assertEquals(result.get("b"), "b");
      Assertions.assertEquals(result.get("c"), "c");
   }

[Java8] Consumer Functional Interface

From wikipedia

A consumer is a person or organization that use economic services or commodities.

The consumer is the one who pays something to consume goods and services produced. As such, consumers play a vital role in the economic system of a nation. Without consumer demand, producers would lack one of the key motivations to produce: to sell to consumers. The consumer also forms part of the chain of distribution.

From Java definition

Represent an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, is expected to operate via side-effects.

Its main functional name is "accept", but why not call "consume" method. Does it mean consumer only accepts the input argument to consume?

Here are some test cases.
Performs this operation on the given argument.

  @Test
   public void testConsumerAccept()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      //when
      addStudent.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

A composed consumer that performs, in sequence, this operation followed by the code after operation

   public void testConsumerAcceptAndThenPrint()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      Consumer<String> printStudentAfterAdding = addStudent.andThen(name -> System.out.println("added " + name));
      //when
      printStudentAfterAdding.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

11/16/2018

Retry Design

Sometimes, Network is inherently unreliable. Connections will occasionally time out or be dropped. For some reasons, we still want to try to establish a connection to a remote endpoint which went down.

There is straightforward answer which wrote down below code to resolve it.

      try
      {
          this.conn = connect();
      }
      catch (Exception e)
      {
         for (int i = 0; i < maxAttempts; i++)
         {
            try { Thread.sleep(1000); } catch (InterruptedException e) {};
            this.conn = connect();
         }
      }

But the solution is difficult to maintain and a lack of flexibility. If we are using java8, this may change below to more be useful.

public static <T> Object retry(Supplier<T> function, int retryCount) throws Exception
   {
      while (0 < retryCount)
      {
         try
         {
            return function.get();
         }
         catch (Exception e)
         {
            if ((retryCount--) == 0)
               throw e;
         }
      }
      return null;
   }
   

Based on above two solutions, we still try to add extra code into connection logic and the unnecessary design. I think there's much better to use if you are using spring or AOP concept.

 @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500))
 public void establishConnection() {
    this.connection = newConnection();
 } 

Code is simply and easy to use.

Reference

spring-retry

11/01/2018

tldr

tldr is a small tool to help you cannot always remember the arguments to many commands as like me. TL;DR originates for "Too long; Didn't Read" in Internal Slang, where it is used to indicate that a long text has been skipped...

We like simplified man pages focused on practical example like below:

➜  ~ tldr lsof
Local data is older than two weeks, use --update to update it.


lsof

Lists open files and the corresponding processes.
Note: Root privileges (or sudo) is required to list files opened by others.

- Find the processes that have a given file open:
    lsof path/to/file

- Find the process that opened a local internet port:
    lsof -i :port

- Only output the process ID (PID):
    lsof -t path/to/file

- List files opened by the given user:
    lsof -u username

- List files opened by the given command or process:
    lsof -c process_or_command_name

- List files opened by a specific process, given its PID:
    lsof -p PID

- List open files in a directory:
    lsof +D path/to/directory

keep it simple, stupid.

tldr in alfred

Really enjoy this plugin in alfred.

https://github.com/cs1707/tldr-alfred

tldr github

https://github.com/tldr-pages/tldr

10/27/2018

sift

I like sift tool which is best than most other grep tools, to search the huge log and code base.

sift also is easy customizations to default ignore case as below.

An example config file: ~/.sift.conf

{
      "BinarySkip": true,
      "Git": true,
      "GroupByFile": true,
      "IgnoreCase": true
  }

Performance report

https://sift-tool.org/performance

Usage

https://sift-tool.org/samples

9/14/2018

Using curl to test port connectivity

It's often necessary to troubleshoot port connectivity as common env, but not found telnet.

curl -v telnet://target ip address:desired port number

curl -v telnet://dragon1:22
* Rebuilt URL to: telnet://dragon1:22/
* Trying 192.168.3.31...
* TCP_NODELAY set
* Connected to dragon1 (192.168.3.31) port 22 (#0)
SSH-2.0-Sun_SSH_1.1.4