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.

Ionic using Sqlite

Sqlite is better than ‘local storage’ and ‘session’ for complex data relationship on ionic/cordova platform.

Here is instruction on how to install

1. create an empty ionic app
$ ionic start myApp blank –type ionic1

2. add Cordova for sqlite native plugin
$ bower install ngCordova
it will install ‘www/lib/ngCordova/’.

3. install sqlite native plugin
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install –save @ionic-native/sqlite

4. in www/index.html, add

5. in app.js make app.js looks like.

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
var myApp = angular.module('starter', ['ionic','ngCordova'])
 
    .run(function($ionicPlatform, $cordovaSQLite) {
 
        $ionicPlatform.ready(function() {
            if(window.cordova && window.cordova.plugins.Keyboard) {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
 
                // Don't remove this line unless you know what you are doing. It stops the viewport
                // from snapping when text inputs are focused. Ionic handles this internally for
                // a much nicer keyboard experience.
                cordova.plugins.Keyboard.disableScroll(true);
 
            }
            if(window.StatusBar) {
                StatusBar.styleDefault();
            }
 
            var db;
            if (window.cordova) {
                db = $cordovaSQLite.openDB({ name: "my.db" }); //device
            }else{
                db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
            }
            $cordovaSQLite.execute(db,"create table if not exists people(id integer primary key, firstname text, lastname text)");
            //$cordovaSQLite.deleteDB("my.db");  
 
        });
    })

Key Important code:

1
2
3
4
5
            if (window.cordova) {
                db = $cordovaSQLite.openDB({ name: "my.db" }); //device
            }else{
                db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
            }

this code snippet is key important because when running on browers using ‘ionic serve’, we use ‘window.openDatabase’ rather than native plugin.

passport.js with node.js to do Local Authentication

The whole example could be found in:

https://github.com/emacslisp/angular2/tree/meteor/passport-local

prerequisites

1. create an empty folder for project, say ‘passport-local’

1
2
3
4
5
6
7
npm init
npm install passport --save
npm install passport-local --save
npm install jade --save
npm install mongodb --save
npm install mongoose --save
npm install passport-local-mongoose --save

2. install mongodb and run
$ mongod

3. create an app.js

1
2
3
4
5
6
7
 
var path = require('path');
var express = require('express');
var http = require('http');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

for more details check github project.

4. ‘node app’ to run the example

5. register user firstly, you will see ‘Account’ doc has been created with username, password and salt.

6. try to login to get session.

WordPress – analysis wp_admin_css(‘install’,true);

as we know css is key role for web page,

wordpress using wp_admin_css(‘install’, true); to print link css.
in format of <link href=’…/xxx.css’>

the most important statement.

1
$tag = apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle, $href, $media);

“<link rel=’$rel’ id=’$handle-css’ $title href=’$href’ type=’text/css’ media=’$media’ />\n” will be replaced
to be ‘<link rel=’stylesheet’ id=’install-css’ href=’http://localhost:8082/wordpress2/wp-admin/css/install.min.css?ver=4.7.2′ type=’text/css’ media=’all’ />

Let’s look at what define of apply_filters, “apply_filters($tag,$value)”. ‘style_loader_tag’ has nothing in global variable $wp_filter.

Therefore, apply_filters do nothing here, it only return second param as string to print.

1
2
3
4
echo $conditional_pre;
echo $tag;
$this->print_inline_style( $handle );
echo $conditional_post;