Engineering Lead. I write about software development, and sometimes writing itself. Mostly original.

Singapore Nationwide AWS LLM League 2024

Congratulations to the 5 finalists

Congratulations to the 5 finalists

The Singapore Nationwide AWS LLM League 2024 concluded today with the grand finale at Raffle City Convention Center. The 5 finalists competed on stage for the top prizes including Amazon vouchers, Amazon Echo, and exclusive swags.

Each finalist, using their own finetuned Llama-3–8B model, answers a series of questions on Singapore culture. Their answers were then shared with a panel of 1 AI judge and a panel of 5 human judges for scoring. They were also shared with hundreds of live and virtual audiences for voting. Fan votes accounted for 20% of each answer’s final score while each AI and human panel contributed 40%.

My Notes of the Singapore TechLawFest 2024

GenAI everywhere in Singapore TechLawFest 2024

GenAI everywhere in Singapore TechLawFest 2024

I attended some discussions and showcases in the Singapore TechLawFest 2024. Here are my notes.

GenAI can automate many tasks and complete up to 50% to 70% of the work. Human is still needed to complete the remaining.

A law firm in the Philippines shared that a 2.5-hour drafting by junior lawyer can be completed by their AI solution in less than a minute.

Hugo - Displaying Quotes the Medium styles

