Using Java 8

Default Method

Using Optional
Optional.ofNullable/orElse(T value)/orElseThrow
ifPresent(Consumer consumer)/orElseThrow(XException::new)

Map + ConcurrentHashMap
ConcurrentHashMap<String, Integer> wordMap = new ConcurrentHashMap<String, Integer>(16, 0.9f, 1);

compute, computeIfAbsent, computeIfPresent
the current (existing or computed) value associated with the specified key, or null if the computed value is null
targets.computeIfAbsent(ticket[0], k -> new PriorityQueue()).add(ticket[1]);
counters.computeIfAbsent(name, k -> new AtomicInteger()).incrementAndGet();
map.computeIfAbsent("key", k -> new LongAdder()).increment();

map.putIfAbsent(sum, i);
Instead of:
if (!map.containsKey(sum)) {
    map.put(sum, i);

map.getOrDefault(key, defaultValue)
wordMap.merge(word, occurrence, (key, value) -> wordMap.getOrDefault(key, 0) + value);
wordMap.reduceValues(1,(count1,count2) -> count1+count2);, (k, v) -> v > 1000 ? k : null);

iterable.forEach(x -> x.setXXX(null));
list.removeIf(s -> s.length() == 0);

list.replaceAll(s -> s.toUpperCase());
list.sort((x, y) -> x.length() – y.length());
Arrays.sort(intervals, (a, b) ->,b.start));
Arrays.sort(intervals, (a, b) -> a.start - b.start);
logger.finest(() -> complexMsg());
lineCount = Files.lines(path).count();

List to map: -> x.getId(), x -> x.getName())); - keyMapper, valueMapper
Convert to a different map - TreeMap
.collect(Collectors.toMap(keyMapper, valueMapper,(k,v) ->{ throw new RuntimeException(String.format("Duplicate key %s", k));}, TreeMap::new)); - mergeMapper, mapSupplier

mapStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

long result=;

Collectors.joining joins the stream elements for a given delimiter, prefix and suffix. 
String result=",","(",")"));

int result =>i));
Map<String,String> map = streak.collect(Collectors.toMap(k->k, v->v+v));

streams cannot be reused. The stream is closed after you call any terminal operation.

Word Count:
groupBy aggregate
Map collect =, counting()));

Map map = "abcabc".chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(c -> c, Collectors.counting()));

Map countMap = Files.lines(file).flatMap(line -> SPLITTER.splitToList(line).stream())
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Method and Constructor References
XClass::aMethod, XClass::new

List to map: Collectors.toMap(Perseon::getId, Perseon::getAge));

