Wednesday, April 22, 2009

Design Patterns

Definitions on this blog came from the book Head First Design Patterns.

  • Strategy pattern - defines a family of algorithms, ancapsulate each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

  • From http://www.ida.liu.se

  • Observer pattern - defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
    - think Swing/GUI

  • From http://kur2003.if.itb.ac.id

    Using Java's built-in Observer pattern (allows observer to pull data from observable)...
    From http://kur2003.if.itb.ac.id


  • Decorator pattern - attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
    - think Java I/O

  • From http://oreilly.com



Ref:
Head First Design Patterns by By Eric Freeman, Elisabeth Robson, Kathy Sierra, and Bert Bates

Monday, April 13, 2009

Web Application Basics

HTTP - Hypertext Transfer (or Transport) Protocol), is a connectionless protocol for communicating clients/browsers and web servers

TCP/IP - Transmission Control Protocol, allows communication between your application software. It is responsible for breaking data down into IP packets before they are sent, and for assembling the packets when they arrive.
-connection oriented
-used to make connections and exchange information to one another
IP - Internet Protocol, is responsible for sending the packets to the correct destination
- connectionless

URL -Uniform Resource Locator, is a full specification of a resource. It includes the protocol, host machine name (domain name or IP address), optional protocol number and resource location.
Three ranges of port numbers:
  1. well-known ports - from 0 through 1023
    20 & 21: File Transfer Protocol (FTP)
    22: Secure Shell (SSH)
    23: Telnet remote login service
    25: Simple Mail Transfer Protocol (SMTP)
    53: Domain Name System (DNS) service
    80: Hypertext Transfer Protocol (HTTP) used in the World Wide Web
    110: Post Office Protocol (POP3)
    119: Network News Transfer Protocol (NNTP)
    143: Internet Message Access Protocol (IMAP)
    161: Simple Network Management Protocol (SNMP)
    194: Internet Relay Chat (IRC)
    443: HTTP Secure (HTTPS)
    465: SMTP Secure (SMTPS)
  2. the registered ports - from 1024 through 49151
    - they can be registered to specific protocols by software corporations/companies or users
    - assigned by or registered to Internet Assigned Numbers Authority (IANA) (or by Internet Corporation for Assigned Names and Numbers (ICANN) before March 21, 2001[1])
  3. dynamic or private ports - from 49152 through 65535
    - available for use by any application or just about anybody
HTML - is the principal language b/w the client and server that expresses content of webpages.



  • DOM - is an interface to the browser and HTML/XML documents.

  • DHTML
    Dynamic HTML is a term used to describe the combination of HTML, style sheets, and scripts that allow dynamic pages.

  • Javascript - is the most common scripting language for browsers.

  • Inversion of Control and Dependency Injection

  • Martin Fowler, who first coined Dependency Injection, considers it the same to Inversion of Control. He used Dependency Injection since he finds Inversion of Control too generic. However, other sources claim that Dependency Injection is just a form of Inversion of Control. With all the articles and blogs written about them, it is very easy to get confused. So I'll try to summarize their description here according to my own understanding and hopefully, it will be simple and easy to understand.

    Inversion of Control is a general principle in which the flow of control is inverted, unlike the traditional sequential flow. It follows the "Hollywood principle" - "don't call us, we'll call you". Your objects don't call services directly. Instead, your objects expect to be called. It is the framework that manages the objects and services, and is aware of what to instantiate and invoke.

    The main idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on.

    Dependency Injection is a way of implementing Inversion of Control in which an external mechanism is supplied in order for your objects not to call services (other objects) directly and therefore not depend on them. The external mechanism is the one responsible in injecting the concrete implementation that your objects needed.

  • Loose coupling - describes a relationship of two entities/objects where they can interact, but have very little knowledge of each other.


To r: inline css vs external css
What is robustness?
Disadvan of frames

Website-static
Webapp-dynamic

Get vs post- when to use get?

Session - uses cookies

Enabling technoligies:
Compiled modules-java servlets
Interpreted scripts-jsp

Monday, February 16, 2009

Other Pointers

  • Weblogic Erroneous Handlers Error - this is caused by the jrockit version of jdk. To get the correct error message, use the Java jdk first. Source: http://ricksolutions.blogspot.hk/2009/03/fixing-erroneous-handlers-error.html
  • checking tables on db2
  • select * from sysibm.systables where dbname='NACS01DB' and name like 'PC%'
  • command for unzipping war files
  • jar xvf xxx.war
  • Extracting the Contents a JAR File
    The basic command to use for extracting the contents of a JAR file is:
    jar xf jar-file [archived-file(s)] 
    Let's look at the options and arguments in this command:
    • The x option indicates that you want to extract files from the JAR archive.
    • The f options indicates that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
    • The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files.
    • archived-file(s) is an optional argument consisting of a space-delimited list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.
  • character encoding - http://www.joelonsoftware.com/articles/Unicode.html
  • DB2 Timestamp to java.util.Date or java.sql.Timestamp
    The ZZZZZZ part of DB2 timestamp is insignificant because it is just the total seconds since previos midnight.
    To convert to java.util.Date, use
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr)
    To convert to java.sql.Timestamp, use
    resultSet.getTimestamp([column name or column index])

Ref:
http://technobuz.com/2011/04/run-commands-for-microsoft-applications/