Please ignore the \ in front of { in code examples. It is used to prevent Hugo from processing the shortcodes even in code block

The Block Quote

This is a block quote

> This is a block quote

The Pull Quote

We need a custom quote.html shortcode and some custom CSS

The quote shortcode:

# quote.html

{{$quote := .Get 0}}

<blockquote class="medium-quote">
  <p>
    {{ markdownify $quote }}
    {{ markdownify .Inner }}
  </p>
</blockquote>

The CSS:

Hugo - Displaying Images the Medium way

Please ignore the \ in front of { in code examples. It is used to prevent Hugo from processing the shortcodes even in code block

The Markdown way

![alt title](1_nHC2UMz-xJM-lvPPwSh_vQ.webp)

title

Though it is recommended, the alt-title is optional. The above can be expressed as ![alt title](path-to-image.jpg)

Pros:

Cons:

The Medium way

{{\< figure src="1_nHC2UMz-xJM-lvPPwSh_vQ.webp" caption="optional caption" \>}}
optional caption

optional caption

Pros:

Behavior Driven Development (BDD) with Selenium in Python

This is a continuation from my previous article where we learned the basic of Selenium and how to program it in Python to perform UI automation testing.

Getting started on UI automation testing using Selenium with Python

Five Minimum Viable Interview Questions series — Updated 17 Feb 2023
Five Minimum Viable Interview Questions series — Updated 17 Feb 2023

Interviewer: ask them if your interview is running out of time. Interviewee: practice them if your preparation is running out of time.

How to join video files in a semi-automated way

TLDR;

You will need the following:

Create a script that use ffmpeg to join video files then save the script and grant it necessary execute permission (on Mac and Linux). Make sure ffmpeg is on executable path, usually the $PATH or %PATH% variable

On Windows, you can use the below.

@echo off
setlocal enabledelayedexpansion

del concat.txt

rem Get the total number of parameters
set "totalParams=0"
for %%# in (%*) do set /a "totalParams += 1"

set /a "to_merge=%totalParams%-1"

echo There are a total of %to_merge% video to merge

rem Loop through all parameters except the last one
set "index=0"
set "outputfile="
for %%f in (%*) do (
  set /a "index+=1"
  if !index! neq %totalParams% (
    set "F=%%f"
    set "F=!F:\=/!"
    set "F=!F:"=!"
    echo file !F!
    echo file !F! >> concat.txt
  ) else ( set "outputfile=%%f" )
)

echo output file %outputfile%

ffmpeg -safe 0 -f concat -i concat.txt -c copy %outputfile%

Assume the script is named concat.cmd, use the command concat.cmd <inputfile> <inputfile> <outputfile as the last argument> to join individual input files to a single output file. For example, to join 2 files video-1.mp4 and video-2.mp4 to a single combine.mp4, we type the following

SOLID in Action: the Dependency Inversion Principle

Photo by ocd studio on Unsplash

Photo by ocd studio on Unsplash

The Dependency Inversion Principle (DIP)

Naive application of traditional software development methods (e.g. SADT or Structured Analysis and Design Technique), in the past, often resulted in a type of relationship where high-level modules depended on lower implementation details. This form of relationship often leads to rigidity, fragility, and immobility. These are the symptoms of bad design according to Robert C. Martin.

A naive application of top-down approaches can lead to bad design. Source: R.C.M paper

A naive application of top-down approaches can lead to bad design. Source: R.C.M paper

Five Minimum Viable Interview Questions series — Updated 17 Feb 2023

Photo by Wes Hicks on Unsplash

Photo by Wes Hicks on Unsplash

Rationale

Let’s face it. A developer is expected to know A LOT these days.

A typical job requirement (screenshot)

A typical job requirement (screenshot)

And that makes interviewing a candidate hard because there is never enough time to ask all the necessary questions.

On the other hand, that also makes preparing for an interview hard because there are too many areas and details to prepare for.

“Look Good to Me — Approve”

https://chrome.google.com/webstore/detail/lgtm-approve/odeollamfjdmamamonbfigajkhakcmag/

https://chrome.google.com/webstore/detail/lgtm-approve/odeollamfjdmamamonbfigajkhakcmag/

A chrome extension that automatically adds a comment while approving the request. Doing so cements the collaboration between the reviewer and the merge request’s submitter

The comment is defaulted to “LGTM” (Look Good to Me) and can be customized.

The extension is available on Chrome Web Store at https://chrome.google.com/webstore/detail/lgtm-approve/odeollamfjdmamamonbfigajkhakcmag/

How it works

The extension works by replacing Gitlab’s “Approve” or “Approve Additionally” button with an upgraded button that adds a comment (e.g. “LGTM”) to the merge request while approving the request.

SOLID in Action: the Interface Segregation Principle

Photos by Eugen Str on Unsplash

Photos by Eugen Str on Unsplash

Photos by Patrick on Unsplash

Photos by Patrick on Unsplash

If you are going to build a house, a table, or a chair, what is your preferred option? The multiple tools on the first picture or one Swiss knife on the second?

Yep, you are right. If you want to create something useful that last for years, you need specialized tools. The same thinking applies to software development, if you want to create a serious application, you need specialized components represented by their own, purposely designed interfaces. The Interface Segregation Principle (ISP) is available to guide the creation of those interfaces.

AFF Cup needs VAR

Thailand comfortably beat Vietnam 1–0 on home soil to seal a 3–2 aggregate win and retain the crown for yet another 2 years. Theerathon Bunmathan was voted the most valuable player of the tournament.

What impressed me most about Theerathon was not his consistent and superb performance but what he said after the match. Theerathon reportedly said that he wanted VAR to be available in future AFF cups because all participating teams are neighbors and should improve their games together instead of committing faults or injuring each other.

Are you a full-stack developer?

Photo by Desola Lanre-Ologun on Unsplash

Photo by Desola Lanre-Ologun on Unsplash

Did you know that anyone in a Scrum team can be called a “developer”?

…developers, researchers, analysts, scientists, and other specialists do the work. We use the word “developers” in Scrum not to exclude, but to simplify. If you get value from Scrum, consider yourself included— The official Scrum Guides

We will, however, discuss this title in a more focused and traditional context in the following sections. Just bear in mind the strong association between the term “developer” and “agile” due not only to the agile movement but the nature of software development itself.

Top Publications For Technical Writers — Jan 2023

Photo by Scott Graham on Unsplash

Photo by Scott Graham on Unsplash

The Incumbents

Toward Data Science

Your home for data science. A Medium publication sharing concepts, ideas and codes.

Followers: 652K (as of 17 Jan 2023)

Review: The most popular tech-oriented publication on Medium with huge followers on Medium, Twitter, and LinkedIn. If you write about data science or its related topics, this is one to apply for. Be prepared to submit your best writing as the submission guideline is comprehensive.

Kotlin, Spring Data, and MongoDB: Develop a “GET /comments” API endpoint

Photo by Pratiksha Mohanty on Unsplash

Photo by Pratiksha Mohanty on Unsplash

TL;DR

The 4 flavors are:

  1. Retrieve ALL — more details at step #4
  2. Filtering by exact matching — more details at step #5
  3. Filtering by partial/substring matching — more details at step #6
  4. Filtering by full-text search — more details at step #7

Sample codes: https://github.com/geraldnguyen/kotlin-springdata-mongodb

#1 — Create a Kotlin + Spring Data + MongoDB project

Let us start by creating a simple project with Spring Initializr:

Shift Left Testing

What is Shift Left Testing?

A picture is worth a thousand words. Here are how Shift Left differs from the traditional approach

Source: https://www.bmc.com/blogs/what-is-shift-left-shift-left-testing-explained

Source: https://www.bmc.com/blogs/what-is-shift-left-shift-left-testing-explained

How does my team shift left?

We started with unit testing, by developers, for their own codes. This is the easiest shift to implement, though it still takes time, effort, and patience to get it right. I recommend Pragmatic Unit Testing in Java 8 with JUnit if you want quickly level-up

What is a 2-Factor Authentication(2FA)?

The Wolf, the Kid, and the Goat

You probably have heard of this popular fable before.

Mother Goat in her wisdom had carefully secured her house and her Kid before going out. She even reminded her Kid to check the password before opening the door. Her password was good. It was very long and contained non-alphabets and special characters.

As fate had it, a Wolf was nearby, he eavesdropped and learned of the mother’s password. He was so sure of filling his belly. He even mimicked the way mother Goat softly said her password

#STYOut or #STYSTAY — What is better for Indonesian Football?

Source: https://zingnews.vn/

Source: https://zingnews.vn/

The Garuda team lost 0–2 to the Golden Dragon team on Monday, thus failing to reach the AFF Mitsubishi Electric Cup’s final. For a team from a football-crazed Indonesia, the loss was heartbreaking for many.

Some took to social media calling for the sacking of coach Shin Tae-Yong. The tag #STYOut has been trending among Indonesian fans. Some were calmer. They defended him. #STYSTAY has been trending as well. As of 11 Jan 2023, #STYSTAY appears to have an upper hand.

Five Minimum Viable Spring REST Interview Questions

Photo by Christina @ wocintechchat.com on Unsplash

Photo by Christina @ wocintechchat.com on Unsplash

This is part of my Five Minimum Viable Interview Questions series where I research and compile Five essential interview questions on each interview topic. All of these questions aim to assess real and practical skills expected at work

#1 — What is REST API?

This question assesses the breadth and depth of a candidate’s understanding of REST API concepts.

SOLID in Action — the Liskov Substitution Principle

Let us start with a question:

Can social media connections substitute for real life friends and family?

Well, it depends on how we define “connection”. If we have it as below, then according to the Liskow Substitution Principle (LSP), the answer is No.

Connection classes

Connection classes

Before we go further into this example, let’s back it up a bit to study the official definition of LSP.

There is some math but I promise to keep it brief

DevOps: Divide and Conquer with Gitlab Parent-Child Pipeline

Gitlab parent-child pipeline

Gitlab parent-child pipeline

Scenario

You are building a pipeline that helps your team reset test data in different non-prod environments such as Test and Sandbox.

Under each environment, there are several application services or databases to clear. Let’s call them A, B, and C.

Trivial Approach

You can create 3 separate jobs for each environment

Trivial approach: 3 separate jobs for each environment

Trivial approach: 3 separate jobs for each environment

AFF Championship and the love for football that unites people

The biennial ASEAN Football Federation (AFF) Championship in 2022 has started its first semi-final leg with a draw between Indonesia and Vietnam yesterday.

It was a tense match with both teams unable to score in front of about 50,000 spectators in Gelora Bung Karno Stadium. That is a huge turnout in a country severely affected by the Covid pandemic just 2 years ago.

They will meet again for the second leg on Monday at My Dinh stadium on Monday. Greeting the Indonesia team would be at least 30,000 home fans there.

Maven — 3 Free Resources for Beginner and Intermediate Java Developers

Screenshot of a Maven POM file

Screenshot of a Maven POM file

Maven is the most popular build and dependency management system from the Apache Foundation.

If you plan to develop serious applications in Java or if you have just started to, you have better pick up Maven. I have just the resources for you below to learn about it and move from Beginner to Intermediate in no time.

Beginner tutorial

I often recommend Baeldung.com to my friends for beginner-level tutorials. They did it again here with this simple and easy-to-follow Maven tutorial

The Home Deity is Not Divine

Photo by Chinh Le Duc on Unsplash

Photo by Chinh Le Duc on Unsplash

The title is loosely translated from a Vietnamese idiom

Bụt chùa nhà không thiêng

Literally translated, the idiom is about a Buddhist Saint (Vietnamese: bụt) prayed to in a pagoda (Vietnamese: chùa) close to or within the home (Vietnamese: nhà) being non-divine (Vietnamese: không thiêng)

Usages

The idiom has 2 common usages. One is a resignation that own advice, tool, resource, etc… was unsuccessful in helping a close friend, a loved one, or a fond organization achieves an objective. For example, when your favorite football team fails to win at home, you may say “Bụt chùa nhà không thiêng” to mean the home advantage and fan support were not successful in securing a win.

Work-hard Verifying or Work-smart Mocking

Photo by Tim Gouw on Unsplash

Photo by Tim Gouw on Unsplash

Let’s test this service

@Service  
public class SampleService {  
    private final SampleRepository sampleRepository;  
  
    public SampleService(SampleRepository sampleRepository) {  
        this.sampleRepository = sampleRepository;  
    }  
  
    public SampleEntity createSampleEntity() {  
        SampleEntity sampleEntity \= new SampleEntity();  
        sampleEntity.setName("sample");  
  
        return sampleRepository.save(sampleEntity);  
    }  
}

If we want to test the method createSampleEntity from SampleService, there are 3 things we want to verify:

Writers, please go to sleep earlier

Photo by Brett Jordan on Unsplash

Photo by Brett Jordan on Unsplash

Brace yourselves. Holidays are ending

I am determined to become a writer. That does not mean forgoing my day job. Once back to work, I will be away from Medium for about 13 hours straights (8 AM to 9 PM). Writings only resume at night or during weekends.

I experienced some of that reality these past 2 weeks. I had cleared my annual leaves in early December to “avoid the crowd”, so I worked the last week of December while most colleagues were away. The work was not that heavy, but integrity forbade me from using company equipment and hours for my own side gig.

Retry WebClient Request

Problem Statement

Sometimes web request fails, for whatever reason, and you need to retry it

Let’s simulate a failed request scenario in a unit test. In the below code, the webClient attempts to submit a GET request to /employee/100 (stored in constant PATH). We mocked the backend server to fail with common status codes such as BAD_REQUEST, UNAUTHORIZED and validate that the client throws WebClientResponseException upon receiving such statuses.

@ParameterizedTest  
@EnumSource(value = HttpStatus.class, mode = EnumSource.Mode.INCLUDE, names = {  
        "BAD_REQUEST", "UNAUTHORIZED", "FORBIDDEN",  
        "SERVICE_UNAVAILABLE", "INTERNAL_SERVER_ERROR"  
})  
void throwExceptionWhenReceiveNon200Response(HttpStatus status) throws InterruptedException {  
    // request  
    var webClient = WebClient.builder().baseUrl(baseUrl).build();  
    var request = webClient.get()  
            .uri(PATH)  
            .retrieve()  
            .bodyToMono(String.class);  
  
    // response to first request with fail status  
    mockBackEnd.enqueue(new MockResponse().setResponseCode(status.value()));  
  
    // assert that exception thrown due to non-200 response  
    var ex = assertThrows(WebClientResponseException.class, () -> request.block());  
    assertEquals(status, ex.getStatusCode());  
  
    // extra assert that the path is correct  
    assertEquals(PATH, mockBackEnd.takeRequest().getPath());  
}

Retry unchanged

The easiest task is just retrying with the same request details.

Regional economic development in Vietnam — Reform & “Reorder”

35 years of Đổi Mới (Economic Reform) helped Vietnam from a country that had to “run for rice” (see note 1) in the early 1980s to become a middle-income country, reaching the top 20 of the world’s leading economies in terms of international trade. The Reform has turned many poor rural areas into industrial districts, farmers into city dwellers, the number of poor households has decreased sharply, the middle class has increased rapidly… But the Reform process also led to the “Reorder” among provinces and regions.

The story of the drums in Singapore

Many times when I visited Singapore, I noticed that under each apartment building, there were 2–3 red-painted drums in a straight line. These drums are modified with ventilation holes, have high legs, and have discharge doors… so that when households need to burn votive paper, they can do it here.

Incense burner (source: author’s father)

Incense burner (source: author’s father)

In a country where more than 70% of the population is Chinese with the tradition and custom of burning votive papers a lot every Lunar New Year, anniversaries, funerals, etc., along with propaganda, fines for violations, uniform arrangement of such burning places proved to be very effective, significantly limiting environmental pollution.

What Are APIs?

Are APIs the waiters?

Source: Reddit and LinkedIn

Source: Reddit and LinkedIn

No — The waiters are part of Frontend.

They are responsible for creating a nice visual and interactive experience such as greeting customers, arranging the tables, present the dishes — like what React or Angular codes do.

They will take your orders — like how HTML forms accept your inputs, auto-complete your sentences, or apologize that certain dishes aren’t available.

From Programmer to Writer

Photo by Glenn Carstens-Peters on Unsplash

Photo by Glenn Carstens-Peters on Unsplash

I’m a programmer by trade and write codes for a living. Then 1 month ago, I decided to become a writer. Here are the reasons why I did it and how I do it.

I’m pursuing my hobby

I never considered writing a hobby. I barely managed to pass my literature and English classes. I preferred subjects that did not require writing such as Mathematics, Chemistry, or Physics.

Singapore: City in a Garden

Photo by Kirill Petropavlov on Unsplash

Photo by Kirill Petropavlov on Unsplash

What is worth learning from the Lion island nation is, first of all, the strategic vision of development and the solution to turn that vision into reality.

The goal is to continuously improve people’s quality of life

From the perspective of urban development, Singapore is considered to have a very good level of urban planning and management. With an area only slightly larger than Vietnam’s Phu Quoc island, a population of 5.3 million people, most of the houses are high-rise apartment buildings… it is clear that Singapore is a case of “compression” of buildings on a narrow area.

SOLID in Action — the Open-closed Principle

Photo by Richard Balog on Unsplash

Photo by Richard Balog on Unsplash

In the physical world, a door closed is a closed door. In the software world, a closed entity may still be open for extension. And it should be so, according to the Open-closed principle (OCP).

There are 2 popular ways to apply this principle. We are going to discuss them both.

And a third option.

#1 — Inheritance

This is the original application of OCP. Bertrand Meyer, who introduced the term in his 1988 book Object-Oriented Software Construction, intended that:

Simple Code — Effective UI — Month Picker

Option 1: separate Month and Year dropdowns

Separate month and year dropdowns

Separate month and year dropdowns

It may be verbose, but you have total control over their placements, label, and format

<select>  
    <option>January</option>  
    <option>February</option>  
    <option>March</option>  
    <option>April</option>  
    <option>May</option>  
    <option>June</option>  
    <option>July</option>  
    <option>August</option>  
    <option>September</option>  
    <option>October</option>  
    <option>November</option>  
    <option>December</option>  
</select> Month  
  
<select>  
    <option>2021</option>  
    <option>2022</option>  
    <option>2023</option>  
</select> Year

Option 2: use the browser’s built-in month picker

Built-in month picker

Built-in month picker

You have less control over the picker’s appearance, but the code is much cleaner. And localization support is free.

Thu Duc, Ho Chi Minh City, Vietnam in December

Taken during my vacation

Photos taken during my vacation in Thu Duc, Ho Chi Minh City, Vietnam on December 2022

Vinhome Grandpark, Thu Duc, Ho Chi Minh City

Vinhome Grandpark, Thu Duc, Ho Chi Minh City

Heavy rain

Heavy rain

Having fun!

Having fun!

Playground

Playground

Swimming Lesson

Swimming Lesson

Manhattan Ave?

Manhattan Ave?

SOLID in Action — the Single Responsibility Principle

Photo by Robert Linder on Unsplash

Photo by Robert Linder on Unsplash

We know the saying “Jack of all trades, master of none”. We dislike it when we are at the receiving end. We dislike it too when it is said to someone we love. That should extend to things that we love too.

We developers love the codes we created. We are proud of the function we write, the class we design, the component, the system, and the microservices… we develop. We thus would not like it if they become “Jack of all trades, master of none”.

Five Minimum Viable Javascript Interview Questions

This is part of my Five Minimum Viable Interview Questions series where I research and compile Five essential interview questions on each interview topic. All of these questions aim to assess real and practical skills expected at work

It is common nowadays for companies to hire for full-stack positions. A full-stack developer is typically expected to work on both frontend and backend development. That same expectation applies to interviews.

It is thus tough to interview or be interviewed for a full-stack position. There would be too many questions to ask or to prepare for. But if you are running out of time, here are five questions I think you should know.

Becoming a SOLID developer

Being called solid is a compliment. The word carries the positive notions of reliability and respectability. All of us should aim to become one.

https://www.collinsdictionary.com/dictionary/english/solid (screenshot)

https://www.collinsdictionary.com/dictionary/english/solid (screenshot)

If you are a software engineer or want to become one, you are in luck because there is a set of SOLID principles to guide your way.

SOLID is an acronym in the software engineering profession. It stands for:

  • Single Responsibility principle
  • Open-closed principle
  • Liskov Substitution principle
  • Interface segregation principle
  • Dependency inversion principle

The term was coined by Michael Feather around 2004 for the 5 object-oriented design principles first collected by Uncle Bob in his 2000 paper Design Principles and Design Patterns and his other articles and books

The best way to fix Hibernate’s MultipleBagFetchException

There are 2 articles from https://vladmihalcea.com describing his analysis and solutions to Hibernate’s MultipleBagFetchException. The first one, appeared around 2020 (when I first researched this problem) or even earlier (2018?), offered an analysis of the problem and a solution using Hibernate’s EntityManager API. The second one appeared around Jun 2022, and offers a slightly different solution for JPA.

I will present below my understanding of his analysis, his solutions, and working sample codes which you can check out and validate your understanding and/or devise your own solutions.

Echo API

Introduction

The need for this library arose when I wanted assurance that my HTTP client was sending correctly formulated HTTP messages.

Another use of this /echo API is to capture and debug the remote calls from another service. Imagine you are providing a webhook endpoint. Before you even build one, you first need to know what incoming messages look like. Supplying an /echo API endpoint in the webhook’s registration allows you to capture and log all incoming messages

Unit testing Java’s try-with-resource

Java’s try-with-resource is a convenient syntactic shortcut. It frees developers from keeping track of closeable resources and closing in a finally block

Unit testing try-with-resource

Unit testing try-with-resource

Overview

Some of us may remember doing such boring and lengthy try-finally-if-not-null-close() A LOT!

On a typical day, we performed these steps a dozen times:

  • Obtained a DB connection, and execute a query within the try {...}
  • And then, to avoid connection leak, we must close the statement and DB connection within the finally {...} block.
  • Because getConnection(), prepareStatment() and executeQuery could fail, stmt and conn could be null . Hence we performed the not-null check prior to invoke close() methods.
public void executeQuery(String sql) throws SQLException {  
    Connection conn;  
    PreparedStatement stmt;   
    try {  
        conn = getConnection();  
        stmt = conn.prepareStatement(sql);  
        stmt.executeQuery();  
    }  
    finally {  
        if (stmt != null) {  
            stmt.close();  
        }  
        if (conn != null) {  
            conn.close();  
        }  
    }  
}

With try-with-resource, the above can be as short as below, freeing us to focus on other things such as data modeling or tuning query performance.

Java Method Reference

I first learned method reference from C#, so the Java concept is familiar to me. Or that’s what I thought until I picked up the Modern Java Recipes book.

In this article, we’ll explore 3 forms of method references in Java

  • object::instanceMethod
  • Class::staticMethod
  • Class::instanceMethod

The last one is a bit more special, as we shall examine in detail

Source: author

Source: author

object::instanceMethod

The object::instanceMethod will invoke the referenced method on the said object with compatible arguments. In the following example, the "hello " string’s concat method is invoked with arguments "a", "b", "c" resulting in "hello a", "hello b", "hello c" respectively

Code Review as an interview tool

Rationale

In all software development teams that I have been part of, we always value and encourage everyone to participate in code reviews. We see it as an effective way of learning and contributing. It has an important place in my Engineering practice.

We learn when we review other people’s codes. That’s actually an effective way of keeping up-to-date with what is happening to the code base, what sort of problems our colleagues are trying to solve, and what techniques they employed to solve them. Whether you are young or experienced, the delightful feeling of seeing creative solutions during code reviews is the same.

Java Stream Interview Tests - takeWhile

Generated by Dall-e

Generated by Dall-e

Why Java Stream?

Since its introduction in Java 8, Stream has become more and more the preferred way of processing collection. But some of its APIs, are complicated and hard to understand, especially those of Collector and those for reduction.

I dare say that even experienced Java Stream users may still find them intimidating. Despite using it for several years and having prior experience with Stream-like operations in other programming languages, I still occasionally find some Stream-related tasks challenging.

Java Stream Interview Tests - Distinct Characters

Requirement

Given a sentence comprising of one or multiple words separated by space (e.g. java, Hello World, aadsbbaba), return a sorted list of distinct characters excluding space

Solve this problem using Java Stream

Hint: Use String.split(“”)to split a string into a String[], then use String.charAt(0) to convert each single-char string to char

Discussion

This problem tests candidate’s knowledge of the following Stream methods:

  • Stream.of(...) or Array.stream(...) to convert an array of single-char string (e.g. from str.split("")) to Stream<String>
  • map(str -> str.charAt(0)) to convert String to Character. Note: while String.toCharArray can readily convert a String to an char[], turning the resulting array to a Character stream isn’t straightforward due to lack of built-in support for char type in Stream and Collection API. The Arrays.asList(str.toCharArray() or List.of(...) results in a List<char[]> instead
  • distinct() to keep only 1 instance of each encountered character
  • sorted() to sort the encountered characters in their natural order
  • collect(Collectors.toList()) to collect stream elements into a list

Sample Solution

A sample solution is shown below. In addition to above operations, we only utilize an extra filter(...) operation to discard spaces from getting into our response

Spring REST API Interview Questions

#1 Complete the REST controller

Objective: Assess a candidate’s practical experience and knowledge

Instructions: Given the below controller, fill in Spring annotations according to instructions given in the code comments

Pay attention to:

  • Did the candidate notice the repetition of /friends prefix? Did he/she suggest a @RequestMapping(/friends) on the controller class instead?
  • How did he/she annotate the optional parameter name and id in findFriends(String name, Long id) method?
  • What annotation can be used to force a 204 (no content) response?
/* Assume all package, imports and dependency classes are available */

/**
 * A rest controller for Friend-related operations
 */
public class FriendController {
    private final FriendService friendService;

    public FriendController(FriendService friendService) {
        this.friendService = friendService;
    }

    /**
     * Response to GET /friends/ request
     * @param name (optional) filter by name
     * @param id (optional) filter by id
     * @return a list of friends
     */
    public List<FriendDTO> findFriends(String name, Long id) {
        if (id != null) {
            return friendService.findByFriendId(id);
        } else if (StringUtils.hasText(name)) {
            return friendService.findByName(name);
        } else {
            return friendService.findAll();
        }
    }

    /**
     * Response to GET /friends/hello/{friend's name} request
     * @param friend a friend's name
     * @return a friendly Hello
     */
    public String hello(String friend) {
        return String.format("Hello %s", friend);
    }

    /**
     * Response to POST /friends/hello/{friend's name} request
     * @param friend a friend's name which is to be saved
     * @return a friendly Hello together with Id of the new friend
     */
    public String helloAndSave(String friend) {
        FriendDTO dto = friendService.add(FriendDTO.builder().name(friend).createDt(LocalDateTime.now()).build());
        return String.format("%s. Your Id is %d", hello(friend), dto.getId());
    }

    /**
     * Un-friend
     * Response to DELETE /friends/{friend's id} request, 
     * return 204 if successful
     * @param friendId the id of the friend
     */
    public void deleteFriend(long friendId) {
        friendService.removeFriend(friendId);
    }

    /**
     * Update friend name
     * Response to <METHOD?> /friends/{friend's id}/{new name} request, 
     * return update friend info
     * @param friendId the id of the friend
     * @param newName the new name of the friend
     * @return updated friend's info
     */
    public FriendDTO updateFriend(long friendId, String newName) {
        return friendService.updateName(friendId, newName);
    }
}
A friendly REST controller

A friendly REST controller

Enable Comment in Hugo site

Note 2024-08-15: An earlier version of this site ran on doks. I’m in the middle of updating it to a medium-like theme*


Introduction

You may have noticed that this website is using a powerful-yet-easy-to-use doks theme.

As I wanted to have more interaction with my readers, enabling comment is a first step.

Enable Comment in Hugo

Hugo provides built-in support for Disqus. It ships with a _internal/disqus.html template that we can simply copy & paste to wherever we want comment to appear. The steps are simple:

Gerald Nguyen

About me

A software craftsman who writes clean code, automated tests, and practices continuous improvement

A seasoned IT professional with 17 years of experience in various industries, business domains, and roles

An admirer of (Vulcan) logic, diversity, and multidisciplinary approaches

Connect with me on Linkedin, or X (formerly Twitter)

Personal Projects

HTML to Markdown

An Chrome extension that translate selected HTML text to equivalent markdown format.

It allows user to select and convert headers, paragraphs, images or links on the web into Markdown text quickly and effortlessly

Kubernetes Memory Units

Default memory unit in Kubernetes is bytes, in addition to other shorter forms with one of supported suffixes: E, P, T, G, M, K, Ei, Pi, Ti, Gi, Mi, Ki.

For example: 128974848, 129e6, 129M , 123Mi

Have you ever wondered what do those suffixes mean?

A popular reference is https://medium.com/@betz.mark/understanding-resource-limits-in-kubernetes-memory-6b41e9a955f9

But the root definition is at https://en.wikipedia.org/wiki/Binary_prefix

javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional

If you’re using Spring or Spring Boot, then use the Spring @Transactional annotation, as it allows you to configure more attributes than the Java EE @Transactional annotation.

If you are using Java EE alone, and you deploy your application on a Java EE application server, then use the Java EE @Transactional annotation.

https://stackoverflow.com/a/62702146/575457

Using Bootstrap with React

Mixing browser and React

Insert links to Bootstrap’s javascript and CSS and its dependencies in app’s index.html

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>

<body>

  <!-- other content -->
  
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
</body>

Invoke appropriate method via window.$ jQuery object

window.$('#about-modal').modal()

Pure React way

Install Bootstrap as a NPM module

npm install bootstrap --save
npm install jquery popper.js --save 

Load bootstrap CSS and Javascript in React app’s entry point (e.g. index.jsx or app.jsx)

[Excel] Bulk Linking Cells to Sheets Whose Name Equates Cell's value

Sub CreateLinkToSheet()
    Dim c As Range
    For Each c In Selection
        ' MsgBox c.Value
        ActiveSheet.Hyperlinks.Add Anchor:=c, Address:="", _
        SubAddress:=c.Value & "!A1", TextToDisplay:=c.Value
    Next c
End Sub

How to run: Select the cells to create link and run the macro

What Happened When You Assigned State to a Stateless Session Bean?

Here’s a scenario that illustrate above possibility

    T1                   |     T2
1) setupState [A]        |                   <- store state as a variable
                         |                      in bean instance [A]
                         | 2) setupState [A] <- [A] is free, so the container
                         |                      allocate it to serve T2 request
                         |
3) someLongRunMethod [A] | 3') aMethod [B]   <- Because A is busy with T1, 
                                                another instance (B) is created 
                                                to serve T2 request. If aMethod 
                                                depends on previously setup state
                                                it will encounter error

