Saturday, November 29, 2008

Java 2D Asteroids Part 6

Add the StationarySpaceObject.java class which really doesn't do anything. It is just a place holder.

StationarySpaceObject.java



public class StationarySpaceObject extends SpaceObjects
{


public StationarySpaceObject()
{

}


}


The SpaceMines.java object is a class that will be the space mines in the game.  This class contains the Affine Transform object that will be used to transform the points to the location of the object in the world.

SpaceMines.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.Random;


public class SpaceMines extends StationarySpaceObject implements Selectable,Drawable
{
private boolean selected;
private int ID;
private int pointValue;
private Random myRNG;
private double[][] curvePoint;
private boolean plasmaField;

private int xWidth;
private int yHeight;

private int blinkcounter;
private boolean remove;


public SpaceMines(int u,int r)
{
remove=false;
blinkcounter=0;
xWidth=u;
yHeight=r;
plasmaField=false;
curvePoint=new double[4][2];
selected=false;
myRNG=new Random();
int x5=myRNG.nextInt(3000);
int y5=myRNG.nextInt(3000);
setLocation(x5,y5);
setColor(new Color(100,100,255));
pointValue=10;

}


public boolean contains(int x, int y)
{

//AffineTransform inVerse
Point p=getLocation();
int x1=(int)p.getX();
int y1=(int)p.getY();

if(x>x1 && x<(x1+ 25)&&(y +25)>y1&&(y+ 25)<(y1+ 25))
return true;
else
return false;

}


public void setSelected(boolean newVal)
{
selected=newVal;

}

public void savePoint(double[][] point)
{
curvePoint=point;
plasmaField=true;
}


public double[][] returnPoint()
{
return curvePoint;
}


public boolean returnField()
{
return plasmaField;
}


public void setField(boolean a)
{
plasmaField=a;
}

public boolean isSelected()
{
return selected;

}//end isSelected Method


public void highlight()
{
setColor(new Color(255,100,0));

}

public void draw(Graphics2D g)
{
if(selected)
highlight();

Point pointx=getLocation();
int e=(int)pointx.getX();
int y=(int)pointx.getY();
int temp=(yHeight-y);
int w=temp;

g.setColor(getColor());

if(selected)
g.fill3DRect(e,w,25,25,true);
else
g.draw3DRect(e,w,25,25,true);

int n=12;
int[] x8=new int[n];
int[] y8=new int[n];

x8[0]=(e-5);
y8[0]=(w);
x8[1]=(e);
y8[1]=(w-5);
x8[2]=(e+ 25);
y8[2]=y8[1];
x8[3]=(e+ 30);
y8[3]=(w);
x8[4]=(e+ 25);
y8[4]=(w+ 14);
x8[5]=(e+ 30);
y8[5]=(w+ 25);
x8[6]=x8[3];
y8[6]=(w +25);
x8[7]=(e+ 25);
y8[7]=(w+ 30);
x8[8]=(e);
y8[8]=(w+ 30);
x8[9]=(e-5);
y8[9]=(w +25);
x8[10]=(e-5);
y8[10]=(w);
x8[11]=(e-5);
y8[11]=(w);

g.drawPolyline(x8,y8,n);
setColor(new Color(100,100,255));


}//end draw Method

public boolean remove()
{
return remove;
}

public void setRemove(boolean r)
{
remove=r;
}

public boolean blink(Graphics g)
{

Point pointx=getLocation();
int e=(int)pointx.getX();
int y=(int)pointx.getY();

int temp=(yHeight-y);
int w=temp;

int x5=myRNG.nextInt(255);
int x6=myRNG.nextInt(255);
int x7=myRNG.nextInt(255);
g.setColor(new Color(x5,x6,x7));
g.fillRoundRect(e,w,25,25,5,5);

blinkcounter++ ;

if(blinkcounter==10)
return true;
else
return false;

}

public void setID(int x)
{
ID=x;
}

public int returnValue()
{
return pointValue;
}


public int getID()
{
return ID;
}

public Point getBounds()
{
Point pt=new Point();
pt=getLocation();
double x=pt.getX();
double y=pt.getY();
y=(yHeight-y);
Point pt1=new Point();
pt1.setLocation(x,y);

return pt1;

}

public Point returnHW()
{
Point pt=new Point();
pt.setLocation(30,30);
return pt;
}

}




Go To Part 7

Read more...

Wednesday, November 26, 2008

Java 2D Asteroids Tutorial Part 5

This class is the space object class that will keep track of the space objects in the game. The only information it is keeping is the location and color of the object.

SpaceObjects.java


import java.awt.Color;
import java.awt.Point;


public class SpaceObjects
{
private Point point1;

private Color color;


public SpaceObjects()
{
point1=new Point();

}


public void setLocation(int x1,int y1)
{
point1.setLocation(x1,y1);

}



public Point getLocation()
{
return point1;
}


public void setColor(Color c)
{
color=c;
}


public Color getColor()
{
return color;
}



}



MovingSpaceObject.java

public class MovingSpaceObject extends SpaceObjects
{
private double heading;
private int speed;

public MovingSpaceObject()
{
heading=0;
speed=0;
}

public void setHeading(double h)
{
heading=h;

}


public void leftHeading()
{
heading =6;
if(heading>359)
heading=0;
}


public void rightHeading()
{
heading-=6;
if(heading < 0)
heading=359;

}


public void setSpeed(int s)
{
speed=s;

}


public void increaseSpeed()
{

if(speed!=200)
speed =8;

}


public void decreaseSpeed()
{

if(speed!=-200)
{

speed-=8;

}

}

public double getHeading()
{
return heading;
}



public int getSpeed()
{

return speed;
}
}


The MovingSpaceObject.java class keeps track of the information required for moving objects. You have two variables which is speed and heading. The heading will be a 360 degree number for a complete circle. It has two methods to allow the user to increase and decrease the speed of the object.
Go To Part 6

