Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i...
Stats
Socket sample
SocketCallBack.java
  1. package bruce.chat;
  2.  
  3. import java.net.Socket;
  4.  
  5. public interface SocketCallBack {
  6.     void onAccepted(Socket socket);
  7. }
ChatServer.java
  1. package bruce.chat;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7.  
  8. import javax.net.ServerSocketFactory;
  9.  
  10. public class ChatServer {
  11.  
  12.     private ServerSocket serverSocket;
  13.     private boolean stopFlag;
  14.     private SocketCallBack callback;
  15.  
  16.     public static ChatServer createEntry(int port) throws IOException {
  17.         ChatServer entry = new ChatServer();
  18.         entry.serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
  19.         entry.stopFlag = true;
  20.  
  21.         return entry;
  22.     }
  23.  
  24.     public static ChatServer createEntry(int port, int backlog, InetAddress ifAddress) throws IOException {
  25.         ChatServer entry = new ChatServer();
  26.         entry.serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, backlog, ifAddress);
  27.         entry.stopFlag = true;
  28.  
  29.         return entry;
  30.     }
  31.  
  32.     /**
  33.      * 起始監聽通道
  34.      */
  35.     public void startListen() {
  36.         new Thread() {
  37.             @Override
  38.             public void run() {
  39.                 while (ChatServer.this.stopFlag) {
  40.                     try {
  41.                         ChatServer.this.startAccept(ChatServer.this.serverSocket.accept());
  42.                     } catch (IOException e) {
  43.                         // TODO Auto-generated catch block
  44.                         if (ChatServer.this.stopFlag)
  45.                             e.printStackTrace();
  46.                     }
  47.                 }
  48.             }
  49.         }.start();
  50.     }
  51.  
  52.     /**
  53.      * 開始接收資料
  54.      * 
  55.      * @param socket
  56.      *            要接收資料的通訊埠
  57.      */
  58.     private void startAccept(final Socket socket) {
  59.         new Thread() {
  60.             @Override
  61.             public void run() {
  62.                 ChatServer.this.callback.onAccepted(socket);
  63.  
  64.                 if (!socket.isClosed()) {
  65.                     try {
  66.                         socket.close();
  67.                     } catch (IOException e) {
  68.                         // TODO Auto-generated catch block
  69.                         e.printStackTrace();
  70.                     }
  71.                 }
  72.             }
  73.         }.start();
  74.     }
  75.  
  76.     public void stopListen() {
  77.         this.stopFlag = false;
  78.         try {
  79.             this.serverSocket.close();
  80.         } catch (IOException e) {
  81.             // TODO Auto-generated catch block
  82.             e.printStackTrace();
  83.         }
  84.     }
  85.  
  86.     public void setCallback(SocketCallBack callback) {
  87.         this.callback = callback;
  88.     }
  89. }
ChatClient.java
  1. package bruce.chat;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7.  
  8. import javax.net.SocketFactory;
  9.  
  10. public class ChatClient {
  11.  
  12.     private Socket socket;
  13.  
  14.     public void connect(String host, int port) throws UnknownHostException, IOException {
  15.         this.socket = SocketFactory.getDefault().createSocket(host, port);
  16.     }
  17.  
  18.     public void connect(InetAddress host, int port) throws IOException {
  19.         this.socket = SocketFactory.getDefault().createSocket(host, port);
  20.     }
  21.  
  22.     public void send(byte[] data) throws IOException {
  23.         this.socket.getOutputStream().write(data);
  24.     }
  25.  
  26.     public void close() {
  27.         if (this.socket != null)
  28.             try {
  29.                 this.socket.close();
  30.             } catch (IOException e) {
  31.                 // TODO Auto-generated catch block
  32.                 e.printStackTrace();
  33.             }
  34.     }
  35. }
