SBT and Netbeans Terminal Emulator..

One of the new features that came bundled with Netbeans 6.9 is the terminal emulator. This provides a shell scripting interface for Netbeans users. This has been very useful especially with running build tools like maven from the terminal emulator without having to navigate out of the IDE.

To access this feature, go to ‘Window > Output > Terminal. For more on the Netbeans Terminal Emulator click here

SBT (simple build tool) appears to be one of the raves of the moment, it gradually has grown on me and i am using it in my current project which obviously is Scala based.

At the moment i do not know of any plugin for SBT on the Netbeans platform.

I Initially assumed that having successfully installed SBT on my computer that it would be easily accessible from the terminal emulator. But ‘Lo and Behold’ the Netbeans terminal emulator was not aware of SBT‘s location.

In order to get SBT running in the terminal emulator the following commands would be appropriate, especially for MAC or Unix based PCs and already have SBT running. If you don’t have SBT running already click here to set it up.



sudo echo "java -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx512M -Xss2M -jar /include/here/path/to/the/sbt-launcher.jar \"\$@\"" | sudo tee /usr/bin/sbt #please don't forget to change the /include/here/path/to/the/sbt-launcher.jar to the relevant path on your system that points to the sbt launcher jar file.

whoami # this would tell you the current user if you already know the name skip this

cd /usr/bin # navigate to the /usr/bin folder

sudo chown username sbt # change owner to the required username on sbt. Also remember to change the username here  to the relevant one on you want to use
or alternatively

sudo chmod u+x sbt # this will give the required operation permission to the user

After this has been done navigate back to your Netbeans IDE’s terminal emulator and type sbt to enjoy it’s goodness within the Netbeans IDE.

CIAO for now..

Scala and Lift Web Framework.. My 2 Cents.

This blog post will most likely appeal to Scala headed and Lift handed programmers, so if you don’t fall into this category… You have been warned ! :)

Scala is an acronym that stands for SCAlable LAnguage. It is a statically typed functional and object oriented programming language that runs on the Java Virtual machine (JVM) and the .NET common language runtime (CLR). It has this feel of a truly dynamically typed language but really it is not dynamically typed.

Scala on its functional side is a branch of the ML languages (example: Haskell), they are known to be strongly typed unlike their homoiconic and dynamically typed functional language counterpart like LISP or Dylan.

The main principle of Scala is that functional programming complements object oriented programming, despite the surface contradictions. Functional programming places her emphasis on immutable values and side effect free functions as opposed to object oriented programming which is all about state that is mutated in objects and methods that can modify state that are out of their scope. But combining these two paradigms in Scala has proven to be worthwhile. Scala makes it possible to create immutable objects and also apply OO goodness. In Scala, every value is an object and every function an object. (Wampler, D., 2008)

The core advantages of Scala are:
Scala is functional which helps to write lesser and more concise code making it easier to test and maintain.
• Because Scala is functional in nature it embraces a lot of mathematical concepts, which emphasise correctness from a logical point of view. This is very important and infact can help reduce bugs in the software system.
Scala introduces better ways of doing object oriented programming, in terms of composability (using mixins and traits) and scalable design.
Scala provides a better model and much more principled approached for dealing with concurrency issues. Scala provides an Actors library that is similar to the one in Erlang. Actors are nothing more than concurrent process actions that communicate by exchanging messages. Actors can also view as active objects, based on this a method call corresponds to sending a message. The Scala Actors can also do asynchronous and synchronous messaging.

Lift is a non-mvc web framework written in Scala. Lift‘s approach to web development, is coined “view first“. With this approach a component of web page is an instance of a Scala object, these are called snippets in Lift.

Snippets basically are bindings between the view and a function that could contain some business logic and primarily transforms input XML to output XML or put in another way renders dynamic or interactive feedback to the View Template. In the view any tag with the Lift namespace is a snippet(Pollak, 2010).

<lift:someclass.function/> #binding to a function
or
<lift:someclass/>  #binding to a render function... if defined will be displayed on page load by default.