Read more...

Asteroids Java 2D Tutorial Part 4

We need some more interfaces for our game that you should create. The below interface will be used to know which objects are selectable.

Selectable.java



public interface Selectable
{


public boolean contains(int x, int y);


public void setSelected(boolean newVal);


public boolean isSelected();

}


The below interface is used for the objects that will be steerable.  This interface will allow you to change your speed and heading.

Steerable.java


public interface Steerable
{

public void changeSpeed(int amount);
public void changeHeading(int amount);

}


Go To Part 5

Read more...

Heritage Web Solutions


Are you looking to improve your website? Are you looking for a full custom website design that fits perfectly with your business? Well I have the answer for you. Heritage Web Solutions creates full custom website design which is not just copy-cat website design but a full, complete, custom, original and authentic design. There are many things that you need to consider when building a website. The website should be custom, original and something that will stand out compared to your competitors. You should get to the point on your website and not clutter your page with words. At Heritage Web Solutions, they will do all that for you. Their custom work starts at only $199. What a great investment to create a great look and feel for your business on the web. Heritage Web Solutions is on the top 25 of the Inc 500 list so this is a company that you can count on. You should visit their website and see a list of unique websites under their portfolio. They are pretty impressive. They can even create logos for you and they have examples on their website. This company is located in Provo, Utah and they started in November of 1999. They have around 225 employees with 300 independent contractors so this company isn’t small time. They service over 15,000 customers worldwide. So it doesn’t matter where you are located, you should checkout this company to help improve your website. They are also ranked in the top 1% of hosting companies as reported by “webhosting.info”. You can visit their website to get their phone number and you can also get a free quote on their website. They also have some good recognition articles on their website. If you are looking to redo your company’s website, this is the place you should go. Nobody will be able to do a better design then this company. You should check them out now.

Read more...

Asteroid Game in Java 2D Part 3

We need some more interfaces to move our objects.  This interface will be used for objects that will need to be moved within the game.

Move.java



public interface Move
{

public void move();
public void Prepare(float e);
public double getPositionX();
public double getPositionZ();
public void rotate();
public double getFuturePosX();
public double getFuturePosZ();

}
 

The below interface is another class that we will use to move objects.

Movable.java

public interface Moveable
{

public void move(int elapsedMilliSecs);

}


Go To Part 4

Read more...

Tuesday, November 25, 2008

Java 2D Tutorial Creating an Asteroid Game Part 2

We are going to need some interfaces for this game.  You should create 6 more classes for your interfaces.  They should be called Collider.java, Drawable.java, Move.java, Moveable.java,  Selectable.java, and Steerable.java.  


Collider.java

import java.awt.Point;


public interface Collider
{
public boolean bounds(Point p1,Point p2);
public void collision();
public boolean removeCollision();
}


The above interface will be used for an object that should implement the collision methods.

The below interface will be used for objects that need to be drawed on the screen.


Drawable.java

import java.awt.Graphics2D;




public interface Drawable
{

public void draw(Graphics2D g);

}

Go To Part 3

Read more...

Using Log4J with Hibernate Step 30

To help you debug your application, it is good to set up a log4j properties file so you can see the queries that hibernate is executing. This will help you to know if your hibernate mappings are correct.

In your build file, you need to include this line of code.
<classes dir="${CONFIG}/properties" />

You will put this code within your war file tag. This code will include your properties file when building your war file.

You should already have a folder called config, but if you don't, you should create one. In that folder you should create a folder called properties and in that folder you should create a file called log4j.properties.

Paste the following code in that file:

log4j.rootCategory=INFO, A1
log4j.category.org.hibernate.SQL=TRACE, A1
log4j.category.org.hibernate.type=TRACE, A1
log4j.categoty.org.apache.struts.tiles=INFO, A1
log4j.additivity.org.hibernate.SQL=false
log4j.additivity.org.hibernate.type=false
log4j.category.org.josso=INFO, A1
log4j.additivity.org.josso=false
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p [%x] - %m%n


This is an example log file. This code sets some hibernate logging parameters that will allow you to debug your hibernate issues.

Go To Step 31

Read more...

Display List from Database using Iterate Tag Step 29

You will also want to display the list of books that you have added to the database.

You should add this code to your addbook.jsp page.

<tr><td>
<b>Current Book List</b>
</td></tr>
<nested:iterate property="bookList">
<tr><td>
Book Name:<nested:write property="bookName"/>
</td></tr>

This will list the book names that you have saved to the database.

You should also add this code to your UserForm class. This is where you will store the book list that will be displayed in your JSP page.

private List bookList=null;

public List getBookList()
{
return bookList;
}
public void setBookList(List bookList)
{
this.bookList=bookList;
}

You will want to replace your addBook method with this code. This code will load your books from the database when the user first enters the JSP page.

UserBookService service = ServiceFactory.getInstance().getUserBookService();
List bookList=service.getBooks();
UserForm userForm=(UserForm)form;
userForm.setBookList(bookList);

System.out.println("in addBook");

return mapping.findForward("addbook");

Go To Step 30

Read more...

Monday, November 24, 2008

Create JSP Page with a Struts Select Box Step 28

The next step would be to create a page that will allow you to save a book to the database.

Add this code to your addbook.jsp page.


<%@ include file="include-taglibs.jspf" %>
<html:form action="/UserAction.do?action=saveBook" enctype="multipart/form-data" >
<br></br>
<table>
<tr><td>
<B>Add a Book</B>
</td></tr><tr><td>
Name of Book<html:text name="userForm" property="book"/>
</td></tr>
<tr><td>
Book Author<html:text name="userForm" property="author"/>
</td></tr>
<tr><td>
Name of Publisher<html:text name="userForm" property="bookPublisher"/>
</td></tr>
<tr><td>
Category<html:select name="userForm" property="categoryId">
<html:optionsCollection name="userForm" property="bookCategoryList" value="id" label="category" />
</html:select>
</td></tr>
<tr><td>
<input type="submit" value="Submit"/></td></tr>
</table>
</html:form>