Java Pointers / Links

JSP Pointers

  • secure/nonsecure alerts on IE6 & 7
  • http://www.zorked.com/security/ie-mixed-content-secure-nonsecure-items/

  • no caching on browsers
  • add: (remove space b/w < and META)
      
    < META HTTP-EQUIV="Expires" CONTENT="0"> - any # less than 1 means no cache
    < META HTTP-EQUIV="Pragma" CONTENT="no-cache"> - for backward compatability
    < META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> - for HTTP 1.1 spec  

  • day in Date
  • function fnGetPrevDayDate(objDate){
     // 1 day = 86400000 ms 
     // var datPrevDate = new Date(objDate.getTime() - 86400000);
     // code above returns incorrect result when time changes from DST to standard time
     
     var datPrevDate = new Date(objDate);
     datPrevDate.setDate(datPrevDate.getDate() - 1);
     return datPrevDate;
    }

  • html:checkbox
  • -If the form is in session and you change the checkbox from true(checked) to false(unchecked), the checkbox attribute in form is not set back to false. This is because the unchecked checkbox is not sent in the request and is therefore not set in the form.
    -solution: Add a reset method in form & reset checkbox to false. Everytime you submit the form, form is reset and then populated before moving to action, thus having correct value for the checkbox.

  • how to use indexId on logic:iterate
  • < logic:iterate id="entityRow" name="<%= DerivativeEntityConstantsIF.SEARCH_RESULT %>" scope="session" offset="<%= String.valueOf(offset)%>" length="<%= String.valueOf(maxLength)%>" indexId="indexNum">
      < html:select name="entityRow" property="linkageClassCode"
    onchange='<%= "fnEditValue(this, " + indexNum + ")" %>' >...

  • html element default values - defaultValue/defaultSelectedd
  • if (frm["termDeal.accountNo"].value != frm["termDeal.accountNo"].defaultValue) return true;
    if (fnIsSelectChanged(frm["termDeal.currency"])) return true;
    
    function fnIsSelectChanged(selectObj) {
      var index = selectObj.selectedIndex;
      var selectedOption = selectObj.options[index];
      if (selectedOption.defaultSelected) return false; 
      return true;
    }

  • use popUpCalendar.js
  • if (!document.layers){
    var startDate = document.getElementById("personalInfoForm.dateOfBirth");
    // use showCalendarWithHolidays if you want to show holidays
    document.write("<[toRemove]a href='javascript:void(0)' onclick='showCalendarWithHolidays(this, startDate, \"mm-dd-yyyy\",null,1,-1,-1, true)'><[toRemove]img src='' border='0'/>");
    }

  • regex of replace
  • .value.replace(/_|-/g, '')  --> replace _ and - with empty str

  • use of sessionScope
  • CL.isNewClient = ${sessionScope[ClientConstants.IS_NEW_CLIENT]} --> do not put semi colon at end (not sure if for AMS only)

Deep copy of Java objects

The class Object's clone method only performs a shallow copy. This means that it creates a new instance of the object but the fields of both the new and original object end up referencing the same objects because only the reference of the fields is copied to the new object. To make deep copies of an object, we can use this class:

import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

/**
* Utility for making deep copies (vs. clone()'s shallow copies) of
* objects. Objects are first serialized and then deserialized. Error
* checking is fairly minimal in this implementation. If an object is
* encountered that cannot be serialized (or that references an object
* that cannot be serialized) an error is printed to System.err and
* null is returned. Depending on your specific application, it might
* make more sense to have copy(...) re-throw the exception.
*
* A later version of this class includes some minor optimizations.
*/
public class ObjectCloner {

// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner() {
}

/**
* Returns a copy of the object, or null if the object cannot
* be serialized.
*/
public static Object deepCopy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();

// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}

Sample call: Object clone = ObjectCloner.deepCopy(oldObject);
A more optimized version can be found here: http://javatechniques.com/blog/faster-deep-copies-of-java-objects/

Wednesday, February 11, 2009

NYAOS (NYACUS,NYADOS,NYAOS-II)

- Nihongo Yet Another Open Shell
- an enhanced commandline shell for Windows,DOS,OS/2
- advantages include filename autocomplete, built-in color, history, etc.
- support and downloads: http://nyaos.org/


1) Download and unzip
2) create env.bat with:
set MAVEN_HOME=S:\commons\apache-maven-2.0.10
set ANT_HOME=S:\commons\apache-ant-1.7.0
set JAVA_HOME=R:\commons\bea\jrockit_150_15
set path=%JAVA_HOME%\bin\;%MAVEN_HOME%\bin;%ANT_HOME%\bin;%PATH%;S:\commons\scripts;D:\Program Files\Rational\clearcase\ClearCase\bin;s:\commons\firefox
mvn -version
3) use nyacus as your cmd with the env properties by creating mycmd.bat with:
nyacus -r env.bat (means that you are loading the script file env.bat instead of _nya)
4) can start other apps by creating start command like eclipse.bat:
set path=R:\commons\bea\jrockit_150_15\bin\;%PATH%;
cmd /C start R:\commons\eclipse -data R:\bel\workspace\workspace33 -vmargs -Xms40m -Xmx512m -XX:MaxPermSize=256m
5) launch mycmd.bat
6) start other apps by calling filename of .cmd