They could be easily mistaken to be controllers (like i did :( ), but they are not.

So far it appears that Lift is elegant and has a productive sensation. I appreciate the fact that it does a lot of the plumbing for me, especially with regards to form rendering and security etc….

This is a web framework that i feel possesses elements of rhythm, tempo, melody, harmony, timbre, articulation, and dynamics. It leverages the power of Scala‘s xml and actors libraries also.

And because Lift is based on Scala, it is possible to play with legacy java code seamlessly and combine both functional and OO features like pattern matching, closures and high order functions etc.

Lift is one of the reasons why Scala is here to stay !

Almost all web applications i have been involved with have had varying numbers of web forms. Usually the state of these web forms are required to be maintained across instances.

This provides valuable information on the status quo and offers varying forms of feedback to users, hence it be referred to as a user friendly application.

Alright, enough chit chat, let’s look at some code. I have previously used this same use case while introducing my self to other web frameworks, but found it to be more intriguing with Lift.

In the following example, I use a simple video rental form application to highlight some of Lift’s features. Hopefully you got maven and Git installed, You can find the full source for this example here on Github and also a working example here.

The Web.xml has got very little mark up in it that points to the LiftFilter class and defines the URL pattern.


<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<filter>
  <filter-name>LiftFilter</filter-name>
  <display-name>Lift Filter</display-name>
  <description>The Filter that intercepts lift calls</description>
  <filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>
 <!--  <init-param>
<param-name>bootloader</param-name>
<param-value>path to my custom Boot class</param-value>
</init-param>  -->

<filter-mapping>
  <filter-name>LiftFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

All lift application must have a Boot class. This is basically an expressive configuration class where lift allows you to define Rules that modify lift’s environment. Lift also allows defining a custom Boot instance using the init param tag, this custom Boot class must extend Bootable class and provide implementation for the boot method. The boot method can run only once.

class Boot {
  def boot {

    // where to search snippet
    LiftRules.addToPackages("com.liftforms")

    // Build SiteMap
    val entries = Menu(Loc("Home", List("index"), "Home", Hidden)) ::
		  Menu(Loc("View", List("view"), "View", Hidden)) :: Nil

    // Setting the sitemap
    LiftRules.setSiteMap(SiteMap(entries: _*))

  }
}

The LiftRules.addToPackages methods tells lift where to find snippets. By default you will get this code for free with the maven Lift archetype. URLs in Lift are pretty, the Menu/setSiteMap methods allows your to define meaningful urls for web pages and more.

The snippet class below extends the StatefulSnippet trait. This trait is used to maintain state of the form variables. Lift does not require using HTML tags for form elements directly, instead Lift provides generator functions on net.liftweb.http.SHtml. This allows Lift to set up all of the internal plumbing which kept my code relatively simple to read and separate from the view.

Below is example code for the forms class “RentingForm.scala”. Notice that is extends StatefulSnippet to help it manage state and the “class” -> “required” is used to meet the criteria for the jquery client side validation library. For more on this click here.

class RentingForm extends StatefulSnippet { // RentingForm snippet extending StatefulSnippet
  var dispatch: DispatchIt = {
    case "rent" => rentForm _ // call rentForm function
  }
  var (name, address, email, movieType, dateOfHire, numberOfDays, discount) = ("", "", "", "", "", "", "") // Tuple of form variables
  val movieSeq = Seq("" -> "Select Movie Type", "Sci-fi" -> "Sci-fi", "Horror" -> "Horror", "Comedy" -> "Comedy", "Suspense" -> "Suspense", "Romance" -> "Romance") // Sequence of movie types
  val discountMap = Map("Regular Customer" -> "Regular Customer", "New Customer" -> "New Customer") // Map of customer types

// definition for rentForm
  def rentForm(xhtml: NodeSeq): NodeSeq = {
    dispatch = {
      case name if name != "" => showDetails _                  // call show details function if name is not equal to ""
    }

    val discounts = SHtml.radio(discountMap.keys.toList, Full("New Customer"), discount = _, "class" -> "required") // radio button

    val submitLabel = "Confirm"
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> SHtml.text(name, name = _, "class" -> "required"), // text field
      "address" -> SHtml.textarea(address, address = _, "rows" -> "5", "class" -> "required"), // text area
      "email" -> SHtml.text(email, email = _, "class" -> "required email"), // text field
      "movie" -> SHtml.select(movieSeq, Empty, movieType = _, "class" -> "required"), //  select options combo box
      "date" -> SHtml.text(dateOfHire, dateOfHire = _, "class" -> "required date", "id" -> "datePicker"), // text field
      "numberOfDays" -> SHtml.text(numberOfDays, numberOfDays = _, "class" -> "required"), // text field
      "regular" -> discounts(0), // radio buttons 0
      "new" -> discounts(1), // radio button 1
      "rtxt1" -> (discountMap.head.key), //radio button label 0
      "rtxt2" -> (discountMap.last.key), // radio button label 1
      "submit" -> SHtml.submit(submitLabel, () => {}, "id" -> "submit")) // submit button

  }
// definition for showDetails
  def showDetails(xhtml: NodeSeq): NodeSeq = {

    val submitLabel = "Edit"
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> Text(name), // plain text rendering form variable to template
      "address" -> Text(address), // plain text rendering form variable to template
      "email" -> Text(email), // plain text rendering form variable to template
      "movie" -> Text(movieType), // plain text rendering form variable to template
      "date" -> Text(dateOfHire), // plain text rendering form variable to template
      "numberOfDays" -> Text(numberOfDays), // plain text rendering form variable to template
      "regular" -> Text(discount), // plain text rendering form variable to template
      "new" -> Text(""), // plain text rendering "" to template
      "rtxt1" -> Text(""), // plain text rendering "" to template
      "rtxt2" -> Text(""), // plain text rendering "" to template
      "submit" -> SHtml.submit(submitLabel, () => S.mapSnippet("RentingForm.rent", editDetails _), "id" -> "submit")) // submit button

  }