Program.java
  1. package bruce.chat;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.InetAddress;
  7. import java.net.Socket;
  8. import java.nio.ByteBuffer;
  9. import java.util.Date;
  10. import java.util.Scanner;
  11.  
  12. public class Program {
  13.  
  14.     /**
  15.      * @param args
  16.      * @throws IOException
  17.      */
  18.     public static void main(String[] args) throws IOException {
  19.         // TODO Auto-generated method stub
  20.  
  21.         ChatServer server = ChatServer.createEntry(9999);
  22.         server.startListen();
  23.         server.setCallback(new SocketCallBack() {
  24.  
  25.             @Override
  26.             public void onAccepted(Socket socket) {
  27.                 // TODO Auto-generated method stub
  28.                 try {
  29.                     InputStream is = socket.getInputStream();
  30.  
  31.                     System.out.printf("Received at %s :%n", new Date());
  32.  
  33.                     // ByteBuffer temp = ByteBuffer.allocate(10240);
  34.                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
  35.                     int readed = -1;
  36.                     byte[] buffer = new byte[512];
  37.  
  38.                     while ((readed = is.read(buffer)) > 0) {
  39.                         // temp.put(buffer, 0, readed);
  40.                         baos.write(buffer, 0, readed);
  41.                     }
  42.                     
  43.  
  44.                     // System.out.println(new String(temp.array()));
  45.                     baos.close();
  46.                     System.out.println(baos.toString());
  47.  
  48.                 } catch (IOException e) {
  49.                     // TODO Auto-generated catch block
  50.                     e.printStackTrace();
  51.                 }
  52.  
  53.             }
  54.         });
  55.  
  56.         Scanner sc = new Scanner(System.in);
  57.         String line = null;
  58.         while ((line = sc.nextLine()) != null) {
  59.             if ("bye".equalsIgnoreCase(line))
  60.                 break;
  61.  
  62.             ChatClient client = new ChatClient();
  63.             client.connect(InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 9999);
  64.             client.send(line.getBytes());
  65.             client.close();
  66.  
  67.         }
  68.  
  69.         server.stopListen();
  70.     }
  71.  
  72. }
