Showing posts with label Problem Solving. Show all posts
Showing posts with label Problem Solving. Show all posts

How to Improve Problem Solving Skills - A Developer's Guide


How to Improve Problem Solving Skills

How to Improve Problem Solving Skills

Jeffery Yuan

April 24, 2019

How to Read Internal docs to Solve Problems


Often, we need find some docs in internal website and read them to figure out how to do some task.

Internal vs Internet
This is different from searching internet, which usually we can find plenty of resources, after read multiple articles, we can usually have a sense how to do it. It's fine if we don't read some articles carefully, - not ideal, but usually we can find related/similar articles and can understand or get it at that time.

Usually there would be only a few docs/pages for internal docs: they are well documented, and give all information we need.

But if you don't read them carefully or miss some key information, you would be mot able to solve the problem by just reading the docs. - you can still ask help from others. 

Be organized when read the docs
- Maybe open all related docs in a different browser, in one window
- Maybe start with the entrance page (maybe given by someone) , and follow the links while read it

Notice/Write down what you don't understand or is strange to you
-- Usually they are the keys to solve the problem

Use tools like evernote to help read the docs
- add note, highlight content etc

First find/know all internal websites that are useful
Search them, read them carefully
Examples: docker sidecar, yubikey-ssh

How to Improve Problem Solving Skills



How to improve problem solving skills from Yun Yuan
Misc
How to test it (locally) and easily
How to verify whether it works easily
What's the short comings of your current approach?
Whether there is better approach?

How To Ask Questions The Smart Way

Problem Solving Practice - Redis cache.put Hangs


The Issue
After deployed the change: Multi Tiered Caching - Using in-process EhCache in front of Distributed Redis to test environment (with some other change and someone did some change in the server like restart), we found out that cache.put hangs when save data to redis.

Troubleshooting Process
First we tried to reproduce the issue in my local setup, it always works. But we can easily reproduce it in test environment.

This mde me think this maybe something related with the test environment.

Then I used kill -8 processId to generate several thread dumps when reproduce the issue in test machine. I found out some suspect:
"ajp-nio-8009-exec-10" #91 daemon prio=5 os_prio=0 tid=0x00007f49c400a800 nid=0x75db waiting on condition [0x00007f495333e000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at  RedisCache$RedisCachePutCallback(RedisCache$AbstractRedisCacheCallback).waitForLock(RedisConnection) line: 600
RedisCache$RedisCachePutCallback(RedisCache$AbstractRedisCacheCallback).doInRedis(RedisConnection) line: 564
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:157)
at org.springframework.data.redis.cache.RedisCache.put(RedisCache.java:226)
at org.springframework.data.redis.cache.RedisCache.put(RedisCache.java:194)
at com.lifelong.example.MultiTieredCache.lambda$put$40(MultiTieredCache.java:130)
at com.lifelong.example.MultiTieredCache$$Lambda$18/1283186866.accept(Unknown Source)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at com.lifelong.example.MultiTieredCache.put(MultiTieredCache.java:128)
at org.springframework.cache.interceptor.AbstractCacheInvoker.doPut(AbstractCacheInvoker.java:85)
at org.springframework.cache.interceptor.CacheAspectSupport$CachePutRequest.apply(CacheAspectSupport.java:784)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:417)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:327)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)

Check the code at RedisCache$AbstractRedisCacheCallback to understand how it works:
for operations like put/putIfAbsent/evict/clear, @cacheable with sync =true(RedisWriteThroughCallback), it check whether there is a key like cacheName~lock in redis, if exist, it will wait until it's gone.

This lock is created and deleted for @Cacheable with sync =true in RedisWriteThroughCallback which calls lock and unlock methods.

This made me check the settings in redis: after created the tunnel to redis, ran command: key cacheName~lock, I found out that it's indeed there.

Now everything make sense:
- we did set sync=true and run performance test, then restarted the server and removed it. The cacheName~lock was left there may be due to server restart. Due to the cacheName~lock, now all resid update api would not work.

After removed cacheName~lock in redis, everything works fine.

Take away
- When use some feature (@Cacheable(sync=true) in this case), know how it's implemented.

Support Spring Expression Language in Spring AOP


User Case
We want to create @Loggable so developers can use it to specify log level and what to log before or after the method being called. developers can use #p0, #p1 to log param values, use #result to log response or specify any valid spring expression.

Learning How to Do it from Spring Code
We know that spring cache annotations supports spring expression language, we can use #p0, #p1 in @Cacheable, use #result in @CachePut. So we can debug spring cache code to figure it how it works.

Relate code in Spring CacheAspectSupport.execute
CacheAspectSupport.generateKey(CacheOperationContext, Object)

CacheOperationExpressionEvaluator.createEvaluationContext
if (result != NO_RESULT) evaluationContext.setVariable(RESULT_VARIABLE, result);
- To support #result, we just put method return result value into the varaible: result.