// definition for editDetails
  def editDetails(xhtml: NodeSeq): NodeSeq = {
    val discounts = SHtml.radio(discountMap.keys.toList, Full(discount), discount = _, "class" -> "required") // radio button
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> SHtml.text(name, name = _, "class" -> "required"), // text field
      "address" -> SHtml.textarea(address, address = _, "rows" -> "5", "class" -> "required"), // text area
      "email" -> SHtml.text(email, email = _, "class" -> "required email"), // text field
      "movie" -> SHtml.select(movieSeq, Full(movieType), movieType = _, "class" -> "required"), // select option combo box
      "date" -> SHtml.text(dateOfHire, dateOfHire = _, "class" -> "required date", "id" -> "datePicker"), // text field
      "numberOfDays" -> SHtml.text(numberOfDays, numberOfDays = _, "class" -> "required"), // text field
      "regular" -> discounts(0), // radio button 0
      "new" -> discounts(1), // radio button 1
      "rtxt1" -> (discountMap.head.key),  // radio button label 0
      "rtxt2" -> (discountMap.last.key), // radio button label 1
      "submit" -> SHtml.submit("Save", () => S.redirectTo("/view", () => S.mapSnippet("RentingForm.rent", thankYou _)), "id" -> "submit")) // submit button

  }

// definition for thankYou
  def thankYou(xhtml: NodeSeq): NodeSeq = {
    Log.info(name, address, email, movieType, dateOfHire, numberOfDays, discount) // logging the form variables
// Binding Form fields and components to template
    bind("v", xhtml,
      "name" -> (name))
  }

}

Finally, the corresponding web page for the above snippet, also notice that is wrapped around the with the which points to the template file in the “templates-hidden” folder. For more on this click here.

<lift:surround with="default" at="content">

    <lift:RentingForm.rent form="POST" id="confirmform" class="cmxform">

            <fieldset>
                <legend>Video Hire Details</legend>

                <div>

                    <label for="name">Name:<span>*</span></label>

                    <v:name/>

                </div>
                <div>
                    <label for="address">Address:<span>*</span></label>

                    <v:address/>

                </div>
                <div>
                    <label for="email">Email:<span>*</span></label>
                    <v:email/>

                </div>
                <div>
                    <label for="movietype">Movie Type:<span>*</span></label>
                    <v:movie/>

                </div>
                <div>
                    <label for="dateOfHire">Date of Hire:<span>*</span></label>
                    <v:date/>
                    <span id="notify"> DD/MM/YYYY </span>
                </div>
                <div>
                    <label for="numberOfDays">Number Of Days:<span>*</span></label>
                    <v:numberOfDays/>
                </div>
                <div class="radio">
                    <fieldset>
                        <legend><span> Discount Rate:<span>*</span> </span></legend>

                        <div>
                              <v:regular/><label> <v:rtxt1/> </label>
                             <v:new/> <label> <v:rtxt2/> </label>

                            </div>

                    </fieldset>
                </div>
                <div id="btn">

                      <v:submit/>

                </div>
            </fieldset>
    </lift:RentingForm.rent>
</lift:surround>

For the full source code on this example:

 git clone git@github.com:kengimel/Lift_forms.git 

and also a working example here.

 

REFERENCE:
Odersky M. et al, 2008. Programming in Scala First Edition, Artima.
Pollak D, 2010 Scala Lift Off London, Q&A, Available at: http://skillsmatter.com/podcast/scala/scala-lift-off-david-pollak [Accessed November 2010.]
Wampler, D., 2008. Available at: http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i [Accessed January 2010.]

Automatic Re-Start Script for Tomcat

I noticed only recently that my remote tomcat instance has been frequently shutting down on it’s own. This turned out to be very annoying, having to restart tomcat manually almost twice a day.

I queried the web and consulted other resources to seek for possible solutions on how i could detect why my remote tomcat instance goes down and also to re-start it almost immediate.

I learnt from several articles, documentations on the web and also got useful tips from friends on how to solve this problem. The steps i applied to solving this problem i have included in this blog post and they are as follows:

First, create a folder and i named it servchk (or you give it any meaningful name you want). I created this folder under root (top-most) directory “/”. This folder contains a file which i named chksrv (ie services checker ).

/servchk/chksrv
mkdir servchk
cd servchk
nano chksrv

Copy and paste the following to chksrv:

# !/bin/bash
# Re-start Service - Automatically restart tomcat when it goes bonkers (down)

/bin/netstat -ln | /bin/grep ":8080 " | /usr/bin/wc -l | /bin/awk '{if ($1 == 0) system("/sbin/service tomcat6 start") }'

Control + O and hit the Return key or enter to save the file and then Control + X to exit nano. (you may choose to use any editor of your choice).

Next i set the permissions for the file. Do this while logged in as root (very important)

chmod 700 /servchk/chksrv

Following the above step, is setting up a crontab. The crontab verifies if the tomcat instance is still running, and if the tomcat instance is down it will restart it.


crontab -l > mycrontab
echo '* * * * * /servchk/chksrv > /dev/null 2>&1' >> mycrontab
crontab mycrontab

#  the above line  will add the following to your crontab:

#  type:
crontab -l
#  to verify the contents of your crontabs list.

Test the crontab is working by manually stopping tomcat.

service tomcat6 stop

Wait for a few seconds to a minute for tomcat to start again.

Setting Up SBT (Simple Build Tool) on Unix For Building Scala Based Project.

One of the problems that plagued the Java development space prior to the advent of tools like ANT and Maven, was the lack of automated build tools.