This code has a text box for your book, bookAuthor, and bookPublisher. Those text boxes are attached to your form with the property attribute.

You also have a select box. We need to assign a book category to your book. The category is contained in another table and we need to establish the relationship between your book and the category it belongs too. You can attach an entire collection to the select box. The collection here is the category list that you already set in your form. You have a property for the list that will take the id from the category that is selected and put it into your form under the categoryId property. The label is the name of the category that the user will see since we don't want to display to them the categoryId. In older versions of struts, you would use the html:options tag to add a collection to the select box.

You now will need to add these methods to your UserForm.java class so your jsp page can set the property values.


private String book="";
private String author="";
private String bookPublisher="";
private String categoryId="";
public String getBook()
{
return this.book;
}
public void setBook(String book)
{
this.book=book;
}
public String getAuthor()
{
return this.author;
}
public void setAuthor(String author)
{
this.author=author;
}
public String getBookPublisher()
{
return this.bookPublisher;
}
public void setBookPublisher(String bookPublisher)
{
this.bookPublisher=bookPublisher;
}
public String getCategoryId()
{
return this.categoryId;
}
public void setCategoryId(String categoryId)
{
this.categoryId=categoryId;
}


When the user submits the form, they call the saveBook method. Therefore, you will need to add this method to your UserAction class.


public ActionForward saveBook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserForm userForm=(UserForm)form;
UserBookService service = ServiceFactory.getInstance().getUserBookService();
Book book=new Book();
book.setBookAuthor(userForm.getAuthor());
book.setBookName(userForm.getBook());
book.setBookPublisher(userForm.getBookPublisher());
Bookcategory cat=service.getOneBookCategory(new Long(userForm.getCategoryId()));
List bookList=cat.getBooks();
bookList.add(book);
service.save(cat);
book.setBookcategory(cat);
service.save(book);
userForm.getBookList().add(book);
return mapping.findForward("addbook");
}

This method sets the property values into a Book class and then saves the Book to the database. It saves the category first after setting the new book to prevent a org.hibernate.TransientObjectException. Since Book requires a Bookcategory.java object, we pull the category from the database and set that object in the Book.

You will need to add this method to your UserBookService.java class.
public Bookcategory getOneBookCategory(Long id);

You will need to add this method to your UserBookServiceImpl.java class.

public Bookcategory getOneBookCategory(Long id)
{
return dao.getOneBookCategory(id);
}

You will also need to add this method to your UserBookDAO.java class. This method will retrieve the Bookcategory object from the database based on the Id.

