Saturday, November 27, 2010

How to include derby into WEB project

If you are working in Eclipse on a WEB project and your boss pushed you to work with derby, it is OK, but would take you some tricks to integrate the derby library properly.

As you have read in all tutorials, just install the plug in for your eclipse, unzip it and GO. BUT somehow your project cannot find the ClientDriver or EmbeddedDriver. Yeah, very confusing, because you probably have already included the libraries in the class path and made your project Derby Nature. Still does not work?

Since it is a web project and Derby is not in the standard distribution of the eclipse or Java IDE you need to include the libraries in the project. The best way to do so is to include all four jar files under the WEB-INF/lib directory.

Refresh your project, start again and voila, it works :)

Thursday, November 25, 2010

Basic way to create tables in SQL

connect to sampleDatabase;

-- the FinancialProduct entity
DROP TABLE FinancialProduct;
CREATE TABLE FinancialProduct (
pid INTEGER NOT NULL,
type VARCHAR(12),
PRIMARY KEY (pid),
CONSTRAINT typecheck CHECK (type IN ('creditLine', 'creditCard', 'personalLoan')));

--the Customer entity
DROP TABLE Customer;
CREATE TABLE Customer (
cid INTEGER NOT NULL,
income INTEGER,
expenses INTEGER,
DOB DATE,
phone# VARCHAR(12),
email VARCHAR(40),
PRIMARY KEY (cid));

--the Bank entity
DROP TABLE Bank;
CREATE TABLE Bank (
bid INTEGER NOT NULL,
address VARCHAR(50),
phone# VARCHAR(12),
PRIMARY KEY (bid));

