Java/JavaScript Tips on Append to File

This is Java/JavaScript Tips on Append content to file. I will introduce append file via command line, Java, and Node.JS (JavaScript).

To append file via command line, in Windows or Unix, you can do:

echo "test" >> a.txt

The file a.txt will be created if not exist at the first time. And the subsequence calls of >> will append the content to next line of the end of file.

To append file via Java, you can do:

PrintWriter pw = new PrintWriter(new FileWriter(new File("a.txt"), true)); 
pw.println("test");
pw.close();

The file a.txt will be created if not exist at the first time. And the subsequence calls of PrintWriter.println will append the content to next line of the end of file.

The interesting thing is I like to use PrintWriter, to call println, which I not need to append \n myself.

Notice the true variable at new FileWriter, this let Java know you want to append file, if you not provide this variable, Java will always overwrite the file but not appending.

To append file via JavaScript, you can do:

in asynchronous calls:

var fs = require('fs');
fs.appendFile('a.txt', 'content\n', function(err) {
 // some callback after append file
});

OR

in synchronize calls:

var fs = require('fs');
fs.appendFileSync('a.txt', 'content\n');

The file a.txt will be created if not exist at the first time. And the subsequence calls of appendFile or appendFileSync will append the content to next line of the end of file.

Node.JS provides asynchronous and synchronize versions for each File IO Calls. Refer the link here. Other than appendFile, for example, readFile/readFileSync, writeFile/writeFileSync.

Node.JS itself is a single threaded and asynchronous. It is always recommended to use asynchronous version of method instead of synchronize version, as synchronize version is a blocking calls. If the content need append to file is very very big, the calls will just hang there, Node.JS cannot handle other requests anymore. To learn how Node.JS back end works, refer here.

WordPress Themes Upgrade Stuck in Maintenance Mode

Just now I tried upgrading my WordPress Themes and it just stuck in maintenance mode. The page just stuck there, whole site shows maintenance mode, I do not how.

I googled it and I found, remove .maintenance file in root, then will disable maintenance mode, and it worked.

I do not know if any problems or not because I just hang up the upgrading process. Hope everything working fine as if you can read this post OK

Java tips String concatenations using StringBuffer

Java provides StringBuffer and String. Always use StringBuffer when you want concatenate string. StringBuffer has better performance over String when doing simple string concatenation.

String is immutable, that something cannot be changed. When you concatenate using String, JVM actually create new Object for each concatenation. Create new Object is expensive. See below example.

When using String, you may doing something like:

String message = ""; // new object
message = message + "I am "; // another new
message = message + "25"; // another new
message = message + " years old"; // another new

When using StringBuffer, you will doing something like

StringBuffer sb = new StringBuffer(); // new object here
sb.append("I am ");
sb.append("25");
sb.append(" years old");
String message = sb.toString(); // another new

As you can see, by using String, you create a bunch of new objects. When you have more things to concatenate, more and more objects created, and again, creating new object is very expensive, and make application performance worse.

It is strongly recommended by using StringBuffer to append string, and at the last, call toString() to export the string content into String object, then you can use it for any purpose.

So for the example on Java tips on joining string with separator, the code can be changed to below:

private static String join_1(String[] array, String separator) {
	StringBuffer sb = new StringBuffer();
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		sb.append(comma + array[i]);
		comma = separator;
	}
	return sb.toString();
}

private static String join_2(String[] array, String separator) {
        StringBuffer sb = new StringBuffer();
	for(int i = 0; i < array.length; i++) {
		sb.append(array[i] + separator);
	}
        String s = sb.toString();
	return s.substring(0, s.length() - separator.length());
}

Another note, when use String for concatenation, internally it will create StringBuffer to do actual concatenation. Refer this link for more information.

Titanium Mobile tips to get weather forecast message

This is Titanium Mobile tips to get weather forecast message, which you can use to implement in your native iOS apps.

This tutorial required Imgshow Library for Titanium Mobile hosted on Github.

We require Titanium.Geolocation method to get our current latitude and longitude, and then pass this info to API, to get weather forecast message.

The sample code to get weather forecast message:

var fetchWeather = function(cb) {
	
	Titanium.Geolocation.purpose = "Get Weather";
	Titanium.Geolocation.getCurrentPosition(function(evt) {
		
		var lat = evt.coords.latitude;
		var lng = evt.coords.longitude;
		imgshow().name('weather').p('lat', lat).p('lng', lng).p('display', 'label').load(function(data) {
			cb(data);
		});
		
	});
};
fetchWeather(function(message) {
  alert("Weather now is: " + message);
});

The sample response would be: Weather now is 28 C Mostly Cloudy at Jurong Town, Singapore.