public Bookcategory getOneBookCategory(Long id)
{
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Bookcategory category=null;
try {
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
category=(Bookcategory)sessionFactory.getCurrentSession().get(Bookcategory.class,id);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (RuntimeException re) {
System.out.println("Error In Hibernate getBook"+re.toString());
throw re;
}
return category;
}

Go To Step 29

Read more...

Sunday, November 23, 2008

Beginning Java 2D Game Programming Part 1

I will be starting a Java programming tutorial showing you how you can create a 2D game using Java. The game we will be creating is Asteroids.

I am assuming in this tutorial that you have had some experience with programming.

You first will need Java 1.5 and Eclipse installed. See my first posts for installation instructions.
 
Create a project in your eclipse called Asteroids.

The first class we will create will be called Application and this class will be the class that you will use to create your game.

public class Application
{

public static void main(String[] args)
{
AsteroidGame game=new AsteroidGame();
game.createGame();


}//end main method


}//end application class

The word public means that any class has access to the class or methods. There is no security in place. If you use this class and something is public, then your other class can access it and change it. If the method or class is private, then nobody outside the class can access it. If the class is protected, then only classes, subclasses and members of other classes in the same package can access it. You usually will be setting a method or class as either private or public. Usually all variables in the class will be set to private. You want the user to access the variables by calling a method, which is set to public, in case you need to do some functionality before setting the variable. Every Java class has to have a main method when creating an application. This main method will be the first method that will be called and the only thing it does is creates the Asteroid Game object that will run the game.

Go To Part 2

Read more...

Friday, November 21, 2008

Display List in JSP using Iterate Tag Step 27

You will need to display the list of categories that you added to the database. You will want to use the iterate tag to accomplish this.

In the addcategory.jsp page, you will want to add this code before the closing form tag. This will iterate through the list of categories that you have in the database.

<b>Current Category List</b><br></br><nested:iterate property="bookCategoryList"><nested:write property="category"/></nested:iterate>

When you first come into your application, you will need to load your category list. Replace your addCategory method with this code in your action class:

public ActionForward addCategory(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserBookService service = ServiceFactory.getInstance().getUserBookService();
List categoryList=service.getBookCategory();
UserForm userForm=(UserForm)form;
userForm.setBookCategoryList(categoryList);
return mapping.findForward("addcategory");
}

When you save a new category, you will need to add it to your list. Replace your saveCategory method with this code:

public ActionForward saveCategory(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserForm userForm=(UserForm)form;
UserBookService service = ServiceFactory.getInstance().getUserBookService();
Bookcategory category=new Bookcategory();
String name=userForm.getCategory();
category.setCategory(name);
service.save(category);
List categoryList=userForm.getBookCategoryList();
categoryList.add(category);
return mapping.findForward("addcategory");
}

You will also need to add the methods to your form to hold the data. Add this code to your UserForm.

List categoryList;
public List getBookCategoryList()
{
return this. categoryList;
}
public void setBookCategoryList(List categoryList)
{
this.categoryList=categoryList;
}

When you view this page, you should see a list of your current categories displayed on your page.

Go To Step 28

Read more...

Thursday, November 20, 2008

Beginning JSP Page Struts Text Tag Step 26

Following my tutorial, this is a simple page to add a category to the database.


Replace your addcategory.jsp code with this page.
This page contains one text field that is attached to your form. When you submit your form, you will grap this category, create an object and save that object to the database.



<%@ include file="include-taglibs.jspf" %>


<html:form action="/UserAction.do?action=saveCategory" enctype="multipart/form-data" >
<br></br>
<table>
<tr><td>
<B>Add a Category</B>
</td></tr><tr><td>
Name of Book Category <html:text name="userForm" property="category"/>
</td></tr><tr><td>
<input type="submit" value="Submit"/></td></tr>
</table>
</html:form>



You will need to add this method to your UserAction class.
This method will retrieve the submitted information from the form and save it to the database.

public ActionForward saveCategory(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserForm userForm=(UserForm)form;
UserBookService service = ServiceFactory.getInstance().getUserBookService();
Bookcategory category=new Bookcategory();
String name=userForm.getCategory();
category.setCategory(name);
service.save(category);
return mapping.findForward("addcategory");
}

You will need to add this information to your form. When the jsp form is submitted, the category value will be set using these methods.

private String category="";
public void setCategory(String category)
{
this.category=category;
}
public String getCategory()
{
return this.category;
}

If your page doesn't show the text boxes or the list of categories, it might be because your addcategory.jsp page isn't including include-taglibs.jspf page that contains the tag libraries.

Go To Step 27

Read more...

Wednesday, November 19, 2008

Creating a User Interface with Struts Step 25

This post is about creating the flow of your User Interface. In the prior step, I showed you how to create a drop down menu for our application. In this post we will create the flow so we can start developing our JSP pages. We are going to add JSP functionality to add a user, to add a book, to add a book category, and to add a view a report.

First, create four JSP pages under your jsp folder called addbook.jsp, addcategory.jsp, adduser.jsp, viewreport.jsp. You should rename the user.jsp page to be called home.jsp. That will now become our home page. You can rename a page in eclipse by selecting refactoring. Select the right mouse button on the user.jsp page and select refactor and then select rename. Change the page to be called home.jsp. You can remove the prior code from that page too because we aren't going to need it anymore.

Replace your header with this code. I added the struts links in the menu so the user can move between the pages.



<!-- TJK_keyBoardDropDown.js is required so the menu works in Internet Explorer-->
<div style="z-index: 10000;" id="base"><!-- Begin Base div-->
<!-- Begin Page Level Navigation -->
<ul id="TJK_dropDownMenu">
<li diamondmenu="yes" class="trigger" id="AB"><a alt="admin" title="admin" href="#">Admin</a>
<ul>
<li diamondmenu="yes"><a href="UserAction.do?action=addUser" >Add User</a>
</li>
</ul>
</li>
<li diamondmenu="yes" class="trigger" id="CF"><a title="Books" href="#">Books</a>
<ul>
<li diamondmenu="yes"><a href="UserAction.do?action=addCategory">Add Category</a>
</li>
<li diamondmenu="yes"><a href="UserAction.do?action=addBook">Add Book</a>
</li>
</ul>
</li>
<li diamondmenu="yes" class="trigger" id="CF"><a title="Report" href="#">Reports</a>
<ul>
<li diamondmenu="yes"><a href="UserAction.do?action=viewReport">View Report</a>
</li>
</ul>
</li>
</ul>
</div>



In your struts.xml file, you need to replace the UserAction with the following code.
This code adds the actions for each item from the menu.


<action path="/UserAction" name="userForm" type="com.action.UserAction" parameter="action" scope="session">
<forward name="success" path="tile.userpage" />
<forward name="addbook" path="tile.addbook" />
<forward name="adduser" path="tile.adduser" />
<forward name="addcategory" path="tile.addcategory" />
<forward name="viewreport" path="tile.viewreport" />
</action>

In your tiles you need to add the following definitions (remove the original tile.userpage):


<definition name="tile.userpage" extends="mainLayout">
<put name="body" value="/WEB-INF/jsp/home.jsp"/>
</definition>
<definition name="tile.viewreport" extends="mainLayout">
<put name="body" value="/WEB-INF/jsp/viewreport.jsp"/>
</definition>
<definition name="tile.addcategory" extends="mainLayout">
<put name="body" value="/WEB-INF/jsp/addcategory.jsp"/>
</definition>
<definition name="tile.adduser" extends="mainLayout">
<put name="body" value="/WEB-INF/jsp/adduser.jsp"/>
</definition>
<definition name="tile.addbook" extends="mainLayout">
<put name="body" value="/WEB-INF/jsp/addbook.jsp"/>
</definition>



You will need to add the following to your action class:


public ActionForward addBook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in addBook");
return mapping.findForward("addbook");
}
public ActionForward viewReport(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in viewreport");
return mapping.findForward("viewreport");
}
public ActionForward addUser(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in addUser");
return mapping.findForward("adduser");
}
public ActionForward addCategory(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in addCategory");
return mapping.findForward("addcategory");
}


Now we established a User Interface mechanism to flow through your application.

Go To Step 26

Read more...

JAVA Jobs and Statistics

Are you looking for a programming job in JAVA? It is always important to understand the job market when looking for a job especially in the computer industry. You can see at the bottom of my blog some Java statistics that will give you some good information on how the job market is doing. You can see all kinds of other graphs located at Java Market Statistics. How about statistics comparing Java and Perl? Or maybe you need some information on Kick Starting your Java Career. These are all important areas that you should understand concerning the Java job market. Check these websites out and give your Java career a boost.

Read more...

Sunday, November 16, 2008

Drop Down Menu User Interface Step 24

I am not doing a CSS tutorial, but you will need to understand it to make a well designed User Interface. You can go to this site for a CSS tutorial: http://www.w3schools.com/css/

This is an example of a drop down menu that you can use in your application. I am showing you how to set up a User Interface so I can demonstrate some of the Struts tags you will use in your JSP pages.