Combination of map and flatten. The parameter mapper function returns a list of stream, flatMap flatten them into a Stream of single value. -> slice.getReplicas()).flatMap(replicas ->

    .map(replica -> replica.getCoreUrl()).collect(Collectors.toList())

ArrayList class extends AbstractList class, which extends AbstractCollection class which contains a toString() method

String.join(", ", list);

When compiler complains: incompatible types: cannot infer type-variable(s),try to declare an explicit type to provide enough type information to compiler: 
Map<K1, V1> to Map<K2, V2>
new HashMap<String, ValueClass>().entrySet().stream().collect(Collectors.toMap((final Entry<String, ValueClass> e) -> LocalDate.parse(e.getKey()), e -> e.getValue()));

Java 8 Time API
LocalDate/LocalTime/LocalDateTime - no time zone, good for store birthday
date1.until(date2, ChronoUnit.DAYS),

DateTimeFormatter - thread safe
-- Prefer it than SimpleDateFormat

LocalDateTime.parse("2016-10-06", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Convert Date to ZonedDateTime
ZonedDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC)

Month Enum
LongAdder vs AtomicLong

Keep alert of Abnormal things - Problem Solving Skills

In the post Read the Error Message - Problem Solving Skills, we mentioned that the first step of troubleshooting is to read and understand the error message.

During reading the error message/log, it's important to keep alert of unusual things/messages and guess possible causes.

Scenario 1 - In Memory Test User not work in Rest-Assured
After developed the feature Spring Security: Integrate In-Memory Authentication for Test Automation, another developer is using it to write automation test  - using Rest-Assured and reusing the session filter.

I was told that it didn't work and asked to help troubleshoot it.

First step: reproduce the problem
If we run the code that uses rest assured with the test user and session filter, it failed.
But I can use the test user to login admin ui in the browser. - This is weird, I should pay more attention to this unusual thing and think about possible causes, but I didn't at that time.

Then I found the following message in the log:
-- This is wired, as I am using the test user - spring should use the in-memory DaoAuthenticationProvider to verify it; it should only call ActiveDirectoryLdapAuthenticationProvider if it's not the in-memory user.

INFO 144038 [http-nio-]   - Active Directory authentication failed: Supplied password was invalid

Now I check the code more carefully and found out that it uses wrong username: uses 'admin-123' instead of 'admin_123'. admin-123 is not in-memory user, so it calls ActiveDirectoryLdapAuthenticationProvider for authentication and it failed obviously.

Actually if I read rest-assured logs more carefully, I should have found the root cause early.
00:05:05.553 [main] DEBUG org.apache.http.headers - >> POST /xapp/j_spring_security_check HTTP/1.1
00:05:24.564 [main] DEBUG org.apache.http.wire -  << "HTTP/1.1 302 Found[\r][\n]"
00:05:24.568 [main] DEBUG org.apache.http.wire -  << "Set-Cookie: JSESSIONID=9C03D491F56D6CDC007FA931898F5504; Path=/xapp/; HttpOnly[\r][\n]"

00:05:24.568 [main] DEBUG org.apache.http.wire -  << "Location: http://localhost:8080/xapp/loginerror;jsessionid=9C03D491F56D6CDC007FA931898F5504[\r][\n]"

Eclipse: Be careful what class you import

In the following code, Eclipse shows warning in methodB: The type parameter T is hiding the type T.

private void methodA(final Map<String, T> map) {}
private <T> void methodB(final Map<String, T> map) {}

The root cause is that when write methodA, I made a mistake: I forgot to declare type variable.

As I configured Eclipse Save Action: it will automatically organize imports not declared classes;  in Map<String, T> map, the T is actually:, so methodA actually compiles.

In methodB, the T is actually type variable, so eclipse shows the warning: The type parameter T is hiding the type T.
This is configured in Preferences > Java > Compiler > Errors/Warnings > Type parameter hies another type > Choose Warning

Lesson Learned
During code review, don't ignore imports part.
Make sure what imports is actually we want.
Don't use T as type variables, use E, K, V etc.
Understand the generic syntax.

Mac Tips & Tricks - 2016

Use all F1, F2, etc. keys as standard function keys
System Preferences > Keyboard -> Use all F1, F2, etc. keys as standard function keys

Search in current folder instead of everywhere - link
Go to preference in finder, select "Search the Current Folder" in "When performing a search" and "Advanced" tab 

System Preferences > Keyboard > Shortcuts > All controls
- then we can use tab to move and use space to select the active button

System Preferences > Trackpad > Point & Click > Tap to click

Keychain Access > Manage passwords and certificates

Change default browser
System Preferences > General > Default web browser

Go to Folder
/ or Command+Shift+G ->
- Use tab completion

CONTROL + a/e > Got to head/end - work in Terminal, Chrome, Atom

Command+` > cycle between open windows in selected application

xtrafinder support features:
Press Enter or Return to open selection
New File
Copy Path
Copy to, Move to
New Terminal Here

Command+i > Show info
Command+shift+deelete > Empty the trash

Rename a file or folder
- By default, we can press enter to change file name. 
- If we use XtraFinder and configure it to press Enter to open file, then we can press fn+enter to rename a file.

Close Windows
Undo/Redo:  Command + Z/Y
Command-Shift-W to close a window
Command-Option-W, Close all windows

Zoom out/in
System Preferences > Accessibility > Zoom
Check "Use keyboard shortcuts to zoom":
COMMAND + OPTION + 8 > Toogle Zoom
COMMAND + OPTION + = > zoom out
COMMAND + OPTION + - > zoom in

Check "Use scroll gesture with modifier keys to zoom"
Scroll scroll on the trackpad while pressing one of keys: CONTROL, OPTION, or COMMAND

Most applications supports: 
COMMAND + "+" > zoom out 
COMMAND + "-" > zoom in

Allow or disallow unidentified apps
Ctrl+click or right click then select Open from the contextual menu.

System Preferences > Privacy & Security > General > Allow applications downloaded from

Automatically Hide the Dock
System Preferences > Dock > Automatically hide and show the Dock
Command+Option+D: hide or show dock

Command + H > hide the current application

Force Quit Applications
Using shortcuts: Command + Option + Escape
Using Activity Monitor
Option + click application in the dock

Cmd + Ctrl + D > Dictionary

Activity Monitor

Spotlight Search: Command + Space
Show file location
- Hold Command key
Open file in Finder
- Hold Command key + enter
- Hold Command key + double-click on the result

Exclude folders from Spotlight Index

System Preferences -> Spotlight -> Privacy tab, add folder to exclude from index

Search in current folder rather than everywhere
Open Finder's preference, choose "Search the Current Folder" in Advanced tab

Install/Use GNU tools
brew install coreutils findutils gnu-tar gnu-sed gawk gnutls gnu-indent gnu-getopt
Search Contents of .jar Files for Specific String
gfind . -iname '*.jar' -printf "unzip -c %p | grep -q 'string_to_search' && echo %p\n" | sh

brew doctor
brew update && brew upgrade
brew cleanup     > remove older version
brew cleanup -ns >  Show what will be removed

brew tap caskroom/versions
brew cask install java7

Install GNU Command Line Tools
brew install coreutils
brew install wget

brew cask install iterm2
Reuse previous session's directory
Preferences > Profiles > Default > General > Working Directory > Reuse previous session's directory

Disable swap space
sudo launchctl unload -w /System/Library/LaunchDaemons/
sudo rm -rf /private/var/vm/swapfile*

sudo launchctl stop|start com.openssh.sshd

Do a basic search in Outlook: OPTION + COMMAND+ F
Do an advanced search in Outlook: SHIFT + COMMAND+ F
Find text within an item: COMMAND+ F

Install Programs from Unidentified Developers
Preferences > Security & Privacy  General  Allow apps downloaded from
To Manually Launch Application: Holding control key + choose open from dropdown menu

Kill Parental Controls
pgrep parentalcontrolsd 
sudo pkill -9 parentalcontrolsd

Making Sense of Mac Keyboard Symbols

Spring Security: Integrate In-Memory Authentication for Test Automation

Use Case
To automate test of our web services apis, we need add test users in test environments.

The Solution
We configure Spring Security AuthenticationManager: first add  in-memory DaoAuthenticationProvider in test environments then add other authentication providers.

The legacy code uses xml to configure authenticationManager and intercept-url rules, so I create bean. If you are using pure java config, please check Spring Security Java Config.
public class WebSecurityConfiguration {
    private static final String[] ENV_SUPPORT_TEST_USER = {PROFILE_LOCAL, PROFILE_XX};

    private Environment environment;

    @Bean(name = "")
    public AuthenticationManager authenticationManager() {
        final List providers = new ArrayList<>();

        final String env = System.getProperty("env");
        if (StringUtils.isBlank(env)) {
            throw new BusinessException(ErrorCode.INTERNAL_ERROR, "env is empty");
        // The order matters: don't change the order - it will first try to use the test user
        // if not succeed then use ldap
        // add test user for local, q1, e1 only
        if (ArrayUtils.contains(ENV_SUPPORT_TEST_USER, env)) {

        if (PROFILE_LOCAL.equals(env) || PROFILE_DOCKER.equals(env)) {
        } else {
            // application is deployed to aws, use different LdapAuthenticationProvider

        final AuthenticationManager authenticationManager = new ProviderManager(providers);
        return authenticationManager;

    protected void addTestUserAuthProvider(final List providers) {
        final DaoAuthenticationProvider testUserAuthProvider = new DaoAuthenticationProvider();
        final Collection users = new ArrayList<>();
        // add admin user
        UserDetails user = new User(environment.getProperty(""),
                Lists.newArrayList(new SimpleGrantedAuthority(environment.getProperty(""))));
        // add provisioner
        user = new User(environment.getProperty(""),
                environment.getProperty(""), Lists.newArrayList(
                        new SimpleGrantedAuthority(environment.getProperty(""))));

        // add user with admin and provisioner
        user = new User(environment.getProperty(""),
                Lists.newArrayList(new SimpleGrantedAuthority(environment.getProperty("")),
                        new SimpleGrantedAuthority(environment.getProperty(""))));

        final UserDetailsService userDetailsService = new InMemoryUserDetailsManager(users);


Testing with Rest-Assured
Now we can use Rest-Assured to login and capture the session and reuse it in subsequent requests.
RestAssured.baseURI = baseURI;
RestAssured.basePath = basePath;
RestAssured.config = config().logConfig(new LogConfig());

final SessionFilter sessionFilter = new SessionFilter();
.form(user, passwd,
        new FormAuthConfig("/j_spring_security_check", "j_username", "j_password"))

// later...

Searching More Effectively - Programmer Skills

Search is an important skill to programmers, it helps us to quickly find root cause, solutions, resource and etc.

Searching Code
Ctrl+alt+h to check call hierarchy
-- When write code, give class/methods easy-to-search name.
Senario 1 
One colleague asked me to help trouble shoot one problem, he wanted to split part of code from one project, so he copied all XX-related code to another project, but found that it doesn't work.

The error message is that it can't inject XXBean:
void doSomething(@Context XXClass xxBean)
Next I tried to find how old project works. The XXClass is not a spring component, so next I checked who called its constructors, then I found out that the constructor is called in XXClassProvider.

Now the root cause is clear: he forgot to copy the XXClassProvider.
@Component @Provider
public class XXClassProvider extends InjectableProvider<Context, XXClass> {}

-- Another way is to use "Open Type", search "* XXClass*" to find XXClass related class.

Github Search
Check the user guide and search the source code from project's github.
From How to ignore pojo annotations while using Jackson ObjectMapper? I know in codehause.jackson, we can configure objectMapper to ignore pojo annotation like below:
objectMapper.configure(, false);

But how to do in Jackson2(fastxml)? So I go to Jackson GitHub, then search USE_ANNOTATIONS:
Now it's easy to see that I should use MapperFeature.USE_ANNOTATIONS.

Or we can try Google search: USE_ANNOTATIONS

Eclipse Search
Avoid duplication
If you think the constant or function defined in your class maybe used in other classes, search the codebase first to avoid duplicate code.

Give classes and methods easy-to-search names.
Command+h          -> search
Command+shift+t -> open type
Command+shift+r -> open resource
Command+o         ->  list all methods of this class
Command+o+o     ->  list all methods of this class including inherited methods
F4 to show all sub classes, then scan related code.

Searching Log
During trouble shoot, it's common that there are 200 + lines in error log that is related: first we can try to use project package name, class name to quickly locate and scan in the error log; if can't, before try other approaches, make sure first quickly scan through all error messages. 
- In most case the root cause is just hidden in the log.
- Check More at: Error creating bean with name ''

Command history search
To run command that you have ran before.
history | grep git | grep erase
history | grep solr | grep cd
history | grep solr | grep start

Google search(do some search) first
Google search (do some search) first before attend meeting or join discussion or ask others for help.

Know/Use internal websites
Know company’s internal resource – where to find them
Know some experts (in company you) can ask help from


Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (37) Eclipse (33) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (16) Defects (14) Text Mining (14) J2EE (13) Network (13) Troubleshooting (13) PowerShell (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) Problem Solving (9) UIMA (9) html (9) Http Client (8) Maven (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts