Tomcat Src – tomcat logging

This is starting of tomcat source code analysis.

Tomcat Log is simple.

the following is main example on how to invoke tomcat logging

1
2
3
4
5
6
7
8
9
10
11
12
13
 
package main;
 
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
 
public class tomcat {
	public static void main(String[] args) {
		Log log = LogFactory.getLog(tomcat.class);
		log.info("this is a info message from tomcat");
		log.debug("this is a debug message from tomcat");
	}
}

but when debugging tomcat src, I find that org.apache.juli.ClassLoaderLogManager is invoked.

Its entry is in catalina.sh as starting up script for tomcat.

1
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

YaraScanService – How to remove it

after Mac OS is upgraded to High Sierra, YaraScanService which is part of MRT.app would start automatically.
YaraScanService takes about 20GB memory in my macbook pro.

so it would make whole mac os frozen.

Even it is working, it would stop a while and start to work.
User wouldn’t feel smoothly operation.

Here is step on how to remove YaraScanService
1. reboot mac os and press ‘Command + R’ to boot into recovery mode.
2. Click the “Utilities” menu and select “Terminal” to open a terminal window.
3. run command csrutil
# csrutil status
# csrutil disable
4. reboot mac os again, now command such as ‘rm -rf xxx’ will work and won’t receive any deny message.
5. after login into macos, open “Terminal” and run
$ sudo rm -rf /System/Library/CoreService/MRT.app
6. in /System/Library/LaunchDaemons , run
$ grep -nri “mrt” *

and delete all files that are displayed on result
7. in /System/Library/LaunchAgent, run
$ grep -nri “mrt” *

and delete all files that are displayed on result

8. reboot mac os, now do some test to check YaraScanService is started or not.
9. go to recovery mode to enable csrutil
$ csrutil enable

Backtrace – leetcode 17 – Letter Combinations of a Phone Number

this is a very classic backtrace problem.

Idea is simple, use ‘call stack’ to store string “a…z”

stack n – z
.
.
stack 1 – a

if stack.length == targetLenth
loop though stack to get char array to string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
package com.dw.leetcode;
 
import java.util.*;
 
public class Letter_Combinations_of_a_Phone_Number_17 {
	static final char[][] number = { { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' },
			{ 'm', 'n', 'o' }, { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z' }
	};
 
    public List<String> letterCombinations(String digits) {
    	List<String> result = new ArrayList<String>();
    	if(digits.length() == 0){
            return new ArrayList<>(); 
        }
 
    	foo(digits, 0, 0, digits.length(), new ArrayList<Character>(), result);
    	return result;
    }
 
    public void foo(String digits, int index, int total, int len, List<Character> temp, List<String> result) {
    	if(total == len) {
    		StringBuilder stringBuilder = new StringBuilder();
    		for(Character c: temp) {
    			stringBuilder.append(c);
    		}
    		result.add(stringBuilder.toString());
    		return;
    	}
 
    	int numberIndex = Integer.parseInt(Character.toString(digits.charAt(index)));
 
    	for(char c: number[numberIndex - 2]) {
    		temp.add(c);
    		foo(digits, index+1, total+1, len, temp, result);
    		temp.remove(temp.size() - 1);
    	}
    }
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Letter_Combinations_of_a_Phone_Number_17 s = new Letter_Combinations_of_a_Phone_Number_17();
		System.out.println(s.letterCombinations("234"));
	}
 
}

javascript – download Blob file directly

As we know that for security issue, browser would disable javascript to download file directly.

but today what I want to show is to use javascript to click on ‘a’ link to download file
using Blob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement("a");
    if (link.download !== undefined) { 
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

Anypoint Studio Frozen Problem when starting on Mac Platform

Anypoint Studio Frozen Problem when starting on Mac Platform

solution: most important is to install jdk 1.8.0 151, this is max version of anypoint studio that support.
any version older that 151 would fail to work.

Edit target AnypointStudio.ini
AnypointStudio.app/Contents/Eclipse/AnypointStudio.ini

use
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/bin
to point to JAVA_HOME of jdk 1.8 151

use
-clean to clean up workspace

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-clean
-startup
../Eclipse/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/bin
--launcher.library
../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.300.v20150602-1417
-vmargs
-Xms512m
-Xmx1536m
-XX:MaxPermSize=512m
-Dosgi.instance.area.default=@user.home/AnypointStudio/workspace
-Dhttps.protocols=TLSv1.1,TLSv1.2
-Djava.awt.headless=true
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts

javascript – using await to make sleep

In old day, when using javascript to create timer,

setInterval or setTimeout are standard function to implement
A few other way to do is using third-party npm library.
or even calling c++ as native timer.

with ES2016, await and asyn keyword has been introducted into.
Here is example.

1
2
3
4
5
6
7
8
9
10
11
12
 
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}
 
demo();

Spring Tomcat – integration error

Spring with Tomcat

add spring security, then restart tomcat get the following error.

1
2
3
4
5
6
7
8
9
10
11
12
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
	at java.util.zip.ZipFile.read(Native Method)
	at java.util.zip.ZipFile.access$1400(ZipFile.java:60)
	at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:717)
	at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:419)
	at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
	at sun.misc.IOUtils.readFully(IOUtils.java:65)
	at java.util.jar.JarFile.getBytes(JarFile.java:425)
	at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193)
	at java.util.jar.JarFile.getManifest(JarFile.java:180)
	at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:140)
	... 13 more

try to build on console.

$ mvn package.

if mvn says some jar/war is interuptted,
then delete these files and let mvn to download them again

Spring 5 has to default a passwordEncoder

However, if passwordEncoder is set to be NoOpPasswordEncoder to ‘ignore’ passwordEncorder

1
2
3
<bean id="passwordEncoder"
class="org.springframework.security.crypto.password.NoOpPasswordEncoder"
factory-method="getInstance">

Spring MVC and Spring Boot with Angular.js

1. Download STS, there are two ways to use spring tools. First, eclipse with its plugins,
go to eclipse marketing place. I didn’t recommend using raw eclipse with spring plugins,
because during I develop, I find eclipse with plugin may fail to work.sometime, it may reinstall every time when eclipse restart.
I highly recommend to download STS whole toolset form https://spring.io/tools/sts. Once it is downloaded and unpacked, it will be used as eclipse.

2. Maven is mainly project management tools. Two important concept.
Parent POM and Child POM, in parent project, it has pom.xml which will contains child project pom.xml as module, while child project will also reference parent project in its POM.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<project>
...
        <groupId>org.springframework.samples</groupId>
	<artifactId>spring-petclinic-angular1</artifactId>
	<version>2.0.0-M3</version>
	<name>Spring Petclinic :: Parent POM</name>
	<packaging>pom</packaging>
 
	<modules>
		<module>spring-petclinic-client</module>
		<module>spring-petclinic-server</module>
	</modules>
...
</project>
1
2
3
4
5
6
7
8
9
<project>
...
	<parent>
		<groupId>org.springframework.samples</groupId>
		<artifactId>spring-petclinic-angular1</artifactId>
		<version>2.0.0-M3</version>
	</parent>
...        
</project>

3. Create parent project
new_project

<1>.choose ‘Spring Start Project’, click ‘next’ following by wizard filling with information.
<2>.delete all folders, only keep two folders ‘spring-petclinic-client’ and ‘spring-petclinic-server’ for child projects
Screen Shot 2017-12-25 at 10.49.51 pm

4. Create child frontend project
<1> choose ‘Spring Start Project’, click ‘next’ following by wizard filling with information.
<2> delete ‘src/main/java’, ‘src/main/resources’, ‘src/test/java’
<3> add bower.json, glupfile.js, package.json and keep src as resource.
Screen Shot 2017-12-25 at 11.20.10 pm

5. create child backend project
<1> choose ‘Spring Start Project’, click ‘next’ following by wizard filling with information.
for backend, project is OK to keep original structure.
restful controller will map url to method.
@PostMapping(“/owners/{ownerId}/pets/{petId}/visits”)
@ResponseStatus(HttpStatus.NO_CONTENT)
Screen Shot 2017-12-25 at 11.24.24 pm

6. run ‘mvn package -DskipTest’ on parent project folder to build all project.
Now we finish all project structure creating process.
for more code, https://github.com/emacslisp/spring-project/tree/master/spring-petclinic-angular1

JQuery – Deferred, then, Apply

One simple example on how to use

1
2
3
4
5
6
7
8
9
10
11
12
function getPromise() {
    var deferred = $.Deferred();
    deferred.resolve("Hello");
 
    return deferred.promise;
}
 
getPromise().then(
    function(data) {
        console.log(data); // output 'hello'
    }
);

will put JQuery Deferred-then-Apply source code analysis later on.

VPS – add Swap to enhance performance

VPS normally does not have any swap space.

1
2
3
4
5
6
7
8
9
10
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
 
/etc/fstab:
/var/swap.1 swap swap defaults 0 0
 
# if it not mounted as swap, using command 
sudo /sbin/swapon /var/swap.1

swap size should be 2 times than Memory for 512MB, 1GB Memory.
Why? take Memory size 512MB for example, when 512MB is full, it will put into some of data into swap,
if now machine is sleeping, it will put 512MB into swap.
therefore, ideally swap should be 2 times than physical memory.

However, for large memory such as 16GB, swap size is based on what you need, for example, 2GB.