[VBA] Save Attachements from Multiple Emails

Prerequisite: Enable Developer tab, macro security and create “C:\mailattachment\” folder if not exists

Instruction: Select emails which have attachment to save (e.g. email containing daily report), select Developer, Macro, SaveAttachment

Sub SaveAttachment()
    Dim myOlapp As Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myFolder As Outlook.MAPIFolder
    Dim myItem As Outlook.MailItem
    Dim myAttachment As Outlook.Attachment
    Dim I As Long
      
    Set myOlapp = CreateObject("Outlook.Application")
    'Set myNameSpace = myOlapp.GetNamespace("MAPI")
    'Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
    'Set myFolder = myFolder.Folders("Ethsys")
    'Set myFolder = myFolder.Folders("Ethsys Operation Alert")
      
    'For Each myItem In myFolder.Items
        'If myItem.Attachments.Count <> 0 Then
            'For Each myAttachment In myItem.Attachments
                'MsgBox myAttachment.FileName
            'Next
        'End If
    'Next
     
     
    For Each myItem In Application.ActiveExplorer.Selection
        If myItem.Attachments.Count <> 0 Then
            For Each myAttachment In myItem.Attachments
                'MsgBox myAttachment.FileName
                myAttachment.SaveAsFile ("C:\mailattachment\" & myAttachment.DisplayName)
            Next
        End If
    Next
     
End Sub

[Unix] – Recursively Listing Files Under a Directory

If you prefer a DIY script:

#! /bin/bash
 
 
function list {
        if [ -z $1 ]
        then
                echo list starting_dir [exclude_file_or_folder] [action_on_file]
                exit 1
        elif [ "$1" == "-help" ]
        then
                echo list starting_dir [exclude_file_or_folder] [action_on_file]
                echo [exclude_file_or_folder]: use string that works with egrep e.g. ".jar|.log|.bak .jar|.log|.bak"
                echo [action_on_file]: if specified, output listing will not be in ls -l format
                exit 0
        fi
 
        local path=$1
 
        if [ -z $2 ]
        then
                ls -al $path
        else
                ls -al $path | egrep -v $2
        fi
 
        for file in `ls -a $path`
        do
                if [ "$file" != "." ] && [ "$file" != ".." ] && [ -d "$path/$file" ]
                then
                        file=`echo $file|grep -v $2`
                        if [ -z $file ]
                        then
                                echo "skipped" >> /dev/null
                        else
                                echo ============= $path/$file ================
                                list $path/$file $2 $3
                        fi
                fi
        done
}
 
 
list $1 $2 $3

But there is a simple alternative

[Database] Exists or Inner Join: Duplicate Records

INNER JOIN vs. EXISTS

Often, EXISTS and INNER JOIN can be used interchangeably to query data with existence in 2 or more tables. However, it is not always the case. There is an important inherent characteristics of INNER JOIN that every developer should keep in mind: INNER JOIN result may contain DUPLICATE data record. This is important for uniqueness-sensitive handling of query result (e.g. record count), or when migrating database table with unique constraints.

Which Form of String Comparison Is Supported

Below example is for Oracle DB, but adopting for other DBMS e.g. Sybase, MS SQL… should be straightforward.

select ‘both no space’ as “String comparison in Oracle” from dual where ‘a’ = ‘a’
--
union
select ‘right has single trailing space’ from dual where ‘a’ = ‘a ‘
union
select ‘right has multiple trailing space’ from dual where ‘a’ = ‘a   ‘
union
select ‘right has single leading space’ from dual where ‘a’ = ‘ a’
union
select ‘right has multiple leading space’ from dual where ‘a’ = ‘    a’
--
union
select ‘left has single trailing space’ from dual where ‘a ‘ = ‘a’
union
select ‘left has multiple trailing space’ from dual where ‘a   ‘ = ‘a’
union
select ‘left has single leading space’ from dual where ‘ a’ = ‘a’
union
select ‘left has multiple leading space’ from dual where ‘    a’ = ‘a’
--
union
select ‘right has single leading and trailing space’ from dual where ‘a’ = ‘ a ‘
union
select ‘right has multiple leading and trailing space’ from dual where ‘a’ = ‘    a   ‘
union
select ‘left has single leading and trailing space’ from dual where ‘ a ‘ = ‘a’
union
select ‘left has multiple leading and trailing space’ from dual where ‘   a      ‘ = ‘a’
—-
union
select ‘both has leading and trailing space but leading space are different’ from dual where ‘ a ‘ = ‘  a ‘

Myths of Secure Web Browsing

1. I am safe because I never visited porn website

Wrong. Nowadays, many more malware infection are linked to visit to legitimate and popular websites than porn or counterfeit sites.

According to Cisco 2013 Annual Security Report, Business/Industry site category stands at 3rd position behind advertising and dynamic content categories in the top 20 dangerous website categories. Included are Shopping (8th), Travel (9th), News (13th). Porn or counterfeit products (e.g. cheap Viagra) didn’t make it to top 20.

JSR 303 – Bean Validation – Let Your Bean Validate Itself

This is a simple application of my previous post whereby you can develop your own validation rule and enforcer.

The significance of this application is the use of SelfValidate interface to enable bean to define its own validation method and validator to invoke bean’s method. Typically this constraint is apply to a type, but application on field is also possible.

Constraint Annotation

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=SelfValidator.class)
 
