How to Write a Technical Blog - 2

Friday, October 24, 2008

So we discussed some questions which needs to be answered before starting a technical blog, in this section, we will see simple tips on how to plan a technical blog and sustain it in the long run and other tips to make the blog look more professional.

For those of you who may want to read this from the beginning please visit How to Write a Technical Blog - 1.

3. Planning a blog

Its very easy to get started and blog enthusiastically for the initial months, but then one may suddenly find themselves wanting if they run out of stream, to avoid such cases one should not only choose a subject which they are so passionate about, but also think two months down the line ALWAYS, blog ideas strike the mind at anytime, therefore its better to note them as a probable entry, in my experience once you work on a technical subject chances are that you will encounter many technical challenges on a day-to-day job which are most likely to add value to some techie in one or other way, therefore noting them down would easily make a valuable blog entry and also ensures that the particular blog idea never gets lost.

But too much of ideas and plans lead nowhere, therefore take the top five blog entries in the to do list, write about them, give 100% on each, upon completing a single post, add an entry in the list of next five blogs from the to-do list and so on, if this process is followed with discipline coupled with the thought process of blogging mentioned above, one may NEVER find it hard to write about, also you don't need to think out of box to blog, simple day-to-day technical problems can lead to an useful tip, for example in the past I was virtually struggling to switch from Mircosoft JVM to Sun JVM in Internet Explorer and every time I did that, I never took the steps on how I did that, but now that has become an useful post, serving as a good reference for me as well as others.

Other useful ideas....

4. Follow comments from readers Sometimes comments from readers also serves as an useful idea to blog about, at least for me, if there is something that readers need which you think would be useful on that particular subject, that becomes a probable future post, also respond to user's comments and queries for the valuable time they spent on posting a comment on your blog.

5. Have a Search Box One can easily add a search box in a blog and keep track of user queries through Google analytics or the adsense tool from which you can research on user queries like what they expect from your blog, the query pattern, etc, which may very well lead to a new idea if you had never thought about that in the past.

6. Be upto the point Unless your blog has some useful code, keep the explanation of concepts very simple, precise and concise.

7. Make the blog look professional Syntax highlight code, have a consistent font (Verdana or Arial is recommended by most), choose the best layout for the blog, in most vases white background is the most preferred one especially if you have lots of text content, use images/pictures sparingly (unless you must include it in the blog, avoid), always remember that the first impression is the best impression.

I want to keep this really simple, useful, effective and refreshing, hope you got some insights on how to write a technical blog, the following resources may be useful for technical bloggers or in general for blogging of any kind.

1. www.problogger.net - Useful tips for bloggers, discusses come finer aspects of blogging, can be applied to blogging of any kind.

2. ThinkingRock - GTD (Getting Things Done) software - A very useful tool recommended by one of my friend, a must have for part-time/professional bloggers to plan to get things done in time.

3. Online Syntax Highlighters - Sometimes if you post code, as most programming blogs have, syntax highlighting code will improve the readability of the post.

4. Online spell checking - The most important quality of a blog and at times easily ignored, spelling mistakes in general may affect the reputation of a blog, so use this tool and crosscheck before posting any entry, thanks to Amit for recommending this tool.

How to Write a Technical Blog - 1

Friday, October 17, 2008

So I have written more than 30 entries in this blog, just want to do a little introspection on what went right and some useful lessons learned in this journey of technical blogging, yes you guessed it right, I want to share some of my views on "How to write a technical blog" from my blogging experience. If you are planning to become a tech geek and want the world to get benefited out of it, the following tips may be useful. Although I don't want to start a thread on "How to blog", "How to write", etc as that's not the the purpose of this blog (other than writing about technical subjects), but I just want to share something about technical blogging, at least to keep me off from code for a few days.

1. Why should I (or should you) blog?
Simple question, but I answered it well before keying in my first entry, the sole purpose is to share some of my technical views to others, in addition it serves as an useful reference for me whenever I needed some code snippet references (sometimes you may forget what you coded in the long run) and also to share some tricky technical answers.