Translating 2.0
  1. <html>
  2. <head>
  3.     <title>Translation 2.0</title>
  4.     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  5.     <style type="text/css">
  6.         textarea {
  7.             width : 100%;
  8.         }
  9.         div#tagGroup a {
  10.             padding-left : 5px;
  11.             padding-right : 5px;
  12.             border : 1px outset;
  13.             cursor : pointer;
  14.             font-weight : bolder;
  15.         }
  16.         #spendTime {
  17.             font-size : 8pt;
  18.         }
  19.     </style>
  20.     <script type="text/javascript" language="javascript">
  21.         var Translation = {};
  22.         // Copy result to Clipboard
  23.         Translation.Copy = function(){
  24.             if (window.clipboardData){
  25.                 window.clipboardData.setData("Text", document.tform.outputData.value);
  26.             }else if (window.netscape){
  27.                 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
  28.                 var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
  29.                 if (!clip) return;
  30.                 var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
  31.                 if (!trans) return;
  32.                 trans.addDataFlavor('text/unicode');
  33.                 var str = new Object();
  34.                 var len = new Object();
  35.                 var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  36.                 var copytext = document.tform.outputData.value;
  37.                 str.data = copytext;
  38.                 trans.setTransferData("text/unicode",str,copytext.length*2);
  39.                 var clipid=Components.interfaces.nsIClipboard;
  40.                 if (!clip) return false;
  41.                 clip.setData(trans,null,clipid.kGlobalClipboard);
  42.             }else{
  43.                 return false;
  44.             }
  45.             return false;
  46.         };
  47.         // Clear all text
  48.         Translation.Clear = function(){
  49.             document.tform.inputData.value = "";
  50.             document.tform.outputData.value = "";
  51.         };
  52.         // Change function module
  53.         Translation.ChangeTab = function(tabObj, fuc){
  54.             // #region change tab color
  55.             var tabs = document.getElementById("tagGroup").childNodes;
  56.             for(var index in tabs){
  57.                 if("A" == tabs[index].tagName){
  58.                     tabs[index].style.backgroundColor = "white";
  59.                 }
  60.             }
  61.             tabObj.style.backgroundColor = "lightblue";
  62.             // #endregion change tab color
  63.              
  64.             // change description
  65.             document.getElementById("funcDes").innerHTML = fuc.Description;
  66.              
  67.             // #region repaint controls
  68.             var controlPanel = document.getElementById("controlPanel");
  69.             // remvoe all component
  70.             while(controlPanel.firstChild){
  71.                 controlPanel.removeChild(controlPanel.firstChild);
  72.             }
  73.             // add control component
  74.             var component;
  75.             for(index in fuc.Controls){
  76.                 // create component
  77.                 if(component = Translation.CreateElement(fuc.Controls[index])){
  78.                     if("function" == typeof(fuc[component.value])){
  79.                         // assign event delegate
  80.                         component.setAttribute("action", fuc[component.value]);
  81.                         component.onclick = function(){
  82.                             // start caculate time
  83.                             Stopwatch.Start();
  84.                             // execute 
  85.                             this.action();
  86.                             // stop caculate time
  87.                             Stopwatch.Stop();
  88.                             document.getElementById("spendTime").innerHTML = Stopwatch.SpendTime();
  89.                         }
  90.                     }                
  91.                     controlPanel.appendChild(component);
  92.                     // clear stopwatch
  93.                     controlPanel.appendChild(document.createTextNode(" "));
  94.                 }
  95.             }
  96.             // #endregion repaint controls
  97.              
  98.             document.getElementById("spendTime").innerHTML = "";
  99.         };
  100.         // Create action controls
  101.         Translation.CreateElement = function(json){
  102.             // check obect and tag name
  103.             if(json && json.tagName){
  104.                 var e = document.createElement(json.tagName);
  105.                 var child;
  106.                 for(var i in json){
  107.                     if("tagName" == i){
  108.                         // skip tag name
  109.                     }else if("innerHTML" == i){
  110.                         // assgin content
  111.                         e.innerHTML = json[i];
  112.                     }else if("children" == i){
  113.                         // process child nodes
  114.                         if(json[i].constructor == Array){
  115.                             for(var j in json[i]){
  116.                                 if((child = Translation.CreateElement(json[i][j]))) e.appendChild(child);
  117.                             }
  118.                         }else{
  119.                             if((child = Translation.CreateElement(json[i]))) e.appendChild(child);
  120.                         }
  121.                     }else{
  122.                         // assgin attribute
  123.                         e.setAttribute(i, json[i]);
  124.                     }
  125.                 }
  126.                 return e;
  127.             }else{
  128.                 return false;
  129.             }
  130.         };
  131.         // Page resized
  132.         Translation.Resize = function(){
  133.             var docHeight = document.body.offsetHeight;
  134.             var tabHeight = document.getElementById("tagGroup").offsetHeight;
  135.             var headerHeight = document.getElementById("header").offsetHeight;
  136.             var actionsHeight = document.getElementById("actions").offsetHeight;
  137.             var txtHeight = (docHeight - tabHeight - headerHeight - actionsHeight - 80) / 2;
  138.             document.tform.inputData.style.height = txtHeight;
  139.             document.tform.outputData.style.height = txtHeight;
  140.         }
  141.         // Page load
  142.         Translation.Load = function(){
  143.             Translation.ChangeTab(document.getElementById("InitComponent"), Blogger);
  144.             Translation.Resize();
  145.             window.onresize = Translation.Resize;
  146.         };
  147.         // Caculate executing time
  148.         var Stopwatch = {
  149.             Tick : 0,
  150.             Start : function(){
  151.                 this.Tick = new Date().getTime();
  152.             },
  153.             Stop : function(){
  154.                 this.Tick = new Date().getTime() - this.Tick;
  155.             },
  156.             SpendTime : function(){
  157.                 var time = this.Tick;
  158.                 var output = time % 1000 + " milisecond";
  159.                 time = Math.floor(time / 1000);
  160.                  
  161.                 if(time > 0){
  162.                     output = time % 60 + " second " + output;
  163.                     time = Math.floor(time / 60);
  164.                 }
  165.                  
  166.                 if(time > 0){
  167.                     output = time % 60 + " minutes " + output;
  168.                     time = Math.floor(time / 60);
  169.                 }
  170.  
  171.                 return "(" + output + ")";
  172.             }
  173.         }
  174.         // Blogger module
  175.         var Blogger = {
  176.             Description : "Html encode for Blogger posting.",
  177.             Controls : [
  178.                 {tagName : "input", type : "button", value : "Translate"},
  179.                 {tagName : "input", type : "button", value : "Resotre"}
  180.             ],
  181.             Translate : function(){
  182.                 var input = document.tform.inputData.value.split("");
  183.                 var chars = [{s:"&",r:"&amp;"},{s:" ",r:"&nbsp;"},{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"}];
  184.                 for(var i = 0; i < input.length; i++){
  185.                     for(var j in chars) input[i] = input[i].replace(chars[j].s, chars[j].r);
  186.                 }
  187.                 document.tform.outputData.value = input.join("");   
  188.             },
  189.             Resotre : function(){
  190.                 var input = document.tform.inputData.value;
  191.                 var chars = [{s:"\t",r:"&nbsp;&nbsp;&nbsp;&nbsp;"},{s:" ",r:"&nbsp;"},{s:"<",r:"&lt;"},{s:">",r:"&gt;"},{s:"&",r:"&amp;"}];
  192.                 var temp = input;
  193.                 for(var i in chars){
  194.                     while((input = input.replace(chars[i].r, chars[i].s)) != temp) temp = input;
  195.                 }
  196.                 document.tform.outputData.value = input;
  197.             }
  198.         };
  199.         // Url encode/decode
  200.         var UrlEncoder = {
  201.             Description : "URL encode/decode.",
  202.             Controls : [
  203.                 {tagName : "input", type : "button", value : "Translate"},
  204.                 {tagName : "input", type : "button", value : "Resotre"}
  205.             ],
  206.             Translate : function(){
  207.                 document.tform.outputData.value = encodeURI(document.tform.inputData.value);
  208.             },
  209.             Resotre : function(){
  210.                 document.tform.outputData.value = decodeURI(document.tform.inputData.value);
  211.             }
  212.         };
  213.         // BASE64 encode/decode
  214.         var Base64Encoder = {
  215.             KeyCode : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  216.             Description : "Base64 encode/decode.",
  217.             Controls : [
  218.                 {tagName : "input", type : "button", value : "Translate"},
  219.                 {tagName : "input", type : "button", value : "Resotre"}
  220.             ],
  221.             Translate : function(){
  222.                 var input = Base64Encoder.UTF8_encode(document.tform.inputData.value);
  223.                 var output = "";
  224.                 var chr1, chr2, chr3;
  225.                 var enc1, enc2, enc3, enc4;
  226.                 var i = 0;
  227.  
  228.                 do {
  229.                     chr1 = input.charCodeAt(i++);
  230.                     chr2 = input.charCodeAt(i++);
  231.                     chr3 = input.charCodeAt(i++);
  232.  
  233.                     enc1 = chr1 >> 2;
  234.                     enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  235.                     enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  236.                     enc4 = chr3 & 63;
  237.  
  238.                     if (isNaN(chr2)) {
  239.                         enc3 = enc4 = 64;
  240.                     } else if (isNaN(chr3)) {
  241.                         enc4 = 64;
  242.                     }
  243.  
  244.                     output = output + Base64Encoder.KeyCode.charAt(enc1) + Base64Encoder.KeyCode.charAt(enc2) + 
  245.                     Base64Encoder.KeyCode.charAt(enc3) + Base64Encoder.KeyCode.charAt(enc4);
  246.                 } while (< input.length);
  247.                 document.tform.outputData.value = output;
  248.             },
  249.             Resotre : function(){
  250.                 var output = "";
  251.                 var chr1, chr2, chr3;
  252.                 var enc1, enc2, enc3, enc4;
  253.                 var i = 0;
  254.  
  255.                 // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  256.                 var input = document.tform.inputData.value.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  257.  
  258.                 do {
  259.                     enc1 = Base64Encoder.KeyCode.indexOf(input.charAt(i++));
  260.                     enc2 = Base64Encoder.KeyCode.indexOf(input.charAt(i++));
  261.                     enc3 = Base64Encoder.KeyCode.indexOf(input.charAt(i++));
  262.                     enc4 = Base64Encoder.KeyCode.indexOf(input.charAt(i++));
  263.  
  264.                     chr1 = (enc1 << 2) | (enc2 >> 4);
  265.                     chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  266.                     chr3 = ((enc3 & 3) << 6) | enc4;
  267.  
  268.                     output = output + String.fromCharCode(chr1);
  269.  
  270.                     if (enc3 != 64) {
  271.                         output = output + String.fromCharCode(chr2);
  272.                     }
  273.                     if (enc4 != 64) {
  274.                         output = output + String.fromCharCode(chr3);
  275.                     }
  276.                 } while (< input.length);
  277.                 document.tform.outputData.value = Base64Encoder.UTF8_decode(output);
  278.             },
  279.             UTF8_encode : function (string) {
  280.                 string = string.replace(/\r\n/g,"\n");
  281.                 var utftext = "";
  282.                 for (var n = 0; n < string.length; n++) {
  283.                     var c = string.charCodeAt(n);
  284.                     if (< 128) {
  285.                         utftext += String.fromCharCode(c);
  286.                     } else if((> 127) && (< 2048)) {
  287.                         utftext += String.fromCharCode((>> 6) | 192);
  288.                         utftext += String.fromCharCode((& 63) | 128);
  289.                     } else {
  290.                         utftext += String.fromCharCode((>> 12) | 224);
  291.                         utftext += String.fromCharCode(((>> 6) & 63) | 128);
  292.                         utftext += String.fromCharCode((& 63) | 128);
  293.                     }
  294.                 }
  295.                 return utftext;
  296.             },
  297.             UTF8_decode : function (utftext) {
  298.                 var string = "";
  299.                 var i = 0;
  300.                 var c = c1 = c2 = 0;
  301.                 while ( i < utftext.length ) {
  302.                     c = utftext.charCodeAt(i);
  303.                     if (< 128) {
  304.                         string += String.fromCharCode(c);
  305.                         i++;
  306.                     } else if((> 191) && (< 224)) {
  307.                         c2 = utftext.charCodeAt(i+1);
  308.                         string += String.fromCharCode(((& 31) << 6) | (c2 & 63));
  309.                         i += 2;
  310.                     } else {
  311.                         c2 = utftext.charCodeAt(i+1);
  312.                         c3 = utftext.charCodeAt(i+2);
  313.                         string += String.fromCharCode(((& 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  314.                         i += 3;
  315.                     }
  316.                 }
  317.                 return string;
  318.             }
  319.         };
  320.         // Format json object (modify required)
  321.         var JSONFormater = {
  322.             Description : "Format json object",
  323.             Controls : [
  324.                 {
  325.                     tagName : "select",
  326.                     id : "indentType",
  327.                     children : [
  328.                         {tagName : "option", value : "\t", selected : "selected", innerHTML : "indent with a tab character"},
  329.                         {tagName : "option", value : "  ", innerHTML : "indent with 2 spaces"},
  330.                         {tagName : "option", value : "   ", innerHTML : "indent with 3 spaces"},
  331.                         {tagName : "option", value : "    ", innerHTML : "indent with 4 spaces"},
  332.                         {tagName : "option", value : "        ", innerHTML : "indent with 8 spaces"}
  333.                     ]
  334.                 },
  335.                 {tagName : "input", type : "button", value : "Translate"}
  336.             ],
  337.             Output : "",
  338.             Translate : function() {
  339.                 var input = document.tform.inputData.value;
  340.                 if (input.length == 0) {
  341.                     alert("Empty source.");
  342.                     return;
  343.                 }
  344.                 try {
  345.                     eval("var temp = " + input + ";");
  346.                 } catch (e) {
  347.                     alert("Invalid JSON data.");
  348.                     return;
  349.                 }
  350.  
  351.                 JSONFormater.FormatNode(temp, true, 0)
  352.                 JSONFormater.ClearComma();
  353.                 document.tform.outputData.value = JSONFormater.Output;
  354.                 JSONFormater.Output = "";
  355.             },
  356.             HasMembers : function(node) {
  357.                 for (var m in node) return true;
  358.                 return false;
  359.             },
  360.             Append : function(str, lineSeparator, hasIndent, indentLevel){
  361.                 var indent = "";
  362.                 if(hasIndent && indentLevel > 0){
  363.                     var indentType = document.getElementById("indentType").value;
  364.                     while(indentLevel-- > 0) indent += indentType;
  365.                 }
  366.                 this.Output += indent + str + (lineSeparator ? "\r\n" : "");
  367.             },
  368.             ClearComma : function(){
  369.                 // clear unexcepted comma
  370.                 if(this.Output.lastIndexOf(",\r\n") == this.Output.length - 3)
  371.                     this.Output = this.Output.substring(0, this.Output.length -3) + "\r\n";
  372.             },
  373.             FormatNode : function(node, isValue, indentLevel){
  374.                 var i;
  375.                 if(node.constructor == Array){
  376.                     this.Append("[", true, !isValue, indentLevel);
  377.                      
  378.                     for(i in node){
  379.                         this.FormatNode(node[i], false, indentLevel + 1);
  380.                     }
  381.                      
  382.                     this.ClearComma();
  383.                     this.Append("]", true, true, indentLevel);
  384.                 }else if(this.HasMembers(node)){
  385.                     this.Append("{", true, !isValue, indentLevel);
  386.                      
  387.                     for(i in node){
  388.                         this.Append("\"" + i + "\" : ", false, true, indentLevel + 1);
  389.                         this.FormatNode(node[i], true, indentLevel + 1);
  390.                     }
  391.                      
  392.                     this.ClearComma();
  393.                     this.Append("},", true, true, indentLevel);
  394.                 }else if(node.constructor == String){
  395.                     this.Append("\"" + node + "\",", true, !isValue, indentLevel);
  396.                 }else{
  397.                     this.Append(node + ",", true, !isValue, indentLevel);
  398.                 }
  399.             }
  400.         };
  401.         // Srt file modifier
  402.         var SRTModifier = {
  403.             Description : "Modify time line of *.srt files.",
  404.             Controls : [
  405.                 {tagName : "input", type : "text", value : "0", id : "srtAdjustment"},
  406.                 {tagName : "input", type : "button", value : "Modify"}
  407.             ],
  408.             Modify : function(){
  409.                 var tick = parseInt(document.getElementById("srtAdjustment").value);
  410.                 if(isNaN(tick)){
  411.                     alert("Invalid parameter!");
  412.                     return;
  413.                 }
  414.                 var lines = document.tform.inputData.value.split(/\r?\n/);
  415.                 var output = "";
  416.                 var session = [];
  417.                 var index = 1;
  418.                 for(var i in lines){
  419.                     // trim
  420.                     lines[i] = lines[i].replace(/^\s+|\s+$/g, "");
  421.                     // start of subtitles
  422.                     if(lines[i].match(/^\d+$/)){
  423.                         if(session.length > 0){
  424.                             output += session.join("\r\n") + "\r\n\r\n";
  425.                             session = [];
  426.                         }
  427.                         // reindexing for appending or deleting
  428.                         session.push((index++).toString());
  429.                     }else if(lines[i].match(/\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+/)){
  430.                         var times = lines[i].split(/\s-->\s/);
  431.                         session.push(SRTModifier.AppendTick(times[0], tick) + " --" + "> " + SRTModifier.AppendTick(times[1], tick));
  432.                     }else{
  433.                         session.push(lines[i]);
  434.                     }
  435.                 }
  436.                 document.tform.outputData.value = output + session.join("\r\n");
  437.             },
  438.             AppendTick : function(time, tick){
  439.                 if(time.match(/\d+:\d+:\d+,\d+/)){
  440.                     var indicator = time.split(/[:,]/);
  441.                     indicator = this.ParseInt(indicator[0]) * 3600000 + this.ParseInt(indicator[1]) * 60000 + this.ParseInt(indicator[2]) * 1000 + this.ParseInt(indicator[3]);
  442.                     indicator += tick;
  443.                     // milisecond
  444.                     var output = "," + this.Format(indicator % 1000, 3);
  445.                     indicator = Math.floor(indicator / 1000);
  446.                     // second
  447.                     output = ":" + this.Format(indicator % 60, 2) + output;
  448.                     indicator = Math.floor(indicator / 60);
  449.                     // minute
  450.                     output = ":" + this.Format(indicator % 60, 2) + output;
  451.                     indicator = Math.floor(indicator / 60);
  452.                     // hour
  453.                     output = this.Format(indicator, 2) + output;
  454.                     return output;
  455.                 }else{
  456.                     return "";
  457.                 }
  458.             },
  459.             Format : function(num, size){
  460.                 var str = num.toString();
  461.                 while(str.length < size){
  462.                     str = "0" + str;
  463.                 }
  464.                 return str;
  465.             },
  466.             ParseInt : function(num){
  467.                 num = num.replace(/^0*([1-9]?\d?)$/,"$1");
  468.                 return num.length == 0 ? 0 : parseInt(num);
  469.             }
  470.         };
  471.         // NCR
  472.         var NCR = {
  473.             Description : "Numeric Character Reference",
  474.             Controls : [
  475.                 {tagName : "input", type : "button", value : "Translate"},
  476.                 {tagName : "input", type : "button", value : "Resotre"}
  477.             ],
  478.             Translate : function(){
  479.                 var input = document.tform.inputData.value.split("");
  480.                 for(var i = 0 ; i < input.length; i ++){
  481.                     input[i] = "&#x" + input[i].charCodeAt(0).toString(16) + ";";
  482.                 }
  483.                 document.tform.outputData.value = input.join("");
  484.             },
  485.             Resotre : function(){
  486.                 var input = document.tform.inputData.value;
  487.                 var output = [];
  488.                 var ncr = input.match(/&#x([\da-fA-F]+);/g);
  489.                 var code = false;
  490.                 for(var i = 0; i < ncr.length; i++){
  491.                     code = ncr[i].toString().replace(/&#x([\da-fA-F]+);/, "$1");
  492.                     output.push(String.fromCharCode(parseInt(code, 16)));
  493.                 }
  494.                 document.tform.outputData.value = output.join("");
  495.             }
  496.         };
  497.         // Convert Java Properties files
  498.         var JavaProperties = {
  499.             Description : "Translate Java properties file.",
  500.             Controls : [
  501.                 {tagName : "input", type : "button", value : "Translate"},
  502.                 {tagName : "input", type : "button", value : "Resotre"}
  503.             ],
  504.             Translate : function(){
  505.                 var lines = document.tform.inputData.value.split(/\r?\n/);
  506.                 var separator = -1, key = "", value = "";
  507.                 for(var i = 0 ; i < lines.length; i++){
  508.                     // comment
  509.                     if(lines[i].indexOf("#") == 0 || lines[i].indexOf("!") == 0){
  510.                         continue;
  511.                     }else{
  512.                         separator = lines[i].indexOf("=");
  513.                         if(separator == -1){
  514.                             // condition of no separator
  515.                             lines[i] = JavaProperties.Encode(lines[i]);
  516.                         }else{
  517.                             name = lines[i].substring(0, separator).replace(/^\s+|\s+$/g, "");
  518.                             value = lines[i].substring(separator + 1, lines[i].length);
  519.                             value = JavaProperties.Encode(value);
  520.                             lines[i] = name + "=" + value;
  521.                         }
  522.                     }
  523.                 }
  524.                 document.tform.outputData.value = lines.join("\r\n");
  525.             },
  526.             Resotre : function(){
  527.                 var input = document.tform.inputData.value;
  528.                 var codes = input.match(/[\\]u([\da-fA-F]{4})/g);
  529.                 var code = "";
  530.                 for(var i = 0; i < codes.length; i++){
  531.                     code = codes[i].toString().replace(/[\\]u([\da-fA-F]{4})/, "$1");
  532.                     input = input.replace(codes[i].toString(), String.fromCharCode(parseInt(code, 16)));
  533.                 }
  534.                 document.tform.outputData.value = input;
  535.  
  536.             },
  537.             Encode : function(s){
  538.                 var buffer = [];
  539.                 for(var i = 0 ; i < s.length; i++){
  540.                     buffer.push(s.charCodeAt(i) < 128 ? s.charAt(i) : ("\\u" + s.charCodeAt(i).toString(16)));
  541.                 }
  542.                 return buffer.join("");
  543.             }
  544.         };
  545.     </script>
  546. </head>
  547. <body onload="Translation.Load();">
  548.     <form name="tform" action="*">
  549.         <!-- Tabs -->
  550.         <div id="tagGroup">
  551.             <a onclick="Translation.ChangeTab(this,Blogger)" id="InitComponent">Blogger</a>
  552.             <a onclick="Translation.ChangeTab(this,JSONFormater)">Json Formater</a>
  553.             <a onclick="Translation.ChangeTab(this,UrlEncoder)">URL</a>
  554.             <a onclick="Translation.ChangeTab(this,Base64Encoder)">BASE64</a>
  555.             <a onclick="Translation.ChangeTab(this,NCR)">NCR</a>
  556.             <a onclick="Translation.ChangeTab(this,JavaProperties)">Java properties</a>
  557.             <a onclick="Translation.ChangeTab(this,SRTModifier)">SRT</a>
  558.         </div>
  559.         <!-- Input & output -->
  560.         <div><textarea name="inputData"></textarea></div>
  561.         <div><textarea name="outputData" style="background-color:lightgray;" readonly="true"></textarea></div>
  562.         <!-- Description & control action -->
  563.         <h4 id="header"><span id="funcDes">Description</span> <span id="spendTime"></span></h4>
  564.         <div id="actions">
  565.             <span id="controlPanel">
  566.                 <input type="button" value="control button" />
  567.             </span>
  568.             <input type="button" value="Copy" onclick="Translation.Copy();" />
  569.             <input type="button" value="Clear" onclick="Translation.Clear();" />
  570.         </div>
  571.     </form>
  572. </body>
  573. </html>
Trim() function
  1. function trim(s){
  2.     return s.replace(/^\s+|\s+$/g, "");
  3. }
HttpClinet 4.01
New version means new api~
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9.  
  10. import org.apache.http.Header;
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.client.ClientProtocolException;
  15. import org.apache.http.client.HttpClient;
  16. import org.apache.http.client.entity.UrlEncodedFormEntity;
  17. import org.apache.http.client.methods.HttpGet;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.client.methods.HttpRequestBase;
  20. import org.apache.http.impl.client.DefaultHttpClient;
  21. import org.apache.http.message.BasicNameValuePair;
  22.  
  23. public class NetClient {
  24.  
  25.     private HttpClient client;
  26.     private String encoding = "UTF-8";
  27.  
  28.     public NetClient() {
  29.         this.client = new DefaultHttpClient();
  30.     }
  31.  
  32.     private String getEncoding(Header header) {
  33.         if (header == null)
  34.             return null;
  35.  
  36.         Pattern p = Pattern.compile("charset=(\\S+)");
  37.         Matcher m = p.matcher(header.getValue());
  38.         if (m.find()) {
  39.             return m.group(1);
  40.         }
  41.         return null;
  42.     }
  43.  
  44.     private String request(HttpRequestBase request) throws ClientProtocolException, IOException {
  45.         StringBuilder sb = new StringBuilder();
  46.         HttpResponse response = this.client.execute(request);
  47.         HttpEntity entity = response.getEntity();
  48.         if (entity != null) {
  49.             Header[] hds = response.getHeaders("Content-Type");
  50.             Header contentType = hds.length > 0 ? hds[0] : null;
  51.             String enc = this.getEncoding(contentType);
  52.  
  53.             InputStream is = entity.getContent();
  54.             InputStreamReader isr = new InputStreamReader(is, enc == null ? this.encoding : enc);
  55.             BufferedReader reader = new BufferedReader(isr);
  56.  
  57.             String line = null;
  58.             while ((line = reader.readLine()) != null) {
  59.                 sb.append(line).append(System.getProperty("line.separator"));
  60.             }
  61.  
  62.             reader.close();
  63.             isr.close();
  64.             is.close();
  65.         }
  66.         return sb.toString();
  67.     }
  68.  
  69.     public String get(String url) throws ClientProtocolException, IOException {
  70.         HttpGet request = new HttpGet(url);
  71.         return this.request(request);
  72.     }
  73.  
  74.     public String post(String url, List<NameValuePair> queryParams) throws ClientProtocolException, IOException {
  75.         HttpPost request = new HttpPost(url);
  76.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(queryParams, "UTF-8");
  77.         request.setEntity(entity);
  78.         return this.request(request);
  79.     }
  80.  
  81.     public void setEncoding(String enc) {
  82.         this.encoding = enc;
  83.     }
  84.  
  85.     public String getEncoding() {
  86.         return this.encoding;
  87.     }
  88.  
  89.     public static void main(String[] args) throws ClientProtocolException, IOException {
  90.         // TODO Auto-generated method stub
  91.  
  92.         NetClient nc = new NetClient();
  93.  
  94.         // String source = nc.get("http://localhost:8080/WebApp/PrintAll?a=bbb");
  95.  
  96.         List<NameValuePair> params = new ArrayList<NameValuePair>();
  97.         params.add(new BasicNameValuePair("page", "22"));
  98.         params.add(new BasicNameValuePair("action", "query"));
  99.  
  100.         String source = nc.post("http://localhost:8080/WebApp/PrintAll", params);
  101.  
  102.         System.out.println(source);
  103.     }
  104.  
  105. }
Library : http://hc.apache.org/httpcomponents-client-4.0.1/index.html