The Implementation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
    Level level() default Level.INFO;
    /**
     * This value has to be a valid spring expression<br>
     * Example: "'-begin'" or use #p0, #p1 to refer method params.
     * 
     * @return
     */
    String beginMessage() default "";
    /**
     * This value has to be a valid spring expression<br>
     * Example: "#result", "'-end'"
     * 
     * @return
     */
    String endMessage() default "";
}
@Aspect
@Component
public class LoggableAspect {
    @Value("${throw.exception.if.invalid.expression:true}")
    private boolean throwExceptionIfInvalidExpression;
    public static final String RESULT_VARIABLE = "result";
    /**
     * It is recommended to reuse ParameterNameDiscoverer instances as far as possible.
     */
    private static final ParameterNameDiscoverer parameterNameDiscoverer =
            new LocalVariableTableParameterNameDiscoverer();
    /**
     * SpEL parser. Instances are reusable and thread-safe.
     */
    private static final ExpressionParser parser = new SpelExpressionParser();

    @Around("@annotation(com.sony.sie.kamaji.vue.metadata.aop.Loggable)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        final Class<?> declaringClass = method.getDeclaringClass();
        final Logger logger = LoggerFactory.getLogger(declaringClass);
        final Loggable loggable = method.getAnnotation(Loggable.class);
        Object result = null;
        if (loggable != null) {
            final Level logLevel = loggable.level();
            if (whetherParseExpression(loggable.beginMessage(), logger, logLevel)) {
                final EvaluationContext beginContext = new MethodBasedEvaluationContext(invocation.getThis(), method,
                        invocation.getArguments(), parameterNameDiscoverer);
                parseExpressionValue(logger, logLevel, loggable.beginMessage(), beginContext);
            }
            try {
                result = invocation.proceed();
                if (whetherParseExpression(loggable.endMessage(), logger, logLevel)) {
                    final EvaluationContext context = new MethodBasedEvaluationContext(invocation.getThis(), method,
                            invocation.getArguments(), parameterNameDiscoverer);
                    context.setVariable(RESULT_VARIABLE, result);
                    parseExpressionValue(logger, logLevel, loggable.endMessage(), context);
                }
                return result;
            } catch (final RuntimeException e) {
                logValues(logger, "Failed with exception: " + e.getMessage(), logLevel);
                throw e;
            }
        }
        return invocation.proceed();
    }

    private void parseExpressionValue(final Logger logger, final Level logLevel, final String expression,
            final EvaluationContext context) {
        if (StringUtils.isBlank(expression)) {
            return;
        }
        Object value = null;
        try {
            value = parser.parseExpression(expression).getValue(context);
        } catch (final Exception e) {
            if (throwExceptionIfInvalidExpression) {
                throw new VMSBusinessException(ErrorCode.internal_error, e,
                        "Failed to parse expression: " + expression);
            }
        }
        logValues(logger, value != null ? value.toString() : expression, logLevel);
    }

    /**
     * If the log level is not enabled, no need to do anything at all.
     */
    private boolean whetherParseExpression(String expression, final Logger logger, final Level logLevel) {
        if (StringUtils.isBlank(expression)) {
            return false;
        }
        switch (logLevel) {
            case INFO:
                return logger.isInfoEnabled();
            case ERROR:
                return logger.isErrorEnabled();
            case WARN:
                return logger.isWarnEnabled();
            case DEBUG:
                return logger.isDebugEnabled();
            case TRACE:
                return logger.isTraceEnabled();
            default:
                return false;
        }
    }
}

How to Troubleshoot and Debug - Programmer Skills


Related: How to Solve Problems
Troubleshooting is fun
We can learn something new, avoid making same mistake in future.
it brings us accomplishment and satisfaction.

How to Troubleshoot and Debug

Check and save current state(logging)
We may not recreate the problem easily, so analyze the problem and save logging first.

Understand the problem first
-- Especially when trouble shoot problem for others(rookie).
First take some time to understand the symptom, what the symptom means, whether it's really a problem
Don't just make some change blindly without understanding the symptom
Check error code, understand how the user is writing the code

Understand the environment first
-- Especially asked to help trouble shoot in other's project which you are not familiar at all
-- Don't blindly think others made some simple/stupid mistake, or same mistake you made before
  -- You din't find some configuration file - it may be because you find it in wrong folder
-- Know how to quickly search/debug in linux
-- Most time, the problem/root cause is simple, or just need some configuration change or there is no problem at all

List/think about what may be the root cause
- trouble shooting problem is thinking what may go wrong
- how it's likely caused by this?
- how easily we can verify it?

- if not likely and not easily to verify it, try/list other possible root cause/approaches first