The secondary reasons include writing interesting and useful stuff, learn more about blog design, coding, etc. In short this blogging experience has been quite fruitful for me in that it refeshes my technical skills and inevitably motivates me to write a lot and learn more to sharpen my technical skills.

So make your technical objectives clear before starting a tech blog, you may be a database expert, or a C++ guru or a script kiddie, everything you share with a purpose could make a difference to others.

2. What to write?

I was often hitting the walls with this because merely starting a blog with a purpose doesn't answer all questions, one of the important, mind boggling and at times a teasing question you can ask yourself is "What to write ?". From my entries I often found that the following topics were highly effective and well received by readers. So the ideal topics for a technical blog would be

2. 1. Troubleshooting tips:

Look for problems which gave you a good run for your money and if you solved it by your own like I did for this after futile attempts with Google Search, then that would make an interesting and a highly effective entry, also think about technical problems which you encountered in the past for which you badly needed an online reference which may save hours of effort for readers, then that solution would really make a difference to your blog.

2.2 Write about your passionate subject/programming language

This may well be your trump card whereby you can show your technical expertise in what you know and can attract targeted audience with similar interests. Sometimes it may even become the niche of your blog indirectly as is the case for me where I mostly use python language for illustrating some technical concepts and it goes without saying that it has become my niche ,although this blog is not only about python language, but it connects the dots in my blog entries in one or other way.

2.3 Write what you learn/use in day to day work

Its most likely that what you learn/use in your day to day work would be helpful for others as well, for example write about interesting or useful commands, how to's, algorithms, etc, you may be surprised to see yourself as an active reader of such entries over a period of time as is the case with me.

2.4 Focus on diverse topics you know:

Unless you are an expert in an area, trying to write a more specific technical subject would be futile and hard to sustain in the long run and you can easily run out of stream if your passion fades over a period of time or your skills change to meet the demands of the industry (unless you are so passionate on a topic and already have lots to share about it). Keep it simple, what matters is the value a blog entry makes to the readers than your personal goals, and for this reason its better to share what you know/learn rather than what you are willing to know (personal goals).

In other words you need to be absolutely sure if you want to use your blog as a platform to learn something over the years to come, else focus on diverse topics.

2.5 Research to improve the length and breadth of your blog:

If you came across a useful tool which you want to share with, that would make an interesting section, if you learn a new language, that would make another section if you want to tell more about that, in general your diverse skill can be handy to write effective blogs at different times, as the saying goes "Learn something about everything and everything about something", the same applies to blogs as well "Blog something about everything (you know) and everything about something (your expertise or you want to know)". This would ensure that you have something to blog about always.

In the next concluding section we will see how to plan blog entries, how to write more professionally and effectively and other aspects of technical blogging.

Continued here.


Jython Inheritance: Extending Java classes from Jython

Monday, October 6, 2008

Today I was experimenting inheritance concepts in jython and java i.e extending a java class from a jython script. In my previous writing on jython, we explored how interface concepts works from jython to java, now we we will see how to inherit a java class from jython. Before diving in, let me refresh some fundamental concepts of the about Python and Java.

1. Python Supports multiple inheritance, i.e a python class can extend or inherit multiple python classes.
2. Java doesn't support multiple inheritance, one prime reason is to avoid "Diamond of Death".

Given this behavior, I was wondering how inheritance from jython to java would work, as obvious the design philosophy of jython should not violate fundamental OOPS design principles of java and jython respects that too as I learnt it the hard way trying to experiment the diamond to death problem.

Ok, we will first see how basic inheritance works from jython to java and multiple inheritance from jython to java (Curious to see what error it throws..)

In the below listing, we have three classes, BaseClass, javaClassA which extends BaseClass and jythonClass which extends javaClassA and see how inheritance works from jython to java.