--the Application entity
DROP TABLE Application;
CREATE TABLE Application (
serial# INTEGER NOT NULL,
type VARCHAR(12),
PRIMARY KEY (serial#),
CONSTRAINT typecheck CHECK (type IN ('creditLine', 'creditCard', 'personalLoan')));

--the Address entity
DROP TABLE Address;
CREATE TABLE Address (
cid INTEGER NOT NULL,
street VARCHAR(20) NOT NULL,
number INTEGER NOT NULL,
city VARCHAR(20) NOT NULL,
postalCode VARCHAR(6),
PRIMARY KEY (street, number, city),
FOREIGN KEY (cid) REFERENCES Customer (cid)
ON DELETE CASCADE);


--the Name entity
DROP TABLE Name;
CREATE TABLE Name (
cid INTEGER NOT NULL,
last VARCHAR(15) NOT NULL,
first VARCHAR(10),
mi VARCHAR (10),
PRIMARY KEY (last),
FOREIGN KEY (cid) REFERENCES Customer (cid)
ON DELETE CASCADE);

--the named relationship set
DROP TABLE named;
CREATE TABLE named (
cid INTEGER NOT NULL,
last VARCHAR(15) NOT NULL,
PRIMARY KEY (cid, last),
FOREIGN KEY (cid) REFERENCES Customer (cid),
FOREIGN KEY (last) REFERENCES Name (last)
ON DELETE CASCADE);

--the livesIn relationship set
DROP TABLE livesIn;
CREATE TABLE livesIn (
street VARCHAR(20) NOT NULL,
number INTEGER NOT NULL,
city VARCHAR(20) NOT NULL,
cid INTEGER NOT NULL,
PRIMARY KEY (cid, street, number, city),
FOREIGN KEY (street, number, city) REFERENCES Address (street, number, city),
FOREIGN KEY (cid) REFERENCES Customer (cid)
ON DELETE CASCADE);

--the receives relationship set
DROP TABLE receives;
CREATE TABLE receives (
bid INTEGER NOT NULL,
serial# INTEGER NOT NULL,
date DATE,
PRIMARY KEY (bid, serial#),
FOREIGN KEY (bid) REFERENCES Bank (bid),
FOREIGN KEY (serial#) REFERENCES Application (serial#)
ON DELETE CASCADE);

--the submitsTo relationship set
DROP TABLE submitsApp;
CREATE TABLE submitsApp (
cid INTEGER NOT NULL,
bid INTEGER NOT NULL,
serial# INTEGER NOT NULL,
date DATE,
PRIMARY KEY (cid, bid, serial#),
FOREIGN KEY (cid) REFERENCES Customer (cid),
FOREIGN KEY (bid) REFERENCES Bank (bid),
FOREIGN KEY (serial#) REFERENCES Application (serial#)
ON DELETE CASCADE);

--the respondsTo relationship set
DROP TABLE respondsTo;
CREATE TABLE respondsTo (
cid INTEGER NOT NULL,
bid INTEGER NOT NULL,
serial# INTEGER NOT NULL,
date DATE,
conditions VARCHAR (30),
PRIMARY KEY (cid, bid, serial#),
FOREIGN KEY (cid) REFERENCES Customer (cid),
FOREIGN KEY (bid) REFERENCES Bank (bid),
FOREIGN KEY (serial#) REFERENCES Application (serial#)
ON DELETE CASCADE);

--the HAS relationship set
DROP TABLE HAS;
CREATE TABLE HAS (
pid INTEGER NOT NULL,
bid INTEGER NOT NULL,
serial# INTEGER NOT NULL,
cid INTEGER NOT NULL,
PRIMARY KEY (pid, bid, serial#, cid),
FOREIGN KEY (pid) REFERENCES FinancialProduct (pid),
FOREIGN KEY (bid) REFERENCES Bank (bid),
FOREIGN KEY (serial#) REFERENCES Application (serial#),
FOREIGN KEY (cid) REFERENCES Customer (cid)
ON DELETE CASCADE);

list tables;
connect reset;
terminate;

Wednesday, November 24, 2010

How to Build a Filter

If you want to add a filter to the webpage, this is a doFilter() function, which would get some information from the request an session, and then, if conditions are satisfied, then it will redirect to another page!


/**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  // place your code here
  

  //ServletContext context = config.getServletContext();
  HttpSession session = ((HttpServletRequest)request).getSession();
  ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart");
  Statistics stats;
  stats = (Statistics)session.getAttribute("statistic");
  if (stats == null)
  {
   System.out.println("stats is null");
   if (cart != null)
    stats = new Statistics(cart.getSize());
   else
    stats = new Statistics(0);
   session.setAttribute("statistic", stats);
  }
  else if ((stats.getItemsNumber() > 2) && (stats.getTimes() < 5))
  {
   stats.setLastTime(stats.getLastTime()+ 1);
   Random r = new Random();
   int  digit = r.nextInt(4);
   if (((digit % 4) == 0) && (stats.getLastTime() > 4))
   {
    System.out.println("stats is not null");
    HttpServletRequest req = ((HttpServletRequest)request);
    StringBuffer newURL =req.getRequestURL();
    stats.setTimes(stats.getTimes() + 1);
    stats.setItemsNumber(cart.getSize());
    stats.setLastTime(0);
    session.setAttribute("statistic", stats);
    session.setAttribute("address", newURL.toString());
   
    
    RequestDispatcher rd = req.getRequestDispatcher("/add.jspx");
    rd.forward(request, response);
    return;
    
   }
  }
  else
  {
   if (cart != null)
   {
    stats.setItemsNumber(cart.getSize());
    session.setAttribute("statistic", stats);
   }
  }
  
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }

Tuesday, November 16, 2010

How to add a JavaScript Library in Eclipse

it is very easy, but when you do not know it, it is sometimes very hard.
Following steps should be done:


  1. Download JavaScript Library whichever you wish
  2. Put it somewhere in the project folder, BUT NOT in the WEB-INF folder, better above, otherwise
    Eclipse and Tomcat would not recognize it
  3. Follow this path in Eclipse: 
    • Window -> Preferences -> JavaScript -> Include Path -> User Libraries -> New...
      1. Create there a new library with the name you wish
      2. Click on "Add .js file"
      3. Find your library in the project and add it
      4. Click OK
This is it, you are done!

Monday, November 15, 2010

Introducing JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of theJavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by, (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

How to sort with JavaScript


var sort_by = function(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}
// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));
// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
You can also display warnings and alert windows:
<a HREF="javascript:window.alert('Invincibility is in oneself, vulnerability is in the opponent')">hey</a>
Another issue is, that < or > sign cannot be displayed and need to be replaced with &lt; and &gt; respectively.