Tag: ssi

  • Spring IoC, DI quick tutorial

    There has been an (evident) craze amongst Java community with contrived terms such as IoC (Inversion of Control), DI (Dependency Injection) mainly through Spring. I initially found the connotation “Don’t call me, I’ll call you” a bit difficult (yeah, it’s bending your head upside down) to understand, but after spending few hours around Spring documentation, I get the gist.

    To a layman (Java layman, of course) it is helpful to picture that each Java program is a set of one or more classes, which act together. Essentially, this means classes are “dependent” on some classes in order to be fully functional. Usually, the class requiring functionality of another class instantiates the class, and uses it. This is called coupling because class instantiates the object of required class. What if we always got an “instantiated” instance of required class, and our class did not have to worry of instantiation? – This is called IoC (Inversion of Control) principle in Spring, and it achieves this by providing ready-to-use instance (injecting dependency) to your class. This has some important uses, since now you don’t worry of creating connections to databases, loggers to log4j, or sessions for JMS queues. Spring will create these for you, and your class can focus on the actual purpose – using the pre-instantiated ready-to-use object.

    Get it? OK, to simplify it further, let us assume you have a class A having one field – log. You want to use log to log information, but your class nowhere has the logic to instantiate or initialize log. You accept a pre-instantiated log through constructor, or getter/setter methods, and you will have a ready-to-use log instance passed to your class via Spring!

    I won’t go into details of Spring further, since Spring’s own documentation on http://static.springsource.org/spring/docs/2.5.x/reference/index.html is the definitive source to look into.

  • Whois purely in SSI

    It was fun learning SSI, and tweaking around to get useful information such as detecting your IP adddress, and further WHOIS information.

    See below in action

    http://www.naiksblog.info/ip2country.shtml

    Impressive how quickly a page could be constructed using SSI. Courtesy to Apache’s mod_include, IP to Country database, and APNIC references.

  • Extremely useful tips for Java

    1. A .java class can contain only one top-level public class.  All other top level classes in same .java file cannot be private or protected or public, only default (package-level access) is allowed.
    2. If no package is specified for class, it belongs to unnamed package – which cannot be imported.
    3. Unlike Linux utilities, long parameters or short parameters to java(c) need just a space before parameter value. e.g. -classpath <classpath> or -cp <classpath> are same. There is no -classpath=<classpath> syntax in java(c) command line.
    4. 8 primitive types (byte, short, int, long, float, double, char, boolean), special type void, and base type for all objects – java.lang.Object.
    5. null is not a keyword, type. It is a value.
    6. String objects created using short-hand String A= "a string";
      syntax creates Strings on pool in heap. A is pointer (32-bit to max. 64-bit) to a String object “a string” on heap memory allocated to your program. Using short-hand syntax to “a string” on String B= "a string"; will point to same string object on heap.
    7. Object gets garbage-collected, not it’s reference.
    8. Garbage collection is indeterminate. You cannot guarantee freeing of memory by forcing System.gc()
    9. finalize method is invoked only once before being removed from memory. Always call super.finalize() if you override it.
    10. Parameters (primitive, references) are always passed-by-value. There is no pass-by-reference in Java. The references passed can be used to modify the object the reference points, but not the reference itself is not modified.
    11. Return values from function are also passed by value, never by reference.
    12. Compound operators (+=, -=, *= etc) automatically cast. Compiler never throws any error on data mismatch.
    13. & (and) results in 1 if both are 1, | (or) results in 0 if both are 0, ^ (xor) results in 1 if either operand is 1
    14. char supports increment, decrement operators.
    15. The default isequal() implementation of Object tests for reference equality, which is same as ==.
    16. When using operators, Java automatically promotes values to int or higher. For values below int – byte, short – an explicit cast is required.
    17. extends comes first then implements
    18. Java tokenizes your source into separators (tab or space), keywords, operators, literals, identifiers (variable names).
    19. new zeroes Object’s fields (instance variables), hence explicit initialization can be skipped.
    20. import static allows importing static variables like System.out into your program. Hence, you can simply use out without prefixing it with class name System.
    21. local variables must be initialized before using. Though method parameters are local variables too, since methods are called with parameters, they are initialized.
    22. arrays are fixed size data structures, where as collections are dynamically sized data structures.
    23. For multidimensional arrays, it is easier to imagine the first dimension as a single row containing the other dimensions.
    24. Array initialization always requires dimension to be provided when initializing through new (caught at compile time). If using array initializer, you can specify {} empty braces, but accessing any index at runtime will only result in index out of bounds exception.
    25. There is always a default constructor – empty body – available for your class only if you do not declare any constructor.
    26. super, this must be the first line in constructor. this() or super() both cannot be placed.
    27. Parent class constructor super() is always called. For this reason, you need to have an empty constructor always in parent class.
    28. Method signature is composed of method name and parameters. Modifiers, return type, exception list has nothing to do with it. Access-specifiers however control visibility.
    29. Javabean properties are get-, set- methods provided over a field in Javabean style.
    30. Variable length parameters always come at the end of the list, and they can be empty (meaning nothing was passed). Being at end of the list automatically implies that only variable length parameters is allowed. (Java 5.0)
    31. Overloading means providing different method signatures in same or inheriting class. Overriding means providing same return type, method signature in inheriting class.
    32. Covariant return types means overriding method returns a subclass of return type in parent class. (Java 5.0)
    33. Method hiding means overriding of static methods.
    34. Abstract method has no body. Interface methods are all abstract, while Abstract class can contain zero or more abstract methods.
    35. All abstract method of Interface are public, it’s fields are public, static and final. No static methods are allowed.
    36. Abstract method compiles with static modifier, but generates runtime error if directly accessed. If abstract static method is overridden in child class, child class works fine.
    37. Enum constructors are invoked for each element.
    38. Anonymous inner class can have only one instance. Local inner class can have multiple instances.
    39. Static nested class is similar to any top-level class.
    40. Static fields in class always need default value; otherwise code does not compile.
    41. false is boolean, 0 is not false, it is int zero
    42. switch…case does not allow case null, since a constant (and final) expression is required for case
    43. You can put break in default for switch
    44. enum classes can have main method
    45. for(;;) is a valid for-loop. It never finishes, since it is an infinite loop.
    46. In enhanced for loop, the variable used for iteration must be declared only in for loop, not outside it.
    47. Java complains if you have unreachable while loop code e.g while(false) is not allowed. However, contrarily if(false) is allowed!
    48. Variables declared inside do…while loop are not available in while to test for condition!
    49. It is a good idea to add labels to your loops to enhance readability
    50. Assertion is put in places in your code where you think it should be always true
    51. Though not a good design, but assertions do allow modification on variables while asserting them e.g. assert ++i
    52. try…catch – catch can never have an exception which is a subclass of previous catch clause. It throws compile error.
    53. Checked exceptions always derive from Exception, runtime exceptions derive from RuntimeException, errors derive from Error. Java enforces checked exceptions are either handled or thrown. For runtime, error there is no such rule, even if RuntimeException derives from Exception.
    54. try… must have either catch or finally atleast, otherwise compile gives error
  • https in 5 easy steps

    Simple 5 step guide to setting up https with your own self-signed certificate
    Prerequisites: Apache2, Ubuntu Server

    1. Generate local keypair
      /usr/bin/openssl genrsa -des3 -out {your domain name}.key 3072
    2. Create self-signed certificate
      /usr/bin/openssl req -new -key {your domain name}.key -x509 -out {your domain name}.crt

    3. Configure your host on port 443 to use the certificate
      <VirtualHost {your ip}:443>
      ...
      SSLEngine on
      SSLCertificateFile {path where certificate is}/{your domain name}.crt
      SSLCertificateKeyFile {path where key file is}/{your domain name}.key

      SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
      ...
      </VirtualHost>
    4. Optional: If you do not want to enter key password each you restart Apache, you can embed the password in key itself.
      /usr/bin/openssl rsa -in
      {path where key file is}/{your domain name}.key -out {path where key file is}/{your domain name}.key.nopass
      Remember to update your Apache configuration to use the new file
      # SSLCertificateKeyFile {path where key fileis}/{your domain name}.key
      SSLCertificateKeyFile {path where key file is}/{your domain name}.key.nopass
    5. That’s it view it. Restart your apache to load the new configuration. And try accessing your url with https://

    If you receive a certificate warning, simply accept it, and proceed. Congratulations, your communication is now encrypted, and safe from prying eyes!

    Self-signed certificate

  • Got my bike license – 大型二輪免許を一発合格しました

    Hurray ! I received my bike license today in Japan ! In my first attempt itself ! Wish me congratulations !

    Bike license in Japan
    My bike license in Japan

    Ok some background – I had a bike license from my country. I had not converted it to International License, so I had to opt only for conversion into Japanese license – 外国免許切り替え. I do have a car license obtained in Japan, so I was exempted from written test (which by the way is too difficult, trust me). Instead, I simply had to appear an actual driving test (which is again difficult, mind you). I was required to produce a translated copy of my original license from my country, which can be done in 30 mins in JAF offices. Rest are your passport (both old, new ones), an application form, few stamps which you can buy right there. I live in Tsukuba, so I had to goto Ibaragi License Center, which is situated in Mito. You can go during weekdays, from 09:00AM. Believe me, you better arrive early. There is plenty of crowd, for all sorts of licenses, and usually you have to spend almost whole day there, in case you pass the test and obtain the license. I spent close fo 6 hours today, but in the end I was a happy guy.

    Once they receive your application, they ask you few questions about your original license – How did you obtain it? Where did you practice? What kind of test did you appear for this license? How many cc bike? Learner’s license? etc. Unless there are any problems, you are then handed over a course map, and timings when your test will start. Mind you, the course map is given so that you “memorize” it, period. You are required to drive the exact course map, observing lane rules, traffic signs, signal, right or left indication, speed or slow. The usual advice is that you have some 45 mins in hand before your test starts. Thus, you should actually take the course map in hand, and walk the entire course by foot atleast once. I did that, making a mental note of the lanes, the distance around which I should turn on the indicator, and so on – till I burnt the course map into my brain cells !

    The most difficult are – Ipponbashi, and Slalom – for me. And I did literally walk on foot imagining I was on bike before my test started.

    I believe I was the only one appearing a bike test today – why I was alone sitting in the waiting room till my turn came. The instructor was kind enough to walk me (verbally) through the course map once again. He also gave me a brief about the bike – Honda CB750 – and for my own safety, in case I should fall, had me wear elbow, knee, body protector before the test.

    When the actual test started, the instructor actually sits in a watchtower, from which he had a complete view of the course. Once he gave a go, I just drove the same path I had walked on foot earlier. I was particularly careful about slow down sign, lane change, and making sure that I move my head from left to right wide enough to show that I am taking visual confirmations before proceeding. At one point when making a turn I did step down, but I guess that was OK, because if I’d had done the same on Ipponbashi or Slalom, or even S-letter, or Crank, I am out without any further discussion. Phew, I did feel once the bike will stop during Crank, but I was lucky enough to make it till the final stop.

    In the end, the instructor appraised my driving skills, and gave me the golden word – “合格” !

  • ID ten T error

    I was having trouble with my computer.  So I called Richard, the 11-year-old next door whose bedroom looks like Mission Control, and asked him to come over.

    Richard clicked a couple of buttons and solved the problem.

    As he was walking away, I called after him, “So, what was wrong?”

    He replied, “It was an ID ten T error.”

    I didn’t want to appear stupid, but nonetheless inquired, “An, ID ten T error?  What’s that?  In case I need to fix it again.”

    Richard grinned. “Haven’t you ever heard of an ID ten T error before?”

    “No,” I replied.

    “Write it down,” he said, “and I think you’ll figure it out.”

    So I wrote it down: I D 1 0 T

  • Tired of teaching how to think

    Sir Ernest Rutherford, President of the Royal Academy, and recipient of the Nobel Prize in Physics, related the following story:

    “Some time ago I received a call from a colleague. He was about to give a student a zero for his answer to a physics question, while the student claimed a perfect score. The instructor and the student agreed to an impartial arbiter, and I was selected.

    I read the examination question: “Show how it is possible to determine the height of a tall building with the aid of a barometer.”

    The student had answered: “Take the barometer to the top of the building,attach a long rope to it, lower it to the street, and then bring it up, measuring the length of the rope. The length of the rope is the height of the building.”

    The student really had a strong case for full credit since he had really answered the question completely and correctly! On the other hand, if full credit were given, it could well contribute to a high grade in his physics course and certify competence in physics, but the answer did not confirm this. I suggested that the student have another try. I gave the student six minutes to answer the question with the warning that the answer should show some knowledge of physics.

    At the end of five minutes, he hadn’t written anything. I asked if he wished to give up, but he said he had many answers to this problem; he was just thinking of the best one. I excused myself for interrupting him and asked him to please go on. In the next minute, he dashed off his answer, which read: “Take the barometer to the top of the building and lean over the edge of the roof. Drop the barometer, timing its fall with a stopwatch.

    Then, using the formula x=0.5*a*t^2, calculate the height of the building.”

    At this point, I asked my colleague if he would give up. He conceded, and gave the student almost full credit. While leaving my colleague’s office, I recalled that the student had said that he had other answers to the problem, so I asked him what they were.

    “Well,” said the student, “there are many ways of getting the height of a tall building with the aid of a barometer. For example, you could take the barometer out on a sunny day and measure the height of the barometer, the length of its shadow, and the length of the shadow of the building, and by the use of simple proportion, determine the height of the building.”

    “Fine,” I said, “and others?”

    “Yes,” said the student, “there is a very basic measurement method you will like. In this method, you take the barometer and begin to walk up the stairs. As you climb the stairs, you mark off the length of the barometer along the wall. You then count the number of marks, and his will give you the height of the building in barometer units.”

    “A very direct method.”

    “Of course. If you want a more sophisticated method, you can tie the barometer to the end of a string, swing it as a pendulum, and determine the value of g [gravity] at the street level and at the top of the building.

    From the difference between the two values of g, the height of the building, in principle, can be calculated.”

    “On this same tack, you could take the barometer to the top of the building, attach a long rope to it, lower it to just above the street, and then swing it as a pendulum. You could then calculate the height of the building by the period of the precession”.

    “Finally,” he concluded, “probably the best,” he said, “is to take the barometer to the basement and knock on the superintendent’s door. When the superintendent answers, you speak to him as follows: ‘Mr. Superintendent, here is a fine barometer. If you will tell me the height of the building, I will give you this barometer.”

    At this point, I asked the student if he really did not know the conventional answer to this question. He admitted that he did, but said that he was fed up with high school and college instructors trying to teach him how to think.

    The name of the student was…

    Neils Bohr

    The Nobel Prize winner in Physics 1922

  • How to manually uninstall Symantec Endpoint Protection client from Windows 2000, XP and 2003, 32-bit Editions

    Much recently to my dismay, I figured out that I cannot remove Symantec’s Endpoint Protection from my own laptop without administrator password. I do not own this password, and I do not want anybody other than me permitting me what to uninstall. Hence I went ahead for manual uninstall according to these instructions (from Symantec’s own site) below-

    How to manually uninstall Symantec Endpoint Protection client from Windows 2000, XP and 2003, 32-bit Editions.

    The instructions are crisp and clear. I could manually uninstall following each step of those instructions, but there is one big trouble. The instructions talk to removing over 100’s of registry keys, values which I believe is sheer impossible manually. Why didn’t Symantec simply provide a small tool which has all those instructions bundled in a simple click-n-go fashion?

    I have tried to create a small registry file which can automate the removal of registry entries Uninstall Registry entries for Symantec Endpoint Protection
    For all other manual deletion of files, it would be great to write a small AutoIt script compiled to an exe. Maybe sometime later…

  • Russian Peasant Multiplication

    Start by writing the two numbers to be multiplied at the head of two columns. Then they repeatedly divide the number in the left column by two (dropping any remainder) and double the number in the right column, writing the two new numbers immediately below their predecessors, until the number in the left column is one. Then they cross out all rows where the number in the left column is even, and add the remaining numbers in the right column, which is the desired product.

    For instance, the product eighteen times twenty-three is found like this.
    Russian Peasant Multiplication
    Programming Praxis: Russian Peasant Multiplication – The Daily WTF.

  • Eset Nod32 blocks Trusted zone IPs

    Last whole week I was stumbled by the fact that my home network with 3 PCs suddenly stopped working. None of them were able to “see” each other, except for a little while… strange.
    Technically (since it is easier to describe), A, B, C – my 3 computers – could reach each other, share files, host apache, download files without any extra configuration.
    Last week, however while using C’s http server from A suddenly stopped. Puzzled, I thought the machine might be overloaded, or something like this must be causing page to timeout, or apache must have hanged (does it?). But things seemed to be working OK on C, in fact top showed a load average below 1 ?
    Further puzzled, I tried pinging A to C, and vice-versa. It worked… but only for a while. Pinging after a while seemed to stop. Huh?
    Scourging over the Internet wasn’t easy for answer. Maybe my way of searching was wrong, but I did spent a good week trying to fish out the ping issue, then next to dig deeper to find that accessing C’s IP from outside (it already has a global ip; though dynamic, paired through dyndns to the world) worked. Now each of them – A, B, C – have no internal 192.168 ip’s, just public ip’s. What good are public ip’s if I have to access them from outside than just sitting home?
    Something was wrong.
    To cut short, I called the ISP, asked them if they have changed anything recently (well, I was using A, B, C sharing files for over 6 months now). My ISP reported that no such upgrade, or settings were done. Deeply mad about this situation, I chose to disable the firewall (Eset Nod32) on A, and then tryout the ping – which worked effortlessly to C, and back.
    What the hell! Why did Nod32 suddenly seem to block my own A, B, C from seeing each other? ARP Poisioning? I don’t know, only thing I know is that it shouldn’t block them. 🙂
    Well, atleast things are fine now. I’ve changed settings on Nod32 to Not block threat detected addresses henceforth.