Listing 1: BaseClass.java


//
// BaseClass.java
// Author: S.Prasanna
//

public class BaseClass {

public BaseClass() {}

public void baseClassMethod() {
System.out.println("I am the baseClassMethod of BaseClass");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Listing 2: javaClassA.java


//
// javaClassA.java
// Author: S.Prasanna
// javaClassA extends BaseClass
//

public class javaClassA extends BaseClass {

public javaClassA() {}

public void methodA() {
System.out.println("I am method A of javaClassA");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Listing 3: jythonClass.py


#
# Inheriting java classes from jython
# jythonClass.py
# Author: S.Prasanna
#

import javaClassA

class jythonClass(javaClassA):

def __init__(self):
print "This is jythonClass inheriting a java class"

if __name__ == "__main__":

jythonInstance = jythonClass()
jythonInstance.methodA()
jythonInstance.baseClassMethod()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Now if you compile the jython code, you will get the below output.

C:\>jython jythonClass.py
This is jythonClass inheriting a java class
I am method A of javaClassA
I am the baseClassMethod of BaseClass

The explanation is simple, the jythonClass extends javaClassA which inturn extends BaseClass and the jython instance calls the methods delegated to the inherited classes.

Now I tried to create a diamond to death scenario with another class javaClassB which also extends BaseClass and the jython class extends both javaClassA and javaClassB and tries to call the BaseClass method, as obvious the interpreter/compiler, whatever you call slaps with the error as you will see below.

Listing 4: javaClassB.java


//
// javaClassB.java
// Author: S.Prasanna
// javaClassB extends BaseClass
//

public class javaClassB extends BaseClass {

public javaClassB() {
}

public void methodB() {
System.out.println("I am method B of javaClassB");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

and the jythonClass.py modified above to extend both classes,


#
# Inheriting java classes from jython
# jythonClass.py
# Author: S.Prasanna
#

import javaClassA
import javaClassB

class jythonClass(javaClassA, javaClassB):

def __init__(self):
print "This is jythonClass inheriting a java class"

if __name__ == "__main__":

jythonInstance = jythonClass()
jythonInstance.methodA()
jythonInstance.methodB()
jythonInstance.baseClassMethod()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The compiler is smart and throws the error message.

C:\Prasanna\myblogs\prasannatech.net\entries\jython_inheritance>jython jythonClass.py
Traceback (innermost last):
File "jythonClass.py", line 10, in ?
TypeError: no multiple inheritance for Java classes: javaClassB and javaClassA

The lesson learned is even though python supports multiple inheritance, once it comes to JVM, it should not violate any fundamental java principles. The last experiment I did is to write the javaClassB.java in jython, again the same error, but some more useful things can be inferred from the below code.

Listing 5: javaClassB.py


#
# javaClassB.py
# Author: S.Prasanna
#

import BaseClass

class javaClassB(BaseClass):

def __init__(self):
pass

def methodB():
print "I am method B of javaClassB"
1
2
3
4
5
6
7
8
9
10
11
12
13
14

and now the jythonClass tries to inherit javaClassA implemented in java and javaClassB implemented in jython.


#
# Inheriting java classes from jython
# jythonClass.py
# Author: S.Prasanna
#

import javaClassA
import javaClassB

class jythonClass(javaClassA, javaClassB.javaClassB):

def __init__(self):
print "This is jythonClass inheriting a java class"

if __name__ == "__main__":

jythonInstance = jythonClass()
jythonInstance.methodA()
jythonInstance.methodB()
jythonInstance.baseClassMethod()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The error message is little different here, but points to the same reason

C:\>jython jythonClass.py
Traceback (innermost last):
File "jythonClass.py", line 10, in ?
TypeError: no multiple inheritance for Java classes: org.python.proxies.javaClassB$javaClassB$0 and javaClassA

One more thing to note is that when you have two java classes with the same name with one implemented in java and the equivalent one in jython, any jython code which imports the java class will import the equivalent jython class module.

Enough of inheritance, the moral: when a scripting language is implemented in a different platform you need to live with that platform's design rules and jython developers had done a great job in this to impress both python as well as java users on a case by case basis.

Implementing a simple HTTP Server in Java to handle GET methods

Saturday, October 4, 2008

Implementing a simple HTTP Server in java using sockets is an useful application, which I thought would be worth sharing here. When I was implementing my own search engine, I always needed a light weight socket HTTP Server which I can bundle with my package and every time you need a HTTP/Web server, you need not to go for Apache Web Server which would be an overkill for simple applications which serves only static content, say a Google desktop search application where you just need a HTML user interface served through a simple HTTP Server.

In this HTTP Server we will see

1. How to process HTTP requests
2. How to handle HTTP GET methods
3. How to create multiple threads of control to handle each HTTP client

The below HTTP Server prints the client HTTP request in the home page, serves any valid files requested through GET method, otherwise prints a HTTP 404 page not found error message, lets look at the code and a simple explanation.


/*
* myHTTPServer.java
* Author: S.Prasanna
* @version 1.00
*/

import java.io.*;
import java.net.*;
import java.util.*;

public class myHTTPServer extends Thread {

static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";

static final String HTML_END =
"</body>" +
"</html>";

Socket connectedClient = null;
BufferedReader inFromClient = null;
DataOutputStream outToClient = null;


public myHTTPServer(Socket client) {
connectedClient = client;
}

public void run() {

try {

System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");

inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());

String requestString = inFromClient.readLine();
String headerLine = requestString;

StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();

StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");

System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}

if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
sendResponse(200, responseBuffer.toString(), false);
} else {
//This is interpreted as a file name
String fileName = httpQueryString.replaceFirst("/", "");
fileName = URLDecoder.decode(fileName);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
else {
sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
}
}
}
else sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
} catch (Exception e) {
e.printStackTrace();
}
}

public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {

String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;

if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "\r\n";
else
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";

if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
}

outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");

if (isFile) sendFile(fin, outToClient);
else outToClient.writeBytes(responseString);

outToClient.close();
}

public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
byte[] buffer = new byte[1024] ;
int bytesRead;

while ((bytesRead = fin.read(buffer)) != -1 ) {
out.write(buffer, 0, bytesRead);
}
fin.close();
}

public static void main (String args[]) throws Exception {

ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println ("TCPServer Waiting for client on port 5000");

while(true) {
Socket connected = Server.accept();
(new myHTTPServer(connected)).start();
}
}
}
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