Previously, Java developers had to either write thier own build script which knew no unformity at all or do javac *.java (did this really work.. hmm).

But today setting up a Java project is gradually becoming a trivial task especially with tools like Maven and SBT.

SBT is a build tool for Scala based project. SBT integrates very well with Maven.

The feature of SBT, i like is the continuous compilation (~compile) this is very useful especially when testing and/or debugging.

Kudos to the hands behind SBT and Maciej Matyjas for recommending SBT to me..  you guys rock. period !

Alright, lets delve in and set up an SBT build environment.

Firstly, you need to download the latest jar of SBT here

Next create the bin folder and move the SBT jar to the bin folder.

mkdir ~/bin
mv ~/Downloads/sbt-launcher-0.7.4.jar ~/bin

Next create the SBT file.

echo "java -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx512M -Xss2M -jar \`dirname \$0\`/sbt-launcher-0.7.4.jar \"\$@\"" | sudo tee ~/bin/sbt

I prefer this way of using “dirname” rather that using a relative or absolute path to the SBT jar file.

After this is done you may need to  change the read write mode for the SBT file.

chmod u+x ~/bin/sbt

This allows you to launch SBT file to run or execute.

Finally, set environment path for SBT, this file name varies across flavours of Unix. I use a Mac OSX 10. 6 and i use .profile or .bash_profile to set my environment path.

For Debian this is .bashrc. Find out the file for setting environment variables for your flavour of Unix.

emacs .profile                              #(or nano .profile or any editor of your choice.. only have it in mind that these type of files are hidden system files)
export PATH=$PATH:~/bin                     #(copy and paste this in to .profile)
source .profile

This allows you to launch SBT from any directory by typing sbt at the terminal.

Type sbt on terminal to enjoy the it’s euphoria.

For more on SBT here

Persisting many to many Relationship (JPA and Spring Strategy)

This post is inspired by the “Netbeans Generate Entity Class From Database” feature which literally spits out vanilla JPA Entity classes for you while you have some coffee. For many to many relationship types Netbeans reads and generates an JPA Entity class for the join table and an extra class which holds the Primary key values for the two tables involved in a many to many relationship. This class is annotated with the @Embeddable JPA annotation. This i found very cool.

In this post i would like to show how to persist data from the respective tables to the join table.

The database create statement for the chosen table goes as follows:

create table Author (author_id int(10) not null auto_increment, name varchar(55) not null, email varchar(55) not null, primary key (author_id));
create table Book (book_id int(10) not null auto_increment, name varchar(55) not null, publisher varchar(55) not null, primary key (book_id));
create table Author_Book (author_id int(10) not null, book_id int(10) not null, primary key (author_id, book_id));
alter table Author_Book add index FKAuthor_Boo670752 (author_id), add constraint FKAuthor_Boo670752 foreign key (author_id) references Author (author_id);
alter table Author_Book add index FKAuthor_Boo981679 (book_id), add constraint FKAuthor_Boo981679 foreign key (book_id) references Book (book_id);

Netbeans generates the following for you.. No skin pain :)

Class Author Entity

@Entity
@Table(name = "Author")
@NamedQueries({
    @NamedQuery(name = "Author.findAll", query = "SELECT a FROM Author a"),
    @NamedQuery(name = "Author.findByAuthorId", query = "SELECT a FROM Author a WHERE a.authorId = :authorId"),
    @NamedQuery(name = "Author.findByName", query = "SELECT a FROM Author a WHERE a.name = :name"),
    @NamedQuery(name = "Author.findByEmail", query = "SELECT a FROM Author a WHERE a.email = :email")})