In your resources folder create two new folders. One we will call css and the other we will call js. The js is for your javascript files and the css will be for your cascading style sheet files.
Replace your ClassicLayout.jsp with the following code



<%@ include file="../include-taglibs.jspf" %>
<script type="text/javascript" src="resources/js/TJK_keyBoardDropDown.js"></script>
<style type="text/css">
@import "resources/css/main_final.css";

</style>
<html>
<body onload="TJK_keyBoardDropDown()">
<tiles:insert attribute="header" />
<tiles:insert attribute="body" />
<tiles:insert attribute="footer" />
</body>
</html>


This file is importing your new js file and css file. It also calls the javascript function needed for the menu when the page is loaded.

Replace your header file with this code. This code will be your menu layout.



<!-- TJK_keyBoardDropDown.js is required so the menu works in Internet Explorer-->

<div style="z-index: 10000;" id="base"><!-- Begin Base div-->
<!-- Begin Page Level Navigation -->
<ul id="TJK_dropDownMenu">

<li diamondmenu="yes" class="trigger" id="AB"><a alt="admin" title="admin" href="#">Admin</a>
<ul>
<li diamondmenu="yes"><a href="#" onclick="#">Add User</a>
</li>
</ul>
</li>


<li diamondmenu="yes" class="trigger" id="CF"><a title="Books" href="#">Books</a>
<ul>
<li diamondmenu="yes"><a href="#">Add Category</a>
</li>
<li diamondmenu="yes"><a href="#">Add Book</a>
</li>
</ul>
</li>
<li diamondmenu="yes" class="trigger" id="CF"><a title="Report" href="#">Reports</a>
<ul>
<li diamondmenu="yes"><a href="#">View Report</a>
</li>
</ul>
</li>




</ul>
</div>




Create a new file called main_final.css and place it in your css folder. Copy the following code into your new css file. These are some of the css classes we will use for your menu.



/* start global styles */

html {
font-size: 100.1%;
padding: 0;
margin: 0;
}

body {
padding: 0 0 8px 0;
margin: 0;
color: #000;
background-color: #fff;
text-align: center;
font-size:100.1%;
font-family:Verdana, Arial, Helvetica, sans-serif;
height:100%;
}

#base
{
width: 100%;
background:#fff;
color:#000;
vertical-align:top;
text-align:left;
margin:0;
padding:0;
float:left;
}

.clear {
clear:both;
margin-left: 0;
padding-left: 0;
}

#content
{
margin:0;
padding-bottom:0;
padding-right:0;
padding-top:0;
padding-left:2px;
text-align:left;
}

div {
position: relative;
}

main_90 {
position: relative;
width:90%;
}

#error
{
text-align:center;
width:100%;
}



/* zeroing padding/margin for all elements */
#TJK_dropDownMenu,
#TJK_dropDownMenu * { margin:0;padding:0;}
/* "Master" UL (the whole Menu) */
#TJK_dropDownMenu {
position:absolute;
background:#0061af no-repeat 100% 50%;
width:100%;
float:left;
margin-bottom:13.5em;
border-bottom:1px solid #666;
white-space:nowrap;
color:#c7c1db;
background:#0061af;
font-size:73%;
text-decoration:none;
font-weight:bold;
text-align:left;
cursor:pointer;

}
/* sub-menu ULs */
#TJK_dropDownMenu li ul {
width:15em !important;/* leaves room for padding */
cursor:pointer;
position:absolute;
height:26px;
display:none;
left:-10px;
padding:1px 10px 10px 10px;
background:url(/img/clear.gif);/* trick to keep'em open */
}
/* All LIs */
#TJK_dropDownMenu li {
position:relative;
cursor:pointer;
float:left;
list-style-type:none;
}
/* sub-menu LIs */
#TJK_dropDownMenu li ul li {
width:15em/*FF*/;
padding:0;
border:none;
max-width:150%;
border:1px solid #ccc;
border-top:none;
}
/* All anchors */
#TJK_dropDownMenu li a {
cursor:default;
color:#fff;
border-left:1px solid #ccc;
text-decoration:none;
display:block;
float:left;
padding:0 .4em;
/* uncomment the declaration below if you want to go "full width" */
/* width:7.47em; */
height:2em;
line-height:2em;
}
/* sub-menu Anchors */
#TJK_dropDownMenu li ul li a {
width:15em/*FF*/;
position:relative !important; /* ie Mac */
cursor:pointer !important;
white-space:nowrap;
line-height:1.7em;
height:1.7em;
font-weight:bold;
border:1px solid #fff;
color:#fff;
background-position:0 50% !important;
background: #0e1676
}
/* :hover and stuff */
#TJK_dropDownMenu li a:hover, {cursor: pointer;}
#TJK_dropDownMenu li a:focus,
#TJK_dropDownMenu li a:active {color:#fff}
/* move the declarations from the rule below the one above if you want a background swap on *all* anchors, including the top level ones */
#TJK_dropDownMenu ul a:hover,
#TJK_dropDownMenu ul a:focus,
#TJK_dropDownMenu ul a:active {color:#fff !important;background:#95017b}
/* display and z-index for the sub-menus */
#TJK_dropDownMenu li:hover ul,
#TJK_dropDownMenu li.msieFix ul {display:block;z-index:10;top:2em !important;}
/* safari: users can keep sub-menus up by from sub-menus to next top level */
/* didn't find a solution for users going back from the last one. I prefer */
/* to leave it like that vs. taking the last sub-menu *out of* the wrapper */
#TJK_dropDownMenu li#AB {z-index:8;}
#TJK_dropDownMenu li#CF {z-index:7;}
#TJK_dropDownMenu li#GJ {z-index:6;}
#TJK_dropDownMenu li#KR {z-index:5;}
#TJK_dropDownMenu li#ST {z-index:4;}
#TJK_dropDownMenu li#XX {z-index:3;}
#TJK_dropDownMenu li#ZZ {z-index:2;}
#TJK_dropDownMenu li#UZ {z-index:1;}

/* Current location - class on Body must match LI's id */
.AB #TJK_dropDownMenu li#AB a,
.CF #TJK_dropDownMenu li#CF a,
.GJ #TJK_dropDownMenu li#GJ a,
.KR #TJK_dropDownMenu li#KR a,
.ST #TJK_dropDownMenu li#ST a,
.XX #TJK_dropDownMenu li#ST a,
.ZZ #TJK_dropDownMenu li#ST a,
.UZ #TJK_dropDownMenu li#UZ a {color:#000;}
/* Keeping current menu accessible to JAWS */
.AB #TJK_dropDownMenu li#AB ul,
.CF #TJK_dropDownMenu li#CF ul,
.GJ #TJK_dropDownMenu li#GJ ul,
.KR #TJK_dropDownMenu li#KR ul,
.ST #TJK_dropDownMenu li#ST ul,
.XX #TJK_dropDownMenu li#ST ul,
.ZZ #TJK_dropDownMenu li#ST ul,
.UZ #TJK_dropDownMenu li#UZ ul {display:block;top:-1000px}

/* "trigger" and "msieFix" classes */
#TJK_dropDownMenu li.msieFix a {}
/* last nested UL. keeping it in */
#TJK_dropDownMenu li#UZ ul {left:-2.3em !important;}

/* If JS is OFF we need to style the links in the sub-menu of the current page */
/* so they are accessible to keyboard users. Using a class on each link would let */
/* us stick each link in the same place, but we would have to plug a lot of */
/* attributes in the markup and many rules here, so... */
.AB #TJK_dropDownMenu li#AB ul li a:focus,
.AB #TJK_dropDownMenu li#AB ul li a:active,
.CF #TJK_dropDownMenu li#CF ul li a:focus,
.CF #TJK_dropDownMenu li#CF ul li a:active,
.GJ #TJK_dropDownMenu li#GJ ul li a:focus,
.GJ #TJK_dropDownMenu li#GJ ul li a:active,
.KR #TJK_dropDownMenu li#KR ul li a:focus,
.KR #TJK_dropDownMenu li#KR ul li a:active,
.ST #TJK_dropDownMenu li#ST ul li a:focus,
.ST #TJK_dropDownMenu li#ST ul li a:active,
.XX #TJK_dropDownMenu li#ST ul li a:focus,
.XX #TJK_dropDownMenu li#ST ul li a:active,
.ZZ #TJK_dropDownMenu li#ST ul li a:focus,
.ZZ #TJK_dropDownMenu li#ST ul li a:active,
.UZ #TJK_dropDownMenu li#UZ ul li a:focus,
.UZ #TJK_dropDownMenu li#UZ ul li a:active {position:absolute !important;top:1028px !important;}

/* End Navigation Bar */


Create a file called TJK_keyBoardDropDown.js and place it in your js folder. This is the javascript function that will be used to create your menu.



// edit made to toggle() to give focus to the next link
function swap(){this.className="msieFix";}
function swapBack(){this.className="trigger";}
function toggle(){(this.parentNode.className=="trigger")?this.parentNode.className="msieFix":this.parentNode.className="trigger";/*return false;*/}
function reveal(){
this.parentNode.parentNode.parentNode.className="msieFix";
}
function cleanUp(){
var zA;
var LI = document.getElementsByTagName("li");
var zLI= LI.length;
for(var k=0;k<zLI;k ){
if(LI[k]!=this.parentNode){
LI[k].className="trigger";
}
}
}
function TJK_keyBoardDropDown(){// v1.2 Copyright (c) 2006 TJKDesign - Thierry Koblentz
var LI = document.getElementsByTagName("li");
var zLI= LI.length;
if (document.getElementById){
for(var k=0;k<zLI;k ){
if(LI[k].diamondmenu == "yes"){
if(LI[k].id){
LI[k].className="trigger";
LI[k].firstChild.onclick=toggle;
LI[k].firstChild.title="";
LI[k].firstChild.onfocus=cleanUp;
}
if(LI[k].className=="trigger"){
LI[k].onmouseover=swap;
LI[k].onmouseout=swapBack;
}
if(!LI[k].id){
LI[k].firstChild.onfocus=reveal;
}
}
}
}
}
document.write('<style type="text/css" media="screen">@import "../css/main_final.css";</style>')
// edit made to toggle() to give focus to the next link
function swap(){this.className="msieFix";}
function swapBack(){this.className="trigger";}
function toggle(){(this.parentNode.className=="trigger")?this.parentNode.className="msieFix":this.parentNode.className="trigger";/*return false;*/}
function reveal(){
this.parentNode.parentNode.parentNode.className="msieFix";
}
function cleanUp(){
var zA;
var LI = document.getElementsByTagName("li");
var zLI= LI.length;
for(var k=0;k<zLI;k++ ){
if(LI[k]!=this.parentNode){
LI[k].className="trigger";
}
}
}
function TJK_keyBoardDropDown(){// v1.2 Copyright (c) 2006 TJKDesign - Thierry Koblentz
var LI = document.getElementsByTagName("li");
var zLI= LI.length;
if (document.getElementById){
for(var k=0;k<zLI;k++ ){
if(LI[k].diamondmenu == "yes"){
if(LI[k].id){
LI[k].className="trigger";
LI[k].firstChild.onclick=toggle;
LI[k].firstChild.title="";
LI[k].firstChild.onfocus=cleanUp;
}
if(LI[k].className=="trigger"){
LI[k].onmouseover=swap;
LI[k].onmouseout=swapBack;
}
if(!LI[k].id){
LI[k].firstChild.onfocus=reveal;
}
}
}
}
}
document.write('<style type="text/css" media="screen">@import "../css/main_final.css";</style>')


When you visit your local host you should see a blue drop down menu. This will be our starting point for our User Interface navigation.


Go To Step 25

Read more...

Saturday, November 15, 2008