Read/Check the Log
Change the logging level to know more abut the internal
For example, if we are using spring security library: then change level of org.springframework.security to debug in dev environment.

Check/Use IDE
- The IDE can help to detect problems.
- Eclipse' problems view may tell problems that cause project not build, or mistake in configuration files such as web.xml.

Reproduce the problem (faster)
Try to reproduce the problem locally in our own setup
-- It's much easier to trouble shooting in our local setup, we can do all tricks add breakpoint, change variable value, force return, drop frames to rerun etc.
-- Sometimes the problem is related with data, it only happens with the data in x line with its data. We can change local setup to point to remote data (via creating tunnel etc). - This is much easier to remote debug code in remote server.

Simplify the suspect code
Create simple test cases to reproduce it

If possible, debug and test locally
For example, we can change local setup to use data in remote setup(test or sometimes production lines).

Remote debug if can't debug locally 
- but last resort, slow and sometimes impossible

Use condition breakpoint to change behavior dynamically
Use display view/force return to change behavior
Force the execution of suspect path
-- throw exception, change value etc

Source code is always the ultimate truth
- Don't assume or think ..., check the code to verify it.
- Always find the related code and understand it
  - how it works, how it gets called, how to configure it
  - You can't troubleshoot without know understanding the code first
- We can find examples/working code
- We can understand how/why the code works by running and debug the code

Check the code and log together

Change the Code to Help Debug
-- Add logging


Construct and test hypotheses

- First verify the most-likely, easy-to-verify ones


Google Search using the error message with library, class and method name
Search source code in Github/Eclipse
Search log: use linux command:(f|e)grep

Compare the difference between the code and the failed code
-- Compare different version in git(hub).
-- Search company's code base and find similar code
-- Others may already fixed same problems

If still gets stuck:
Take time to learn the framework/feature etc
Sleep on it, try to solve it later.

Scripting
Write test code using scripting or other languages

Ask in StackOverflow, product's forum
Read the Doc/JavaDoc

Solve problems quickly but find root cause slowly
- Solve problems quickly so others can move on
- But take time to find root cause or reflect if it matters

Collaboration
Ask questions
-- When help solve problems for others or debug other's code.
Get more information as much as possible - when help others
Provide more information when ask help

When work on urgent issues with others
-- Collaborate with others timely
-- Let others know what you are testing, what's your progress, so there is no overlap.

Reflection: Lesson Learned
How we find the root cause, why it takes so long

What we learned
What's the root cause

Why we made the mistake

How we can prevent this happens again

Share the knowledge in the team

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-0.0.0.0-8080-exec-10] org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider   - 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]"

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.
How to searching code in Github
Git - Tips and Tricks
in:path, in:file
path:sub-project/sub-folder
filename:the-name
extension:yml

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(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, false);

But how to do in Jackson2(fastxml)? So I go to Jackson GitHub, then search USE_ANNOTATIONS:
https://github.com/search?q=org%3AFasterXML+USE_ANNOTATIONS&type=Code
Now it's easy to see that I should use MapperFeature.USE_ANNOTATIONS.

Or we can try Google search: site:grepcode.com USE_ANNOTATIONS
https://github.com/jersey/jersey/search?utf8=%E2%9C%93&q=DisableWADL

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 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0'

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

Read the Error Message - Problem Solving Skills


The first step of trouble shooting is to read and understand the error message, then we can infer,guess and list likely causes from it, verify or exclude it one by one.

Senario 1
After upgrade some library to newer version and upgrade to JDK 8 and tomcat 8, deployment of the web application fails.

Step 1: Read/Understand the error message
SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webappA]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1798)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/webappA] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1Boolean->org.bouncycastle.asn1.DERBoolean->org.bouncycastle.asn1.ASN1Boolean]
        at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2066)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2012)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1936)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1897)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5080)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 10 more
In another app, the error message is:
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/megaphone-admin-1.0.3_jbuild363] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1EncodableVector->org.bouncycastle.asn1.DEREncodableVector->org.bouncycastle.asn1.ASN1EncodableVector]

Step 2: Find which jar contains the class
org.bouncycastle.asn1.DERBoolean
http://www.findjar.com/class/org/bouncycastle/asn1/DERBoolean.html

ls -altr | grep bcprov
-rw-r--r-- 1 tomcat tomcat  2902942 Sep 25 22:01 bcprov-jdk15on-1.52.jar
-rw-r--r-- 1 tomcat tomcat  1876535 Oct 12 07:01 bcprov-jdk16-1.46.jar
-rw-r--r-- 1 tomcat tomcat  1593423 Oct 12 07:01 bcprov-jdk15-140.jar

run mvn dependency:tree and check why these jars are imported, and use dependency/exclusion to exclude the old ones.
<exclusion>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcmail-jdk15on</artifactId>
</exclusion>
<exclusion>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15on</artifactId>
</exclusion>