public class Author implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "author_id")
    private Integer authorId;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @Basic(optional = false)
    @Column(name = "email")
    private String email;

    public Author() {
    }

    public Author(Integer authorId) {
        this.authorId = authorId;
    }

    public Author(Integer authorId, String name, String email) {
        this.authorId = authorId;
        this.name = name;
        this.email = email;
    }

    public Integer getAuthorId() {
        return authorId;
    }

    public void setAuthorId(Integer authorId) {
        this.authorId = authorId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (authorId != null ? authorId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Author)) {
            return false;
        }
        Author other = (Author) object;
        if ((this.authorId == null && other.authorId != null) || (this.authorId != null && !this.authorId.equals(other.authorId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.Author[authorId=" + authorId + "]";
    }

}

Class For Book Entity..

@Entity
@Table(name = "Book")
@NamedQueries({
    @NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"),
    @NamedQuery(name = "Book.findByBookId", query = "SELECT b FROM Book b WHERE b.bookId = :bookId"),
    @NamedQuery(name = "Book.findByName", query = "SELECT b FROM Book b WHERE b.name = :name"),
    @NamedQuery(name = "Book.findByPublisher", query = "SELECT b FROM Book b WHERE b.publisher = :publisher")})
public class Book implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "book_id")
    private Integer bookId;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @Basic(optional = false)
    @Column(name = "publisher")
    private String publisher;

    public Book() {
    }

    public Book(Integer bookId) {
        this.bookId = bookId;
    }

    public Book(Integer bookId, String name, String publisher) {
        this.bookId = bookId;
        this.name = name;
        this.publisher = publisher;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (bookId != null ? bookId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Book)) {
            return false;
        }
        Book other = (Book) object;
        if ((this.bookId == null && other.bookId != null) || (this.bookId != null && !this.bookId.equals(other.bookId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.Book[bookId=" + bookId + "]";
    }

}

Class for the join Table Author_Book

@Entity
@Table(name = "Author_Book")
@NamedQueries({
    @NamedQuery(name = "AuthorBook.findAll", query = "SELECT a FROM AuthorBook a"),
    @NamedQuery(name = "AuthorBook.findByAuthorId", query = "SELECT a FROM AuthorBook a WHERE a.authorBookPK.authorId = :authorId"),
    @NamedQuery(name = "AuthorBook.findByBookId", query = "SELECT a FROM AuthorBook a WHERE a.authorBookPK.bookId = :bookId")})
public class AuthorBook implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected AuthorBookPK authorBookPK;

    public AuthorBook() {
    }

    public AuthorBook(AuthorBookPK authorBookPK) {
        this.authorBookPK = authorBookPK;
    }

    public AuthorBook(int authorId, int bookId) {
        this.authorBookPK = new AuthorBookPK(authorId, bookId);
    }

    public AuthorBookPK getAuthorBookPK() {
        return authorBookPK;
    }

    public void setAuthorBookPK(AuthorBookPK authorBookPK) {
        this.authorBookPK = authorBookPK;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (authorBookPK != null ? authorBookPK.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof AuthorBook)) {
            return false;
        }
        AuthorBook other = (AuthorBook) object;
        if ((this.authorBookPK == null && other.authorBookPK != null) || (this.authorBookPK != null && !this.authorBookPK.equals(other.authorBookPK))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.AuthorBook[authorBookPK=" + authorBookPK + "]";
    }

}

Below we have the class that holds the primary key values of the participating tables, also generated for you by netbeans:

@Embeddable
public class AuthorBookPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "author_id")
    private int authorId;
    @Basic(optional = false)
    @Column(name = "book_id")
    private int bookId;

    public AuthorBookPK() {
    }

    public AuthorBookPK(int authorId, int bookId) {
        this.authorId = authorId;
        this.bookId = bookId;
    }

    public int getAuthorId() {
        return authorId;
    }

    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) authorId;
        hash += (int) bookId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof AuthorBookPK)) {
            return false;
        }
        AuthorBookPK other = (AuthorBookPK) object;
        if (this.authorId != other.authorId) {
            return false;
        }
        if (this.bookId != other.bookId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.AuthorBookPK[authorId=" + authorId + ", bookId=" + bookId + "]";
    }

}

At this point in order to persist, we require a component, service and repository (DAO) objects to do this.
For the view component, what ever is your web framework of choice, be it jsf, spring mvc, gwt or wicket, etc all you need to do is inject the service and call the respective method for saving that you have defined in your service object. the below is based on JSF.

Note: at this point you need to persist both sides of the divide at the same time (the join table entity in this case AuthorBook and anyone of the participating sides). For the AuthorBook Entity you instantiate the constructor for the join table entity class that accepts the ids of the participating table (for this example this is achieved by passing to the constructor the get method for retrieving the ids for the participating tables for the join table.) Like this

authorBookService.save(new AuthorBook(book.getBookId(), author.getAuthorId())); 

The code for this goes as follows:

@Component
@Scope("request")
public class ComponentBean implements Serializable {

    private AuthorBook authorbook = new AuthorBook();
    private Author author = new Author();
    private Book book = new Book();
    private AuthorService authorSerivce;
    private AuthorBookService authorbookSerivce;

    @Autowired
    public ComponentBean(AuthorService authorSerivce, AuthorBookService authorbookSerivce) {
        this.authorSerivce = authorSerivce;
        this.authorbookSerivce = authorbookSerivce;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }
public void setAuthorbook(AuthorBook authorbook) {
        this.authorbook = authorbook;
    }
 public AuthorBook getAuthorbook() {
 return authorbook;
 }

 public void setBook(Book book) {
 this.book = book;
 }
public Book getBook() {
        return book;
    }
public void save(ActionEvent actionEvent) {
 authorService.save(author);
 authorBookService.save(new AuthorBook(book.getBookId(), author.getAuthorId())); // you instantiate the constructor for the join table entity  class and pass it the get method for retrieving the ids for the participating tables for the join table

 }
}

Service interface to define the the save operation:

public interface AuthorBookService {

public void save(AuthorBook authorBook);
}

Next the implementation for the AuthorBookService Service Interface:


@Service("authorBookService")
public AuthorBookServiceImpl implements AuthorBookService  {
private AuthorBookDAO authorbookdao;
@Autowired
public ModelServiceImpl(AuthorBookDAO authorbookdao) {
        this. authorbookdao = authorbookdao;
    }
    @Transactional
    public void save(AuthorBook authorBook) {
        authorbookdao.persist(AuthorBook authorBook);
    }
}

The Data Access object interface:

public interface AuthorBookDAO {

public void persist(AuthorBook authorBook);
}

The Data Access object implementation proper:

@Repository
public class AuthorBookDAOImpl implements ModelDAO {

    @PersistenceContext
    protected EntityManager entityMgr;

    public EntityManager getEntityMgr() {
        return entityMgr;
    }

    public void setEntityMgr(EntityManager entityMgr) {
        this.entityMgr = entityMgr;
    }

    public void persist(AuthorBook authorBook) {

      this.entityMgr.persist(authorBook)

    }
}

Note: the service and repository for Author and Book will follow the same pattern. See the my previous blog post for more hints.. Ciao for now..

Populating JSF Combo Box with Database values. (or drop down list)…

I am presently working on my AISD project, and i am using jsf(primefaces) spring and jpa to build the system. i would like to commend the efforts of the brains behind jsf 2.0 and primefaces (1.* and 2.*) :) in particular for making the life of java web devs much easier. I remember back in the days the first versions of jsf were simply nightmares, which lead my cohorts and i  to move to frameworks like wicket :) .

This blog post seeks to show how to populate a jsf Combo box with values from a database table and also you would notice that the implementation for this case includes both jsf 1.* and jsf 2.*. I assume some familiarity with spring jpa and jsf.

Most relational database records have a primary key to uniquely identify it. This key appears on other tables as foreign keys. In my application i needed to display one or more of the attributes of a record from a table on a form and persist its unique identifier .

Below i provide some sample code that gives some hint on how this can be achieved using plain old java objects..

First lets paint the screen.. For JSF 1.*:


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.myModelValues}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

For JSF 2.* this is even easier (thanks to Çağatay Çivici the primefaces lead for pointing this out to me :) ):


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.mlist}" var="model" itemLabel="#{model.modelvalue}" itemValue="#{model.modelId}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

Next lets define the backing page bean… For JSF 1.* this is ok :

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private Map<String, String> myModelValues = new HashMap<String, String>();
private List<Model> mList;
public PageBean(){
}

 @Autowired
public PageBean(ModelService modelService){
this. modelService = modelService;
        mList = modelService.findAll();
        for (Model m : mList) {
            myModelValues.put(m.getmyModelValue(), m.getmyModelId());
     }
}
public Map<String, String> getMyModelValues() {
return myModelValues;
    }
public void setMyModelValues(Map<String, String> myModelValues) {
this.myModelValues= myModelValues;
 }
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

For JSF 2.* it is even better => You don’t need  use a Map or Hash Map as the case may be above (thanks to Çağatay Çivici the primefaces lead for pointing this out ):

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private List<Model> list;
public PageBean(){
}

@Autowired
public PageBean(ModelService modelService){
        this. modelService = modelService;
        list = modelService.findAll();
}

public List<Model> getList() {
	return list;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

Below is a service interface to define the the findAll method:

public interface ModelService {

public List< Model> findAll();
}

Next the implementation for the Model Service Interface:


@Service("modelService")
public ModelServiceImpl implements ModelService  {
private ModelDAO modeldao;
@Autowired
public ModelServiceImpl(ModelDAO modeldao) {
        this. modeldao = modeldao;
    }
    @Transactional(readOnly = true)
    public List<Model> findAll() {
        return modeldao.findAll();
    }
}

The Data Access object interface:

public interface ModelDAO {

public List< Model> findAll();
}

The Data Access object implementation proper:

@Repository
public class ModelDAOImpl implements ModelDAO {

    @PersistenceContext
    protected EntityManager entityMgr;

    public EntityManager getEntityMgr() {
        return entityMgr;
    }

    public void setEntityMgr(EntityManager entityMgr) {
        this.entityMgr = entityMgr;
    }

    public List<Model> findAll() {
        Query query = entityMgr.createNamedQuery("Model.findAll");
        return query.getResultList();
    }
}

Finally lets define the jpa model object:

@Entity
@Table(name = "MODEL")
@NamedQuery(name = "Model.findAll", query = "SELECT m FROM Model m") // this query returns distinct values from the database.
public class Model implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "MODEL_ID")
    private String modelId;
    @Basic(optional = false)
    @Column(name = "MODEL_VALUE")
private String modelValue;
 public Model() {
    }
 public Model(String modelId, String modelValue) {
this.modelId = modelId;
this.model = modelValue;
}
 public String getModelId() {
        return modelId;
    }

    public void setModelId(String modelId) {
        this.modelId = modelId;
    }

    public String getModelValue() {
        return modelValue;
    }

    public void setModelValue(String modelValue) {
        this. modelValue = modelValue;
    }
    }

The code above steps through it all… Ciao for now..

Configuring Spring Security..

Over the years web application security has continued to be a critical issue. This area of concern is a major source of worry for most enterprise application developers. We as software developers, are faced with the task of securing valuable data that exist within our applications. This data could vary from  email account secured with a username / password pair or a brokerage account secured with a trading PIN, protecting an application is a important aspect of most applications, if not all.  (Walls C., 2007).

According to Craig Walls (2007, pg 248), Security is a concern that transcends an application’s functionality. For the most part, an application should play no part in securing itself. Although you could write security functionality directly into your application’s code (and that’s not uncommon), it is better to keep security concerns separate from application concerns.