Making Your User Interface ADA and W3C Compliant Step 23

When creating a User Interface, it is also important to consider if your User Interface needs to be ADA (Americans with Disabilities Act) and W3C (Web Content Accessibility Guidelines) compliant. If you do any projects for the government, than you will need to make sure your User Interface is compliant. You can get more information at the following websites.

http://www.w3.org/TR/WCAG10/

http://www.ada.gov/

If you need to do a complete scan of your system to make sure you are compliant, you might need to purchase software such as Rational.

http://www-01.ibm.com/software/rational/offerings/websecurity/

However, you can visit this website http://validator.w3.org/#validate_by_upload to validate your web pages. You can view the source of each page on your website and save it as a separate file. You can Upload it by selecting the “validate by File Upload” tab and scan the page for any errors. It will give you a list of errors that you will need to fix.

You can also download eclipse's Accessibility Probe.

http://www.eclipse.org/actf/downloads/tools/accprobe/index.php

Go To Step 24

Read more...

Thursday, November 13, 2008

Creating an Effective User Interface Step 22

Now that you have some experience with retrieving data and saving data to the database, it is now time to create a User Interface in JSP.  There are many things you need to know before creating a User Interface.  You might have a User Interface designer create a html page and have you convert it to a JSP page, or you might be responsible for creating the User Interface yourself. However, you should be familiar with creating a well design User Interface.  


What is usability?

“A set of attributes that bear on the effort needed for use, and on the individual assessment of such use, by a stated or implied set of users.”

– ISO 9126 (1991) Software Engineering Product Quality

“The extent to which a product can be used by specified users to achieve specified goals with effectiveness, efficiency and satisfaction in a specified context of use.”
– ISO 9241-11 (1998) Guidance on Usability

 “Usability is a quality attribute that assesses how easy user interfaces are to use. The word “usability” also refers to methods for improving ease-of-use during the design process." 
– Jacob Nielson

Here are somethings you need to remember when creating a User Interface.

·        Learnability
How easy is it for users to accomplish basic tasks the first time they encounter the design?

·        Efficiency
Once users have learned the design, how quickly can they perform tasks?

·        Memorability
When users return to the design after a period of not using it, how easily can they re-establish proficiency?

·        Errors
How many errors do users make, how severe are these errors, and how easily can they recover from the errors?

·        Satisfaction
How pleasant is it to use the design?

Universal Principles of Design, an industry standard reference text for design, lists one hundred design principles. These principles cover a wide range of disciplines, including interior design, architecture, publishing, mechanics, and interface design. Many have demonstrated their effectiveness over hundreds of years of use in these disciplines. While some of these principles use daunting terminology, most are simply common sense.

The 80/20 rule: The high percentage of effects in any large system are caused by a low percentage of variables.

Accessibility: Objects and environments should be designed to be usable without modification, by as many people as possible such as perceptiblity, operability, simplicity. 

Aestetic (Usability Effect): Aesthetic designs are perceived as easier to use than less-aesthetic designs.

These are just a few principles you will need to remember.

There are a lot of information on creating a great User Interface and that is why User Interface designers who are familiar with these principles are in a high demand.  Just remember that creating a User Interface isn't just throwing buttons and links together, but should take some thought and discussion.

Links referenced:


http://en.wikipedia.org/wiki/Pareto_principle

http://en.wikipedia.org/wiki/Universal_design

http://en.wikipedia.org/wiki/Universal_usability

http://www.design.ncsu.edu/cud/about_ud/udprinciples.htm

http://www.jnd.org/dn.mss/emotion_design.html 

Go To Step 23  

Read more...

Deleting Using Hibernate Step 21

You need to be careful when deleting from a relational database. You have to be careful of creating what is called an orphan. An orphan is where two rows should have a relationship within two tables, but in one table the row was deleted so you broke the relationship between the two rows in the two tables. There are two ways you could delete from the database. If you do not want to be concerned about breaking the relationship, you can have a deleted flag in the database. If the flag is true, then the item is deleted and if it is false or null, then the file has not been deleted. You will have to add a where clause to your queries/mappings to only pull the objects that are not deleted. This solution will keep your referential integrity in your database. However, sometimes it is important to do a hard delete and remove the item completely from the database.

1) Adding Where Clause to Hibernate Mappings

In our Book.hbm.xml we need to add a where clause to pull the objects that are not deleted.

<class name="com.vo.Book" table="book" catalog="catalog" where="deleted is null or deleted=0">

You will need to add a column to your Book table in the database called deleted. You will make this column a boolean value. You will set this value to true if the item is deleted.

2) Delete Hibernate Object from Database (Hard Delete)

You can use this method to delete an object from the database.
sessionFactory.getCurrentSession().delete(Object);

To delete from all tables where this item is related, You can do a cascade delete by adding this to your mappings.

cascade="all-delete-orphan"

3) Delete Using SQL Query

You can also delete the data using a sql query.