JavaScript Tips on Objects and Array and their For loop

This is JavaScript Tips on Objects and Array and their For loop.

In JavaScript, there is an Object and represented as:


var someObj = {name:"YongHao", age:25}

There is an Array and represented as:


var someArr = [1,2,3,4]

Use normal for loop only for Array, and use for…in only for Object.

For example, for Object

var someObj = {name:"YongHao", age:25}
for(var i in someObj) {
  console.log(i + ' - ' + someObj[i]);
}

We get:
name – YongHao
age – 25

For Array

var someArr = [1,2,3,4]
for(var i = 0; i < someArr.length; i++) {
  console.log(i + ' - ' + someArr[i]);
}

We get:
0 - 1
1 - 2
2 - 3
3 - 4

Do not use for...in to Array, if you do:

var someArr = [1,2,3,4]
for(var i in someArr) {
  console.log(i + ' - ' + someArr[i]);
}

It may return good result, but not recommended, as i now is a string but not an integer.

UltraSound Data Transfer And Receiver

I did a lab testing based on the open source code on Github for UltraSound Data Transfer and Receiver project. By transmitting data from iOS device to desktop Chrome using Ultra Sound without WIFI network. It just works.

To test this, please open your Desktop browser and a mobile phone, either iPhone or Android to the below URL. Click button on mobile phone, then see response on Desktop browser.

http://ultrasound.herokuapp.com/

It is really amazing. This is not new, but amazing, it works.

Currently I found it may affected by noisy environment, for example, fan. And it is only capable of transmitting small amount of data, and within short distance due to the nature of UltraSound. But it is enough to transfer PIN securely from one device to another without using networks, which avoids to be hacked by someone.

I found if I encode a six digit pin. Due to noisy environment, sometimes it may transfer six digit, sometimes lesser, but there is an important characteristics, that if transferred digit is six, the number ordered always correct. The orders always correct but some numbers in the middle may be missing due in transmission.

Java/JavaScript tips for removing list elements when iterating list

This is Java and JavaScript tips for same topic, removing list elements when iterating list.

In Java, we will use List as an example, as it is uncommon to remove element from an Array. In Javascript we will use Array as an example, as only Array is supported in JavaScript.

Introduction