Senario 2
When deploy the app to jdk8, it fails:
org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 18.

To fix it, I need upgrade aspectj related libs to latest one 1.8.9 - exclude from the framework that imported it, and explicitly declare them to use 1.8.9.

Then when I run mvn clean install, it fails:  
The following artifacts could not be resolved: aspectjrt:org.aspectj:jar:1.8.9, aspectjweaver:org.aspectj:jar:1.8.9

It took me one hour and finally realized that I made a stupid mistake: I typed artifactId where it should be groupid.
<exclusion>
  <artifactId>org.aspectj</artifactId>
  <groupId>aspectjrt</groupId>
</exclusion>

If I can check the error message more carefully and think about the possible causes, it would save me a hour.

Senario 3
Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0'
I converted the xml declaration of authentication-manager to java config bean, it failed with above error.

There are a lot of error messages(200+ lines), but as long as I scan all error messages, the root cause is clear:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is java.lang.IllegalArgumentException: A parent AuthenticationManager or a list of AuthenticationProviders is required
....
Caused by: java.lang.IllegalArgumentException: A parent AuthenticationManager or a list of AuthenticationProviders is required
at org.springframework.security.authentication.ProviderManager.checkState(ProviderManager.java:117) ~[spring-security-core-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.security.authentication.ProviderManager.<init>(ProviderManager.java:106) ~[spring-security-core-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.security.authentication.ProviderManager.<init>(ProviderManager.java:99) ~[spring-security-core-3.2.5.RELEASE.jar:3.2.5.RELEASE]

at xx.services.app.config.WebSecurityConfiguration.authenticationManager(WebSecurityConfiguration.java:33) ~[WebSecurityConfiguration.class:na]

This is because of the bug in the code: I first create an empty list then create authenticationManager with the empty list.
@Bean
public AuthenticationManager authenticationManager() {
    final List<AuthenticationProvider> providers = new ArrayList<>();
    // this will fail: we have to first add providers to the list then create authenticationManager with the non-empty provider list.
    final AuthenticationManager authenticationManager = new ProviderManager(providers);
    ...// build daoAuthenticationProvider, ldapAuthenticationProvider
    providers.add(daoAuthenticationProvider);
    providers.add(ldapAuthenticationProvider);
}

Solving Problem from Different Angles - Programmer Skills


Senario
Hit one issue in production: when we query solr, the parameter rows is too small. 
We need fix this problem ASAP.

One possible solution is to fix the code and make a new deployment.
Another possible solution is to change the data so the one we want to return to client listed at first.

The solution that we used is to change solrconfix xml(only we uses the solr server) to always get 100 rows, ignore rows client passes.

https://wiki.apache.org/solr/SearchHandler
-- invariants - provides param values that will be used in spite of any values provided at request time. They are a way of letting the Solr maintainer lock down the options available to Solr clients. Any params values specified here are used regardless of what values may be specified in either the query, the "defaults", or the "appends" params.

<requestHandler name="/select" class="solr.SearchHandler">
   <lst name="defaults">
     <str name="echoParams">explicit</str>
     <int name="rows">10</int>
   </lst>

   <lst name="invariants">
     <int name="rows">100</int>
   </lst>
</requestHandler>
Later we fixed the code and design issue, and removed the invariants in solrconfig.xml.

How to Solve Problems


Don't overcomplicate it.
In most case, the solution is actually quite easy.
Try simplest solution first.

Understand the problem/environment first
Understand the problem.
-- Look carefully at the logging, the symptom.
Think about it first before google search otherwise it may just lead you to totally wrong directions.

Make sure you understand the root cause and the final solution.

Troubleshooting problem is thinking what may go wrong
- how it's likely caused by this?
- how easy we can verify the assumption?
- if not likely and not easily to verify it, try/list other possible root cause/approaches first

Try different approaches
Try to ask different questions (probable solution) and google it.

Track what change you have made
Check when it stops working, and what change u have made.


When help others
Ask what related change they have done

Ask help from others.
But be sure to understand the problem and have tried to fix by yourself.
Provide log or any information that may help others understand the problem.

When work with others
If you are trouble shooting problems together with others, communicate with them, know each other progress, doubt, what u will try next etc. They may try different approaches that may help to get final solution.

If no progress and too late or tired, go to rest and try it later or talk with others.

Solve problem quickly and Learn from it
Solve the problem first (so the project or others can move on) then try to learn related stuff later.
Write down what to check or learn later.

Take the chance to expand your knowledge.

Think More
Think over the code/problem, try to find better solution even it's already "fixed"

Check whether the problem also happens in other places(code, different server etc), if so, fix them.

Misc
Check configuration
-- If it works in dev-line, but fails in product line.

-- Happy hacking

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)