public @interface SelfValidation {
   String message() default "Self-validation failed";
   Class[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}

Constraint Validator

public class SelfValidator implements ConstraintValidator<SelfValidation, SelfValidate>;
{
   @Override
   public void initialize(SelfValidationconstraint) { }
 
   @Override
   public boolean isValid(SelfValidate value, ConstraintValidatorContext validatorContext)
   {
      value.validate();
   }
}

SelfValidate interface

public interface SelfValidate {
{
   public String validate();
}

JDBC Transaction Without EJB

  1. Create a DAO method in which you set JDBC connection’s auto-commit property to false
dbConn.setAutoCommit(false);
  1. Execute all your queries
stmt = dbConn.createStatement();

result = stmt.executeQuery(query);

stmt.executeUpdate(update);
  1. Commit or rollback the transaction
dbConn.commit();
  1. Reset auto-commit to true again for other execution
dbConn.setAutoCommit(true);

This is really simple, as it should be for something purely mechanical. The challenge for every programmer is how to write your transaction code or order your queries such that you can achieve desired result.

JSR 303 – Bean Validation – Custom Constraints

So far, we have learn the basic and a not-so-common nested usage of JSR 303 Bean Validation, it’s time to learn how the declarative validation rule was implemented. In another word, we will learn to create a custom constraint this this post.

Constraint Annotation

Custom constraint is a special kind of annotation that is itself annotated with @javax.validation.Constraint annotation. For example:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=CustomeValidator.class) 
public @interface CustomConstraint {
   String message() default "Custom validation failed";
   Class[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}

Your own custom constraint will look pretty much like the one above, except for:

JSR 303 – Bean Validation – Nested Validation

Following up from my previous post about JSR 303 – Bean Validation, we will see how to apply it to any nested property and how to display validation error on screen using Spring MVC’s JSP tags

1. Bean Validation on Nested Property

Recall that to validate any property, we only need to put a Constraint annotation on top of its declaration. Example of common constraints are @NotEmpty, @Pattern, @Email. One thing in common of these constraints are that the applied property has to be of type String.

JSR 303 – Bean Validation – Basic

JSR 303 – Bean Validation is defines a metadata model and API for JavaBean validation. The metadata is primarily in Annotation forms, with the possibility of being overridden or extended by XML descriptors. Hibernate Validator is the reference implementation of JSR 303.

The current version, as of August 2nd, 2012, of JSR303 is 1.0, and of  Hibernate Validator version is 4.0.1.

1. Example

A straightforward use of Bean Validation is to document and specify validation rules on JavaBean’s properties. In the below example, it is easy to deduce that field manufacturer, licensePlate and seatCount are mandatory while note is not. In addition, licencePlate must contain at least 2 and at most 14 characters; seatCount must be equal or higher than 2.

ILLEGAL SPORT BETTING DURING EURO CUP

SPRING MVC – SESSIONATTRIBUTES ANNOTATION

Spring MVC’s SessionAttributes has 2 parameters: values (storing attributes’ names) and types (storing attributes’ types).

It’s pretty straightforward for values. You specify the name of your attribute and it is remembered.

It’s trickier for types. For example:

@SessionAttributes (types= java.util.List.class) does not work!

– But @SessionAttributes (types= java.util.ArrayList.class) works (but not always)

The reason behind this peculiar behaviour is that Spring does exact matching of attribute’s type versus declared type, instead of assessing attribute object’s Is-A relationship.

HOW YOUR CONSUMPTION BENEFIT SOCIETY?

(Disclaimer: I’m no economist. I simply find this story/concept interesting and want to share it)

If you initially have $2000 cash and you buy yourself a new smartphone (or any other good). Let’s say it costs you $1000.

So, after your buying:

– You have $1000 left

– Seller have $1000 revenue

– You have a good (i.e. the phone) worth $1000.

Thus your initial $2000 is split into 3 pieces which in total worth $3000.

Java XML Parse error: Tried all: '1' addresses, but could not connect over HTTP to server

I had a previous problem with Tiles and XML (and common-digester). I resolved it by telling WLS to use a different SAXParserFactory.

But when my SAXParserFactory was correct and I still encountered XML parsing error for the sample code from Tiles’s website, it is really puzzling.

java.net.ConnectException: Tried all: '1' addresses, but could not connect over HTTP to server: 'tiles.apache.org', port: '80'        at weblogic.net.http.HttpClient.openServer(HttpClient.java:312)  ...        at org.apache.commons.digester.Digester.createInputSourceFromURL(Digester.java:2072)        at org.apache.commons.digester.Digester.resolveEntity(Digester.java:1725)        at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107)        at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)        ..        at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)  ...        at org.apache.commons.digester.Digester.parse(Digester.java:1887)        at org.apache.tiles.definition.digester.DigesterDefinitionsReader.read(DigesterDefinitionsReader.java:267)

