85
Training - Day 1 Nate Johnson Indiana University Davis, CA : Sept 18-21, 2006

Training - Day 1

Embed Size (px)

DESCRIPTION

Training - Day 1. Nate Johnson Indiana University Davis, CA : Sept 18-21, 2006. Principal Systems Analyst Indiana University in Bloomington, IN SIT (Systems Integration Team) Portal Workflow Integration Production debugging & troubleshooting Training. About me. - PowerPoint PPT Presentation

Citation preview

Training - Day 1

Nate Johnson

Indiana University

Davis, CA : Sept 18-21, 2006

About me

• Principal Systems Analyst– Indiana University in Bloomington, IN

• SIT (Systems Integration Team)– Portal– Workflow– Integration– Production debugging & troubleshooting– Training

This week

• Very informal… feel free to ask questions at any time

• Start each day at 9:00 am and try to finish near 5:00 pm

• Lunch?

Monday Sept 18

• Eclipse

• MyEclipse

• Web environment

• Ant & log4j

• Java 5.0

Tuesday Sept 19

• Struts Framework– Struts tag libraries

• JSP

• JSTL– Custom JSTL tags

• DisplayTag tag library

Wednesday Sept 20

• OJB

• Might begin the Spring Framework

Thursday Sept 21

• Spring Framework

• Testing– jUnit– jMeter

This week continued…

• Lots of exercises and sample code

• Feel free to work in pairs and talk out the exercises

• Will also be building a small sample application that uses all of the frameworks we are learning this week

Section 1: Eclipse & MyEclipse

• Most of this section will be covered via a demo/walkthrough

Navigating Eclipse

• The workbench• Perspectives• Views• Editors• Toolbars and menus• Exploring our project

The Workbench

• The term Workbench refers to a desktop development environment. – It strives to seamlessly integrate

perspectives (editors, views, menus, etc.) into a useful environment.

• The Welcome project (Help > Welcome)

Perspectives

• A workbench may contain multiple perspectives (Java, Debug, CVS, etc.)

• A perspective is a group of related editors, views, and menu actions

• Switch (or add / remove) perspectives using the perspective shortcut bar

Editors

• Editors are typically used to edit a resource (a Java or XML file)

• Multiple instances of an editor may be open at the same time - editing multiple Java and XML files

• Editors follow a open > save > close lifecycle (* denotes an unsaved editor)

• External editors can be used (MS Word)

Views

• Used to navigate a hierarchy of information– Resources– Outlines– Display properties

• Can be moved and re-docked to fit you• Modifications are saved immediately• Most likely only one instance of a view will

exist at one time• Fast Views save space on small screens

Toolbars and Menus

• The main, or workbench, toolbar– Changes based on active perspective– Active view may enable/disable features– Sections can be rearranged

• View toolbars– Appear in title bar of the view– May also have a triangle button menu dropdown

• Perspective switcher• Fast view bar

Creating a new things

• Create a brand new Java project– File > New > Project– Select Java Project – Follow the wizard

• Create new files– File > New > Class | Interface | etc.– Be sure to give it a package and legal name

Using Source Control

• Check out a project from CVS– Most likely method used in UIS– Use CVS Repository Perspective– Get the project: Right-click > Check Out

Exploring the project

• Do you have any red X’s in your Package Explorer? If so, we need to figure them out before continuing

• Views: Overview most common… add Ant View if not currently available

• Editors: Overview the Java Source Editor and the MyEclipse XML Editor

Still Exploring…

• Project properties

• The deployment script: build.xml

• MyEclipse – Window > Preferences… > MyEclipse– MyEclipse toolbar icons

• Build (automatically) and run the project

Tips and tricks

• Eclipse Platform– http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.pl

atform.doc.user/tips/platform_tips.html

• Java Specific– http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.jdt

.doc.user/tips/jdt_tips.html

• Let’s take a look at some!

References

• http://help.eclipse.org/help32/index.jsp

Section 2: Web Environment

• The HTTP Request / Response cycle• Properties Files and Resource Bundles• Java Servlets• Servlets and threads• Servlet Context• Servlet Request• Servlet Response• Filtering• Sessions• Web Applications• Web application deployment descriptor (web.xml)• Java Server Pages and JSP Tag Libraries