One of the popular options for the enterprise java world is spring’s security framework (formerly Acegi).

Craigs Walls in his spring in action book defined spring security as  “a security framework that provides declarative security for your Spring-based applications.”

In this blog post, I intend to share my personal experience configuring spring security.

Firstly there are a few requirements (jars). you will need to define the following in your maven pom.xml file.

<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core-tiger</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-taglibs</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-acl</artifactId>
 <version>2.0.4</version>
 </dependency>
<dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.5.4</version>
 </dependency>

Next task is configuring the Web.xml file:


 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 classpath:applicationContext.xml
 </param-value>
 </context-param>

 <listener>
 <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class>

 </listener>

 <filter>
 <filter-name>springSecurityFilterChain</filter-name>
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
 <filter-name>springSecurityFilterChain</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

Every Spring application requires an applications context, this is a primary requirement of all spring based applications, this is a trimmed down version focusing on the topic of this blog post.

<?xml version="1.0" encoding="MacRoman"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
<context:component-scan base-package="com.example" />
<security:http auto-config='false'>
<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/login.jsp" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_USER" filters="none" />
<security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" />
<security:concurrent-session-control max-sessions="1"/>
<security:logout logout-url="/logout" logout-success-url="/"/>
</security:http>
<security:authentication-provider>
<security:password-encoder hash="md5" />
<security:user-service>
<security:user name="ikenna" password="3d801aa532c1cec3ee82d87a99fdf63f" authorities="ROLE_USER" />
<security:user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER" />
<security:user name="test" password="098f6bcd4621d373cade4e832627b4f6" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</beans>

Finally the login.jsp page. This page hold the form tags and should be placed in the root of the webapps foilder.

<%@page contentType="text/html" pageEncoding="MacRoman"%>
<%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt' %>
<%@ page import="org.springframework.security.ui.AbstractProcessingFilter" %>
<%@ page import="org.springframework.security.ui.webapp.AuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.AuthenticationException" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <title> Login Page</title>
 <link href="<c:url value="includes/stylesheets/main.css" />" media="screen"  rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/calendar.css" />" media="screen" rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/forms.css" />" media="screen" rel="Stylesheet" type="text/css" />
 </head>
 <body>
 <h1>Login </h1>
<c:if test="${not empty param.login_error}">
 <font color="red">
 Your login attempt was not successful, try again.<br/><br/>
 Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
 </font>
 </c:if><br><br>
 <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST">
 <fieldset>
 <legend>Log In Form</legend> <hr>
 <ol>
 <li><label for="login">Username:</label>
 <input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/>
 </li>
 <li>
 <label for="password">Password:</label>
 <input type='password' name='j_password'/>
 </li>
 <li>
 <label for="remember_me">Remember me:</label>
 <input type="checkbox" name="_spring_security_remember_me">
 </li>
 </ol>
 <div>
 <input name="reset" type="reset" value="Reset"  onclick="return confirm('Are you sure you want to Clear or Reset this form');">
 <input name="submit" type="submit" value="Log In">
 </div>
 </fieldset>
 </form
 </div>
</body>
</html>

One thing though, I struggled with is spring security not by passing the resources (*.js, *.css, and images etc..) declared the head section of my login.jsp file.

I noticed Spring security takes into account all the resources that are declared in the *.jsp pages and will atempt to display the last resource it remembered (declared in the login.jsp page).Also modern browsers request for the favicon.ico file from the web pages, I notice spring security required me to let it know that the resources should not be a priority to it.

I would suggest copying all your *.js, *.css, and images etc.. in to one folder (includes) and then declare the folder as IS_AUTHENTICATED_ANONYMOUSLY also setting the filters off.

<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />

REFERENCE:
Walls C., Breidenbach R. 2007. Spring in Action Second Edition, Manning Publishers.

The Higher Order Style.. (Functions)

These past days have been a revealing period, as i wondered into Scala land to behold it’s features that have made it such a hot topic….