After a few hours googling, I found the solution here: http://stackoverflow.com/questions/5067447/struts2-tiles-when-apache-org-is-down-my-webapp-fails-to-start. To quote it:

How do you display input validation error

Display errors in red below each invalid input field

Blogger: https://www.google.com/accounts/CreateAccount?continue=https%3A%2F%2Fwww.blogger.com%2Floginz%3Fd%3Dhttp%253A%252F%252Fwww.blogger.com%252Fhome%26a%3DADD_SERVICE_FLAG&hl=en_GB&service=blogger&skipvpage=true&ltmpl=start&naui=8

Yahoo Mail: https://edit.yahoo.com/registration?.intl=us&.pd=ym_ver%253D0%2526c%253D%2526ivt%253D%2526sg%253D&new=1&.done=http%3A//mail.yahoo.com&.src=ym&.v=0&.u=cgf061p6mc1fm&partner=&.partner=&pkg=&stepid=&.p=&promo=&.last=

Oracle Forum: https://myprofile.oracle.com/EndUser/faces/profile/createUser.jspx?nextURL=http%3A%2F%2Fforums.oracle.com

Twitter: https://twitter.com/account/create

Esnip (on Firefox): http://www.esnips.com/NewAccountAction.ns?action=init

Hotmail: https://signup.live.com/signup.aspx?id=64855&mkt=en-US&form=MWGELB&publ=SIGNINHM&crea=SITEACQ_CIMS015888_Hotmail_EN-US_0x0_36214&lic=1