To remove an element from a Java List, you will do

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");
someList.remove(1); // to remove by index
someList.remove("one); // to remove by element value
System.out.println(someList);

To remove an element from a JavaScript Array, you will do

var someArray = ["two", "one", "three"];
someArray.splice(1, 1); // to remove by index
console.log(someArray);

What if you want to remove an element from a List or Array when you iterating the List, you want to remove it based on some conditions?

In Java, you may do

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");

for(String item : someList) {
  if(item.equals("one")) {
    someList.remove(item); // #1
  }
  else if(item.equals("three")) {
    someList.remove(item); // #2
  }
}

Unfortunately, by doing this, you will get exception thrown.

By executing line #1, “one” is removed from someList, and next if you still continue the for loop, you will get exception as someList is modified, affecting the for loop execution.

The best way to remove item from a Java list is to use Iterator

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");

Iterator it = someList.iterator();
while(it.hasNext()) {
  String item = it.next();
  if(item.equals("one")) {
    it.remove();
  }
  else if(item.equals("three")) {
    it.remove();
  }
}

System.out.println("Latest someList: " + someList);

This is the safe way to remove items from List when you will still continue iterating over the someList.

In JavaScript, you may do

var someArray = ["two", "one", "three"];
for(var i = 0; i < someArray.length; i++) {
  if(someArray[i] == "one") {
    someArray.splice(i, 1); // #1
  }
  else if(someArray[i] == "three") {
    someArray.splice(i, 1); // #2
  }
}

Unfortunately, by doing this, you will get exception thrown.

By executing line #1, "one" is removed from someArray, and next if you still continue the for loop, you will get exception as someArray is modified, affecting the for loop execution.

The best way to remove item from a JavaScript array is to iterate the Array from last.

var someArray = ["two", "one", "three"];
for(var i = someArray.length - 1; i >= 0; i--) {
  if(someArray[i] == "one") {
    someArray.splice(i, 1); // #1
  }
  else if(someArray[i] == "three") {
    someArray.splice(i, 1); // #2
  }
}

This is the safe way to remove items from JavaScript Array.

Why this works? You may think same thing also applies to Java right? Yes you are right. How this works? Leave it for your back home reading.

JavaScript universal http request method – frequest

I wrote some universal JavaScript method for my apps, across Node.JS and Titanium Mobile, Freeswitch, jQuery. Here introduces a very simple but useful method, http request.

We all doing HTTP request on our apps. Make a request via HTTP and get back the response. I designed an API that I can use the same method signature when I am developing apps for Node.JS and Titanium Mobile. Node.JS is a server side program, and Titanium Mobile is a framework compile to Native iOS code. Freeswitch is an open source SIP Media Server, supports JavaScripts to create IVR apps. jQuery is a web based client framework. These platforms had different underlying native libraries to do HTTP request. I just want to design a very simple API that can wrap up these platforms, then I can share code easily across these platform.

The client code I can do:

frequest({
    url : 'http://somewebsite.com',
    callback : function(data) {
        console.log(data);
    }
});

The code for Node.JS:

frequest : function(args) {
		var http = require('http');
		
		try {
			var options = {};
		
			if(args.options) {
				
				options = args.options;
				
			}
			 
			if(args.url) {
				if(args.url.indexOf('http') == -1) return;
				var b = require('url').parse(args.url);
				
				// resolve host name
				if(b.hostname) {
					options.host = b.hostname;
				}
				
				// resolve port
				if(!b.port) {
					b.port = 80;
				}
				
				if(b.port) {
					options.port = b.port;
				}
				
				// resolve web path
				if(b.pathname) {
					options.path = b.pathname;
					
					if(b.search) {
						options.path += b.search;
					}
				}
					
			}
			
			if(args.headers) {
				options.headers = args.headers;
			}
		    
		    var request = http.get(options);
		
			if(args.callback || args.callbackJSON) {
				request.addListener('response', function(response){
				    var data = '';
				
				    response.addListener('data', function(chunk){ 
				        data += chunk; 
				    });
				    response.addListener('end', function(){
				        
				        // prepare data for callback
				        
				        if(data != '') {
				        	if(args.callback) {
					        	args.callback(data);
					        }
					        
					        if(args.callbackJSON) {
					        	try {
					        		var json = JSON.parse(data);
					        		args.callbackJSON(json);	
					        	
					        	} catch (e) {
					        		console.log(e);
					        	}
					        }
				        }
				        
				    });
				});
			}
		} catch (e) {
			console.log(e);
		}
		
		
	
	}

The code for Titanium Mobile:

var frequest = function(args) {
	
	
	var xhr = Ti.Network.createHTTPClient();
	xhr.onload = function() {
		var res = this.responseText;
		
		if(args.callback) {
			args.callback(res);
		}
		
		if(args.callbackJSON) {
			args.callbackJSON(JSON.parse(res));
		}
	};
	
	xhr.onerror = function(e) {
		// detect message
		var errortitle = 'Connection Failure Error';
		var errormsg = ''; // define some suggested network failure message
		if(e.error && e.error.indexOf('A connection failure occurred')) {
			errormsg = 'A connection failure occurred';
		}
		if(args.errorCallback) {
			args.errorCallback({
				e : e,
				errormsg : errormsg
			});
		} else {
			Ti.UI.createAlertDialog({
				title : errortitle,
				message : errormsg
			}).show();
		}
	}
	if(args.timeout) {
		xhr.timeout = args.timeout;
	}
	if(args.progressCallback) {
		xhr.onsendstream = function(e) {
			args.progressCallback(e.progress);
		}
	}
	
	var method = args.method || 'GET';
	xhr.open(method, args.url);
	if(args.headers) {
		for(var k in args.headers) {
			var v = args.headers[k];
			xhr.setRequestHeader(k,v);
		}
	}
	var params = args.params || null;
	if(params != null) 
		xhr.send(params);
	else
		xhr.send();
};

The code for Freeswitch:

frequest : function(args) {
		var result = fetchUrl(args.url);
		if(args.callback) {
			args.callback(result);
		}
	}

The code for jQuery:

var frequest = function(args) {
    $.ajax({
      url : args.url,
      success : args.callback
    });
};

Feel free to share your code for related frequest implementation.

Java tips on joining string with separator

This is Java tips on joining string with separator. Sometimes you have an Array or List and you want to join the String with separator. For example, an Array {“one”,”two”,”three”}, you want to make it as a String as “one,two,three”.

You can have several ways, here do two:

private static String join_1(String[] array, String separator) {
	String s = "";
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		s = s + comma + array[i];
		comma = separator;
	}
	return s;
}

private static String join_2(String[] array, String separator) {
	String s = "";
	for(int i = 0; i < array.length; i++) {
		s = s + array[i] + separator;
	}
	return s.substring(0, s.length() - separator.length());
}

I will recommend first method. Here is my analysis.

Both code run in same speed. Test by putting 10000 elements of array.

First code will simply lesser memory consumption compared to second code. As String#substring will create another new copy of String with different offset.