HTTP Request / Response Cycle

• User makes a request (for a webpage in a browser).

• Web server gets request, and formulates a response to send to user.

• Stateless!• Frameworks, like Struts, make this

easier than the old CGI, or even Servlets, programming models.

Properties Files & ResourceBundles

• Common way to configure web applications.

• ResourceBundles use one or more files to provide i18n based on Locales.

Java Servlets

• Java’s OO HTTP• A servlet container maps requests to servlets as well

as maintains the servlet lifecycle.

public void init( ServletConfig config);

public void doGet( HttpServletRequest request,

HttpServletResponse response);

public void doPost( HttpServletRequest request,

HttpServletResponse response);

public void destroy();

• org.apache.struts.action.ActionServlet

Servlets and threads

• Web container can boost performance by multi-threading servlets (the default way a servlet is deployed and coded).

• One instance of a servlet is created and all requests go through it.

• doGet() and doPost() need to be thread safe.

Servlet Context

• Servlet’s view of the web application which is running the servlet.

• Servlet.getServletConfig() and JSP application variable.

• Provides access to webapp resources and servlet context attributes.

Servlet Request

• javax.servlet.http.HttpServletRequest– Cookies - the cookies included with this request– Headers - HTTP headers that were included with the

request – Parameters - Request parameters from the query string or

post data – Request URI Information – items such as contextPath,

servletPath, and pathInfo– And more…

• Request attributes are very useful in relaying information to Views – you will see this when we start looking at the Actions and JSPs.

Servlet Response

• javax.servlet.http.HttpServletResponse – Set Headers - set response headers, such as Content-Type.– Set Cookies - add cookies to the current response. – Send Error Responses - send an HTTP error status (instead

of a usual page of content).– Redirect To Another Resource - use the sendRedirect()

method to redirect the client to some other URL that you specify.

• Any of the above MUST be done before the first buffer is flushed the user will see an error.

• Most of the time you will not directly manipulate the response object… the framework, Struts, will do it for you.

Filtering

• javax.servlet.Filter • Process requests/responses and can

be chained.• Good place to do common processing

for all requests.• Ex: The CAS filter, which can help in

providing SSO and an IU User to each request.

Sessions

• HTTP is stateless, which means every request is brand new.

• javax.servlet.http.HttpSession • The servlet container can provide the concept of a

session in two ways– Cookies– URL Rewriting

• Have a timeout• Session attributes need to be Serializable.• Think carefully about how much you store in Session:

this uses memory (session/per user) on the server.

Web Applications

• A servlet container can run many web application at one time.

• Each web application has its own namespace.

• A web application is bundled into a Web Application Archive file (WAR).

Web application deployment descriptor (web.xml)

• <webapp>/WEB-INF/web.xml

• Configuration of a web application, and the web application lifecycle

• In UIS, we configure CAS, log4j, various tag libraries, and datasources in web.xml– Let’s check it out

Java Server Pages & JSP Tag Libs

• A JSP is an xml document, that looks similar to HTML, which can contain Java logic or use special tags, and creates a dynamic web page.

• JSP is compiled into a servlet by the servlet container.

• Tag libraries are sets of JSP tags, that can be used for a number of tasks, from logic to formatting to querying a database.

Walkthrough

• Let’s take a look at our webapp

Section 3: Useful Libraries

• Ant – http://ant.apache.org/manual/index.html

• log4j• Let me know if there are others you

would like to know about and we might be able to work them in at the end of the week.

Section 4: Java 1.5 (aka 5.0)

• Generics

• Enhanced for loop

• Auto-boxing and auto-unboxing

• Typesafe enumerated types

• Variable arguments

• Static imports

More changes…

• Networking

• Security

• Formatter

• Scanner

• Concurrency Utilities

• Monitoring

Generics

• Compare and contrast generic and non-generic collections

• Use the generic version of the Collections API

• Use generics with wildcards

• Integrate legacy (non-generic) code with generic code

Intro

• Common examples are container types such as the Collections: Set, List, and MapList myIntList = new LinkedList();myIntList.add(new Integer(47));Integer x=(Integer) myIntList.get(0);