Job Street: http://myjobstreet.jobstreet.com/registration/quick-register.php?site=sg&deposit_through=s

JobsDB: http://sg.jobsdb.com/SG/EN/JobSeeker/Registration

Property Guru: http://www.propertyguru.com.sg/register#top

Display an generic message at the top of the page + Display errors in red below each invalid input field

Vietnamework.com: http://www.vietnamworks.com/jobseekers/signup.php?lang=2#err_top

Apple Store: https://store.apple.com/1800-MY-APPLE/WebObjects/singaporestore.woa/920184021/wo/nZMi8SOBKCCj343MT1tza3xYBZk/5.0.16.9.5.1.1.0.1

Display all invalid error at the top of the page

Amazon.com: https://www.amazon.com/ap/signin?ie=UTF8&pf_rd_r=05JGGPJ2RGK60ME9AEBM&pf_rd_m=ATVPDKIKX0DER&pf_rd_t=6301&pf_rd_i=usflex&pf_rd_p=1277563402&pf_rd_s=signin-slot

Forum phpBB: http://forum.vncnus.net/ucp.php?mode=register

Validate input on client side

Esnip (on IE): http://www.esnips.com/NewAccountAction.ns?action=init

Static vs Singleton Revisited

Static vs Singleton vs Dependency Injection