Explanation:

The code is pretty simple, in main (lines 133 - 143), we accept new connections and invoke a thread on the newly created HTTPServer instance which will process the request.

In Line 53, while (inFromClient.ready()) loops till all HTTP request parameters are recieved, this means reading all lines in the input HTTP request are read, the ready function of BufferedReader tells whether the stream is ready to be read or not, therefore we process the HTTP request from the client till the stream is ready thereby ensuring that we get the complete request available for processing, including all request headers.

In Line 67, we use fileName = URLDecoder.decode(fileName) to decode the request GET method URL, most HTTP coding errors happen because the input HTTP request is not URLDecoded as a result we won't get the correct parameters to process, therefore one needs to URLDecode the input request string.

Other things are straightforward, we print the HTTP GET Request headers in the homepage, else the requested file is served, else a 404 Page not found error is output if the input GET request is not a valid file in the file system.

Output:

1. http://127.0.0.1:5000 should print the home page with the HTTP request parameters
2. http://127.0.0.1:5000/myHTTPServer.java would download the java source file, provided you run the java class file in the same location or try any other file in the filesystem by giving the absolute path, that would be downloaded.
3. http://127.0.0.1:5000/invalidfile would result in HTTP 404 file not found error.

We will see how to handle HTTP POST methods in future with an example of a file upload HTTP server.


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.