• Line 3 introduces clutter but is essential to guarantee type safety

What does generics give you

• With generics, you can:– Specify element type of collection– Enforce specification at compile time

• No more runtime errors

– Provide stronger typing with less clutter

Same example, with Generics

• The core idea behind generics is that programmers can mark a list as being restricted to a certain type

List<Integer> myIntList = new LinkedList<Integer>();

myIntList.add(new Integer(47));Integer x = myIntList.get(0);

• You say that List is a generic interface that takes a type parameter – in this case, Integer

• Notice, also, that the cast is gone on line 3

Defining your own Generics

• Example of List and Iterator using generics:public interface List<E> { void add(E x); Iterator<E> iterator();}public interface Iterator<E> { E next(); boolean hasNext();}

• Elements in the angle brackets ( <E> in this example) represent formal type parameters

Defining continued…

• During invocation, formal type parameters are replaced by actual type parameters

• Imagine that List<Integer> stands for a version of List where E has been formally replaced by Integer:List<Integer> myInteger;

Is like:IntegerList myList;

Where:public interface IntegerList { void add(Integer x); Iterator<Integer> iterator();}

Subtyping Generics

• Consider the following example:List<String> ls = new ArrayList<String>();

List<Object> lo = ls;

• Is this legal? Line 2 suggests that a List of String is a List of Objects.

Actually, it’s not

• What if you had this:lo.add(new Object());

String s = ls.get(0);

• The generics would fail

• The compiler will prevent you from doing the assignment in the first place

Wildcards and Subtyping

• You may think that a wildcard would be Collection<Object> since Object is the base class of all objects – but its not.

• For generics, it’s Collection<?> where ? is to be read as “unknown”

• For subclassing something like Shape (Circle and Rectangle) you can not just use List<Shape>

• You have to do it this way:List<? extends Shape>

General v. Bounded Wildcards

• From the previous slide’s classes. This would only draw Shape objects.

public void drawAll(List<Shape> shapes)

• Whereas this would draw anything.

public void drawAll(List<?> objects)

• And this would draw anything that extends Shape.

public void drawAll(List<? Extends Shape> shapes)

Generic Methods

• Write a method that takes an array of objects and a collection and dumps all of the objects into the collection:

void arrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile time error }}

• Will not work? Why?

We need generic methods

• As with type declarations, method declarations can also be generic:

<T> void arrayToCollection(T [] a, Collection<T> c) { for (T o : a) { c.add(o); // NO compile time error }}

• T is the return type, collection type, and array type

Examples

• With T as ObjectObject [] oa = new Object[100];Collection<Object> co = new ArrayList<Object>();arrayToCollection(oa, co);

• With T as StringString [] sa = new String[100];Collection<String> cs = new ArrayList<String>();arrayToCollection(sa, cs);

• Compiler will ensure types work out and that the proper types are used

What about Legacy Code?

• Up until now, we have just assumed everything has been written with generics – that’s not the real world.

• As long as your collections are taking the proper types from legacy code, you will be ok, and will just get a warning from the compiler

Example – Legacy Code

package drawings;

public interface Shape { ... }

public class Gallery { public static void addDrawing(String name, Collection shapes) {...} public static Drawing getDrawing(String name) {...}}

public interface Drawing { public Collection getShapes();}

Generic code uses the legacy code

package gallery;

import drawings.*;

public class Circle implements Shape { ... }

public class Square implements Shape { ... }

public class Main { public static void main(String[] args) { Collection<Shape> c = new ArrayList<Shape>(); c.add(new Circle()); c.add(new Square()); Gallery.addDrawing(“Explorations”, c); Collection<Shape> k = Gallery.getDrawing(“Explorations”).getShapes(); }}

Sharing

• This will be true because there is only one runtime class, regardless of the typed parameter.

List<String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); l1.getClass() == l2.getClass();

• Static variables and methods are shared among all instances.

When should you use them?

• Always!

• Increases clarity and type safety, and works with legacy code.

In conclusion…

• Generics provide a way for you to communicate the type of a collection to the compiler, so that the type can be checked

• Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection

• Generics provide type safety and remove clutter associated with casting

Exercise: Generics

• Handout 1

Enhanced for loops

• Enhanced for-loops make it easy to traverse through collections while avoiding error-prone iterators.

for ( Type x: collection ) {

x.doSomething();

}

• No more Iterator!• Less code, more reliable, better performance

because the compiler knows best.

Example: Where’s the bug?

01: List<Suit> suits = ...;02: List<Rank> ranks = ...;03: List<Card> sortedDeck = new ArrayList<Card>();04:05: for (Iterator<Suit> s = suits.iterator(); s.hasNext();) {06: for (Iterator<Rank> r = ranks.iterator(); r.hasNext(); ) {07: sortedDeck.add(new Card(r.next(), s.next()));08: }09: }

Fixed the bug

01: List<Suit> suits = ...;02: List<Rank> ranks = ...;03: List<Card> sortedDeck = new ArrayList<Card>();04:05: // Fixed and pretty06: for (Suit suit : suits) {07: for (Rank rank : ranks) {08: sortedDeck.add(new Card(rank, suit));09: }10: }

Final thoughts

• Can not be used when:– you want to remove an element from a collection.– you want to modify an element while iterating.– you want to iterate multiple collections at the same time.

• Any other time, go for it!• Note: can be used with arrays too.• Check out example in exercises package

– ForEach.java

Exercise: Enhanced For Loop

• Handout 2

Auto-boxing and Auto-unboxing

• Auto-boxing and Auto-unboxing reduce the efforts previously required to cast primitive types back and forth. The compiler now does this for you.

• Before Java 1.5Integer grade = new Integer(10);int g = grade.intValue();

• In Java 1.5Integer grade = 10;int g = grade;

Another example

• Autoboxinglist.add(23); // list is List<Integer>

• Auto-unboxingint value = list.get(0);

Caveats

• The wrappers are created behind the scenes, so performance degradation is possible.

• Use them to make your code more readable: IMO, I would sacrifice a bit of performance for maintainability… most of the time.

• Don’t use them when:– you are inside of an long running inner loop– items in a collection might be null

Exercise: Autoboxing

• Handout 3

Typesafe enums

• Typesafe enums provide a way to define enumerated types that can be checked by the compiler for type safety.

• Better than the C/C++ counterpart: they are a class, not a glorified integer.

• Simple example:enum Suit { CLUB, DIAMOND, HEART, SPADE };

01: public class ChessPiece {02:03: public static final int TYPE_KING = 0;04: public static final int TYPE_QUEEN = 1;05: public static final int TYPE_ROOK = 2;06: public static final int TYPE_KNIGHT = 3;07: public static final int TYPE_BISHOP = 4;08: public static final int TYPE_PAWN = 5;09:10: public static final int COLOR_WHITE = 0;11: public static final int COLOR_BLACK = 1;12:13: private final int type;14: private final int color;15:16: public ChessPiece(int type, int color) {17: this.type = type;18: this.color = color;19: }

Typical “enumerated types” before Java 1.5

- used a bunch of ints

20:21: public int getType() {22: return this.type;23: }24: public int getColor() {25: return this.color;26: }27:28: public String toString() {29: String out = this.color == COLOR_WHITE ? “white“ : “black“;30: switch (this.type) {31: case TYPE_KING: return out + “ king”;32: case TYPE_QUEEN: return out + “ queen”;33: case TYPE_ROOK: return out + “ rook”;34: case TYPE_KNIGHT: return out + “ knight”;35: case TYPE_BISHOP: return out + “ bishop”;36: case TYPE_PAWN: return out + “ pawn”;37: default: return “invalid chess piece”;37: }38: }39: }

Can you think of any problems with this solution?

Problems

• Not type safe: constructor takes ints… nothing is enforcing a type or color.

• Can do things like:int x = ChessPiece.COLOR_BLACK + ChessPiece.TYPE_QUEEN;

• Printed values are uninformative: just ints.

• No easy way to enumerate/iterate and no bounds.

A fix with typesafe enums01: public class ChessPiece {02:03: public static enum Type { KING, QUEEN, ROOK, KNIGHT, BISHOP, PAWN };04:05: public static enum Color { WHITE, BLACK };06:07: private final Type type;08: private final Color color;09:10: public ChessPiece(Type type, Color color) {11: this.type = type;12: this.color = color;13: }14:15: public Type getType() {16: return this.type;17: }18:19: public Color getColor() {20: return this.color;21: }22:23: public String toString() {24: return System.out.printf("%s %s\n", this.color, this.type);25: }26: }

Benefits• Compile time safety• Loaded at run time – don’t have to recompile client code.• Allows arbitrary fields and methods.• Can implement interfaces.• Can be iterated/used in collections.• Inherit from java.lang.Object• Implement Comparable and Serializable• Nice printed values• Performance is similar to using ints – no worries.• Can be used in switch statements, unlike other objects.

01: public enum Planet {02: // Constants03: MERCURY (3.303e+23, 2.4397e6),04: VENUS (4.869e+24, 6.0518e6),05: EARTH (5.976e+24, 6.37814e6),06: MARS (6.421e+23, 3.3972e6),07: JUPITER (1.9e+27, 7.1492e7),08: SATURN (5.688e+26, 6.0268e7),09: URANUS (8.686e+25, 2.5559e7),10: NEPTUNE (1.024e+26, 2.4746e7),11: PLUTO (1.27e+22, 1.137e6);12:13: // Fields14: private final double mass; // in kilograms15: private final double radius; // in meters

16:17: // Constructor18: Planet(double mass, double radius) {19: this.mass = mass;20: this.radius = radius;21: }22:23: // Methods24: public double getMass() { return mass; }25: public double getRadius() { return radius; }26: public static final double G = 6.67300E-11;27:28: public double getSurfaceGravity() {29: return G * mass / (radius * radius);30: }31: public double getSurfaceWeight(double otherMass) {32: return otherMass * getSurfaceGravity();33: }34: }

Enums can be more powerful by giving them their own methods!

Using the Planet enum01: public class Test {02:03: public static void main(String [] args) {04: double earthWeight = Double.parseDouble(args[0]);05: double mass = earthWeight / EARTH.getSurfaceGravity();06: for (Planet p : Planet.values()) {07: System.out.printf("Your weight on %s is %f\n",08: p, p.getSurfaceWeight(mass));09: }10: }11:12: }

Let’s give it a try and see what it does.

Exercise: Typesafe Enums

• Handout 4

Variable arguments

• Varargs allow a variable number of arguments to be passed to a method. Another idea borrowed from C/C++.

• A good example is the new printf method.• Can only be used as the last variable to a method.• Basically, an array is created behind the scenes

– Can even call .length to find how many arguments were passed to the method call

Old School (the max method)

• Here is a basic max methodint max(int a, int b) { return a > b ? a : b;}

• For multiple arguments you would call it as follows:// works, but hard to readint m = max(a, max(b, max(c, d)));

• Another solution: write overloaded methods: ex: int max(int a, int b, int c)

Using varargs01: // return the int with the maximum value02: int max(int... values) {03: int max = Integer.MIN_VALUE;04: for (int i : values) {05: if (i > max) {06: max = i;07: }08: }09: return max;10: }11:12: int m2 = max(a, b);13: int m3 = max(a, b, c);14: int m4 = max(a, b, c, d);15:16: // what if the values already come in an array?17: int [] values = {1, 2, 3, 2, 3, 1};18: int m = max(values);

Let’s give it a try and see what it does.

Exercise: Varargs

• Handout 5

Static imports

• Static imports simplify the task of importing constants and other static members in your code like when you are importing packages.

• Instead of: double r = Math.cos(Math.PI * theta);

• Import it and use it to make your code more readableimport static java.lang.Math.cos;import static java.lang.Math.PI;// ...double r = cos(PI * theta);

A common Anti-pattern

• A common way to get at constants has been to stick them in Interfaces and implement the interface, or just use that interface to get to global constants.

• Interfaces are public APIs, and logic (constants) really should not be in a public API.

• Not very clean, and now there is a solution built into the language.

When vs. When Not?

• It’s best not to overuse this neat new feature. It can make your code harder to read if you statically import too much.

• Use it when you are accessing a constant a lot, or when you feel the desire to write one of those anti-patterns

Exercise: Static Imports

• Handout 6