Why visited? Because I wrote one before

I no longer favor static over singleton as much as before. Static is convenient (sometimes very!), low memory footprint. But it does take away several Object-Orientation (OO) ’s strength. In addition, it couples your code to a specific implementation class. Singleton is less convenient (sometimes troublesome), slightly higher memory footprint, but it can deliver all OO’s strengths that static drops.

What makes Israel so innovative and entrepreneurial?

I really admire the Israel mindset.


Milking Israel’s dairy expertise in Vietnam (http://www.israel21c.org/201102078760/environment/milking-israels-dairy-expertise-in-vietnam)

New Zealand cows are arriving by the boatload in Vietnam as part of an Israeli-led $500 million dairy farm project there.

Israeli company, SAE Afikim is helping Vietnam develop its dairy industry, in the largest project of its kind in the world.

In the largest project of its kind in the world and the biggest ever undertaken by an Israeli firm, 30,000 dairy cows are being flown to Vietnam to supply 300 million liters of milk annually as part of a $500 million dairy farm project there.

Harvey Balls

http://en.wikipedia.org/wiki/Harvey_Balls

Static method vs Singleton class

Static method

It really depends. If you hate storing object reference or passing it around, static is a excellent tool.

But remember: static method CANNOT be overridden by sub-classing, it’s only hidden. Refer to http://faq.javaranch.com/view?OverridingVsHiding for a simple explanation. (Side note: invoking a static method on a object reference only brings confusion, it’s the variable data type that determine which static method’s code will execute - remember: hidden, not overridden).

Since static method cannot be overridden, the polymorphism power of OOP is lost, and we fall back to the realm of procedural programming. Some even complain about the difficult of unit testing with static method.

How Sun's certification exam are prepared

“Without getting into too much detail, I can tell you some of what Sun did to create their various Java certification exams. So, in the old Sun days…

The whole process to create a new exam takes a long time. A first team of experts is assembled and for several months the team develops a new set of objectives. Once created, the new set of objectives go through all sorts of vetting / verification processes.

Consistency in framework design

Concistency

Framework: a set of ideas, principles, agreements, or rules that provides the basis or outline for something intended to be more fully developed at a later stage (MSN Dictionary)

Not sure if you agree, but for me, the above definition implies “consistency” as a essential effect of using a framework. In the context of software development, using a framework usually equals to following its design guideline, or implementing/extending its interfaces/base classes. Things can stuck or go wrong and time will definitely be wasted if you don’t.

Who owns the source code? Employee or employer?

I found these 2 articles discussing “who owns the source code” issue.

http://www.computerworld.com/s/article/print/9126595/Who_owns_the_code_Beware_copyright_pitfalls?taxonomyId=11&taxonomyName=Development

http://www.burgess.co.nz/law/copyright-ownership-and-software-development

The first article discusses the issues using US copyright law; the second is in the context of New Zealand. There are slight difference between the 2 laws with regard to Contractor/Customer relationship but the case of Employee/Employer is the same: without explicit agreement (contract), the Employer owns the source code.

In Singapore, it is the same: Employer is the copyright holder. This article briefly mentions it: http://www.guidemesingapore.com/incorporation/trademarks/singapore-copyright-law-introduction

Quicksort vs Merge sort in Java

The title is a little larger that what I have in this entry :D

If you want the answer fast, go here http://www.coderanch.com/t/520171/java/java/Why-Collections-sort-merge-sort#2355668

And here is a longer write-up:

I participated in an thread in Javaranche regarding why Arrays uses quicksort and Collections use merge sort (http://www.coderanch.com/t/520171/java/java/Why-Collections-sort-merge-sort). The thread starter claimed that quicksort is the best sort algorithm, for which I disagreed. I also replied with a link to wikipedia about merge sort performs better when the underlying datatype does not support random access (as does array). I thought that was the reason why Collections use merge sort: because a collection type such as LinkedList does not necessarily support random access.

How do you initialize an EJB3 Stateful Session Bean ?

In EJB 3, we can obtain a reference to Stateful Session Bean either either by using @EJB annotation or performing JNDI look-up. Yet these 2 methods do not offer you a way to initialize a Stateful SB as EJB 2.1 Home interface’s createMETHODs do.

StatefulSB bean = home.create (arg0, arg1, arg2);

EJB3 defines @Init annotation as a replacement for EJB 2.1 createMETHOD. But it is intended for bean written to 2.1 client view (that means you will need to define an home interface and annotate the bean class with @RemoteHome or @LocalHome annotations)

Weblogic SAXParserFactory Issue

I have just wasted 1 whole day trying to debug this issues. Since I get most help from the internet, here is what I can do in return :D


I was trying to build a Spring 3.0 webapp with Tiles 2.2. Since Tiles depends on common-digester which subsequently depends on SAXParserFactory, I got stuck in a whole range of strange Weblogic behaviors.

Firstly, I got UnsupportedOperationException everytime I first access the webapp. Subsequent access is fine, but the first always encounters that exception. Hours of googling tells me that the exception is due to weblogic’s RegistrySAXParserFactory.

Recursive Tagfile

Tagfile is a good alternative for lazy people like me who hates doing java coding and XML configuration for simple task with lots of HTML codes.

But laziness knows no limit. Just now I ended up wasting haft a day on a recursive tagfile that would otherwise be completed within 1 hour at most. Yet it was an experience that’s worth sharing.

The tagfile is named catalogue.tag. Its purpose is to display recursively a hierarchy tree of catalogues..

Interesting - AKA

AKA = Also-Known-As

Combine EJB and WAR file in a same web service EAR

That has been my challenge since yesterday. And I think I have just got it :D

Let’s see if I can reconstruct a step-by-step manual:

1. First of all, let have some understanding of the structure of a EAR file.

EAR stands for Enterprise ARchive. It’s a convenient mean to to pack and deploy components of an enterprise application. Essentially, you can pack WAR, EJB, Resource Adapter and supporting libraries inside a EAR file. Having them all in one place, as a single unit tremendously helps release management and deployment. But it does pose some challenges in the context of class-loading.

2-way SSL with WebLogic server 10.3

TOOLS

  1. keytool: a key and certificate management tool. Provided as part of Sun’s JDK Online reference: http://java.sun.com/javase/6/docs/technotes/tools/windows/keytool.htm.

  2. utils.CertGen: a certification generate tool provided by WLS. By default it will generate certificates from default CertGenCA.der and CertGenCAKey.der; but have not been able to generate certificate from other cert and key (probably because of the lack of original cert & key AND CertGenCA has constraint of max 1 descendant). Online renference: http://download.oracle.com/docs/cd/E13222_01/wls/docs103/admin_ref/utils.html#wp1198920

  3. utils.ImportPrivateKey: a tool provided by WLS. Used to import certificate generated by CertGen to keystore as PrivateKey (normal keytool’s importcert store imported key as trustedCertEntry which is unsuitable for Identity & personal keystore)

    J2EE Programming Tips

    J2EE Programming

    1. Learn to program Java well. SCJP is nice to have.

    2. Do program with performance-awareness.

    3. Always try to optimize your program; performance is a big concern in any J2EE application.

    4. Dont just follow what other people call best practices, they may not fit your need while being costly to implement.

    5. J2EE application’s performance is often constraint by its interraction with database(s). Optimise your database access, data transaction management codes.

      Interesting - 2009

      Capitalism vs Socialism

      “Capitalism is the unequal distribution of wealth. Socialism is the equal distribution of poverty.” – Winston Churchill

      President Harry Truman

      President Harry Truman once said that he wanted to find a one-armed economist.

      When he asked his economists for advice, they always answered, “On the onehand, . . . . On the other hand, . . . .”