My background in programming is largely imperative.. until earlier this year when i started  trying out some functional programming languages (Haskell, F#, Scala.. etc).

One feature of functional languages that i found very interesting were Higher Order Functions.

Higher order functions are notably a vital part, if not the most important part of functional languages.

A higher order function  accepts a function as a parameter or can return  a function back.

An example:

In an imperative language like JAVA looping through characters to find a lowercase value could be:


private boolean hasLowerCase = false;
for(int i = 0; i = title.length(); i++){
if (Character.isLowerCase(title.charAt(i))){
hasLowerCase = true;
break;
}
}

In Scala this can be achieve thus:

val hasLowerCase = title.exists(_.isLowerCase)
or
val hasLowerCase = title.exists(title => title.isLowerCase)

In Scala this is possible because Scala functions are values, this means you can take a function and explicitly set it to a variable.

val areaOfTriangle = (l:Int, b:Int) => l * b / 2
areaOfTriangle(2,3) = 3

This qualifies it to be passed as a parameter to another function.

Scala allows it’s users to define and use Higher order functions, this as shown makes code concise, putting to good use higher levels of abstractions, which to me is awesome:

In Scala playing or looping through Lists appears to be trivial as shown below:


List(3.5, 2.5, 1.5).map((a:Double) => a * 2)
or
List(3.5, 2.5, 1.5).map(a => a * 2)
or
List(3.5, 2.5, 1.5).map(_* 2)

Above the code multiplies the members of the List by 2.. The last two functions rely on the implicit typing capability of the Scala language. This makes the code even less noisy, gives us little to type and gives a similar feel of regular dynamic scripting language as the compiler does all the hard work of type inferencing.

Programming with higher order functions, like the map or exists function makes it;

  • Expressively clear, ease to grasp what the program does and the intention of the programmer.
  • Functions that accept Functions as arguments are more reusable than other functions.
  • Higher order function gives us the needed syntactic sugar to build big functionalites out of tiny bits of code.

Using the Wicket Framework to Update style tag.

In this post, Wicket Framework is used to update the embedded style tag.

An already working sample can be found here.

Let’s begin by configuring the web application (i.e. web.xml)


<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<display-name>CSS and Wicket</display-name>
<filter>
<filter-name>css_wicket</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>com.jw.ike.pages.CssApplication</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>css_wicket</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

 

The wicket application class go as follows:


public class CssApplication extends WebApplication {

public CssApplication() {
}

public Class getHomePage() {
return CssDemo.class;
}

}

The getHomePage() method returns this Page:

public class CssDemo extends WebPage implements Serializable {
	private String uStyle;

	public CssDemo() {
		add(new Label("style"));
		add(new CssForm("addform"));

	}

	public CssDemo(String userStyle) {
		this.uStyle = userStyle;
		this.add(new Label("style", new PropertyModel(this, "uStyle")));
add(new CssForm("addform"));

	}

}

And the accompanying HTML web page is:

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="../css/style/style.css">
<title>Wicket Updating Style Sheet</title>
<style type="text/css" wicket:id="style"></style>
</head>
<body>

<div id="bmain">
<form wicket:id="addform">
<h2>Update Style Sheet...</h2>

<span>Select Pre-Defined CSS Rules </span>

<select wicket:id="combo">

</select>

<textarea id="ta" wicket:id="txta" rows="20" cols="60"> rich text </textarea>

<input id="btn" type="submit" value="::Post Style Sheet::"></form>
<a href="http://wicket.apache.org/" >
<img id="logo" alt="Wicket" src="../images/wicket-logo.png" border="0" width='111' height="155"/></a>

</div>

<div id="side">

<h1>Change Me @!#%.</h1>

 </div>
</body>
</html>

And then the Form Class:


public class CssForm extends Form {

private String style1 = "Choose a style";
private String style2 = "h1{ font-size: 4.0em; font-family: Mistral; color: #dc512b; border:10px solid #bb342d; background-color: #098762;text-align: center;}";
private String style3 = "h1{ font-size: 5.0em; font-family: Comic Sans MS; color: #0066CC; border:10px solid #330066; background-color: green;text-align: center;}";
private String style4 = "h1{ font-size: 6.0em; font-family: Curlz MT; color: #CCFFFF; border:10px solid #445698; background-color: #6666CC;text-align: center;}";

private static String css;
private List cssList;
private String selectedCss = style1;
private DropDownChoice dropDownMenu;
private TextArea textArea;

public CssForm(String componentid) {
super(componentid);

cssList = Arrays.asList(new String[]{style1, style2, style3, style4});

dropDownMenu = new DropDownChoice("combo", new PropertyModel(this, "selectedCss"),
     cssList) {

 @Override
 protected void onSelectionChanged(Object newSelection) {

     textArea.setModelObject(newSelection);

 }

 @Override
 protected boolean wantOnSelectionChangedNotifications() {

     return true;
 }

};
add(dropDownMenu);

textArea = new TextArea("txta", new PropertyModel(this, "css"));

add(textArea);

}

@Override
protected void onSubmit() {
String definedCssRule =  textArea.getModelObject().toString();
definedCssRule = "\n\n\n" + definedCssRule + "\n\n\n";
setResponsePage(new CssDemo(definedCssRule));
textArea.setModelObject(null);
}
}

The External Style Sheet :


body {
	background-image: url("../images/cl.jpg");
	background-repeat: no-repeat;
}

h1 {
	font-size: 4.5em;
	color: #4088b8;
	margin: -300px 0 0 0;
	position: relative;
	left: -20px;
	top: 10px;
	position: relative
}

h2 {
	color: #4088b8;
}

span {
	font-size: 1.0em;
	color: #4088b8;
	padding:0 33px 0 2px;
}

#logo {
	position: relative;
	left: 0px;
	top: 50px;
	z-index: 1;
}
select {

	position: relative;
	left: 0px;
	bottom: 2px;
	width: 230px;
}

#jw {
	position: relative;
	left: 900px;
	top: -50px;
	z-index: 1;
}

#bmain {
	width: 510px;
	margin: 10px 0 0 0;
	position: inherit;
}

#side {
	float: right;
	width: 600px;
	margin: -150px 0 0 0;
	padding: 1px 0 0 0;
}

#ta {
	padding: 0 20px 0 0;
}

#btn {
	background-color: #4088b8;
	border-color: 4088b8;
	color: white;
	position: relative;
	left: 180px;
	top: 50px;
}