PreparedStatement ps = null;
try{
Connection conn = sessionFactory.getCurrentSession().connection();
String sqlDelete = "delete from Book where id=?";
ps = conn.prepareStatement(deleted);
ps.setString(1,bookid);
ps.executeUpdate();


Go To Step 22, Usability

Read more...

Sunday, November 9, 2008

More Information on Hibernate using HQL and Converting Sets to List Step 20

There are a number of ways to get data from the database using Hibernate. In this post I am going to show you how to use a named query and the Hibernate's Transformer Object to pull data from the database. I am also going to show you how to retrieve List Objects from Hibernate instead of the Set Object. The Set Object is more difficult to work with and most programmers would prefer to retrieve a List Object.


Change Hibernate Mapping to Retrieve a List instead of a Set:

Since the reverse engineering creates Sets instead of Lists, you might not realize that you can get Lists from hibernate mappings instead of Sets. If you retrieve a List instead of a Set, you will not need to convert your Sets to Lists within your code. It is pretty easy to do this. All you need to do is go to your mappings (in our case: Book.hbm.xml, Bookcategory.hbm.xml and the Users.hbm.xml) and change set to bag. Then you will need to go to your vo objects and change the Sets to Lists (private List userses = new ArrayList();). Hibernate will now return Lists and not Sets into your vo objects.

Pulling Data using Hibernate's ResultTransformer:

HQL is the hibernate query language. It allows you to query similiar to SQL, but using objects.

You can paste this code into your Book.hbm.xml before your closing tag for your hibernate-mapping:

<query name="get_book_category">
SELECT DISTINCT a.bookName as bookName FROM Book a ORDER BY 1 </query>

This code is a HQL query that gets all of the book names from the object book. Notice that I am using the property name of the object and not the database column name. I am querying the list of book objects using the HQL language.

Add the below method into your UserBookDAO object.

public List<Item> getBookCategoryList()
{
Query query=null;
List<Item> categoryList=null;
try { HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); SessionFactory sessionFactory=HibernateUtil.getSessionFactory(); query = sessionFactory.getCurrentSession().getNamedQuery("get_book_category"); query.setResultTransformer(new AliasToBeanResultTransformer(Item.class)); categoryList=query.list(); HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); }
catch (RuntimeException re)
{ throw re;
}

return categoryList;
}

The named query has an attribute called bookName. This will be the same name as the attribute in the new object we are going to create called Item. We are going to transform the named query into the class called Item. In the above code we call the named query using the getNamedQuery method. We transform the object using the ResultTransformer into a new object called Item. We create that object below. The named query's property values should match the property values in the Item object. Add the below object to your com.vo package.

com.vo.Item.class
package com.vo;
public class Item {
private String bookName;
private String bookCategory;
public String getBookName()
{
return bookName;
}
public String getCategoryName()
{
return bookCategory;
}

public void setBookName(String name)
{
bookName=name;
}

public void setCategoryName(String name)
{
this.bookCategory=name;
}
}
You will now need to add this method to your UserBookServiceImpl.java class.

public List getBookCategoryList() { return dao.getBookCategoryList(); }

You will need to add this method to your UserBookService.java class.

public List getBookCategoryList();

You can then place this code into your setUser method in your action class or any other method you are using to test if your code still works. This code tests if you return a list in your book class instead of a set, and it will test your named query. If the proper information prints out into your console, than your changes worked.

UserBookService service = ServiceFactory.getInstance().getUserBookService();
List<Item> bookCategory=service.getBookCategoryList();
if(bookCategory!=null)
{
for(Item item:bookCategory) {
if(item.getBookName()!=null) {
System.out.println("item book name: "+item.getBookName());
}
if(item.getCategoryName()!=null) {
System.out.println("item category name: "+item.getCategoryName());
}
}
}
List<Book> bookList=service.getBooks();
Book book=bookList.get(0);
List<Users> userList=book.getUserses();
for(Users user:userList) {
System.out.println("User in book "+ user.getFirstName()+ " " +user.getLastName());
}

Read more...

Monday, November 3, 2008

Retrieve Object Hibernate, Save Serializable Object Step 19

In my last step I showed you how to retrieve objects and set up the Hibernate DAO.

In this post, I will show you how to save your Hibernate Object, and retrieve a specific object using the id.

If you were able to set everything else up in Hibernate, these steps should be pretty easy.

These three methods you should add to your UserBookDAO.java Object.

Method to Retrieve Objects based on the Id and Method to Save Hibernate Objects

public Book getOneBook(long id)
{
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Book book=null;
try {
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
book=(Book)sessionFactory.getCurrentSession().get(Book.class,id);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (RuntimeException re) {
System.out.println("Error In Hibernate getBook" re.toString());
throw re;
}
return book;
}
public Users getOneUser(long id)
{
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Users user=null;
try {
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
user=(Users)sessionFactory.getCurrentSession().get(Users.class,id);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (RuntimeException re) {
System.out.println("Error In Hibernate getBook" re.toString());
throw re;
}
return user;
}
public void save(Serializable transientInstance) {
try {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
sessionFactory.getCurrentSession().save(transientInstance);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (RuntimeException re) {
throw re;
}
}



The first two methods retrieves the objects using the id. This will allow you to retrieve a particular User or a particular Book based on the id. The other method will allow you to save the objects. The save method allows you to save a serializable object. Hibernate will know which table to save the data too based on your hibernate mappings.

You will also need to add these methods to your UserBookServiceImpl.java class.

public Book getOneBook(long id)
{
return dao.getOneBook(id);
}
public Users getOneUser(long id)
{
return dao.getOneUser(id);
}
public void save(Serializable transientInstance)
{
dao.save(transientInstance);
}


You will need to add these to your UserBookService.java class.


public Book getOneBook(long id);
public Users getOneUser(long id);
public void save(Serializable transientInstance);


This code can be added to your action class to test to make sure the methods work.
This code has the id's hardcoded.  Therefore, make sure that the id in this code matches the ids in your database.

Book book=service.getOneBook(1);
System.out.println("Book with Id: "+ book.getBookName());
Users user=service.getOneUser(1);
System.out.println("User with Id: " +user.getFirstName() +" "+ user.getLastName());
Users newuser=new Users();
newuser.setFirstName("New User");
newuser.setLastName("New Users Last Name");
service.save(newuser);

************************************************
The
eclipse console should printout the names of the individual user and individual book you called based on the id. A new user will be added to the database as well. You can check your database to make sure the new user was added. Make sure you pass in a valid id into the method or you will get a null pointer exception.

You might receive an error that says you have a duplicate key when saving the User to the database. That is because you need to change your hbm.xml mappings to reflect a key generator that will increment your key id for you. In all of your mappings, you should change your generator to class="increment" from the class="assigned". This will allow hibernate to insert a key into the database for you and increment the id for each object that is saved. This way your primary key will still be unique.


Read more...