Wednesday, May 13, 2009

java.lang.IllegalStateException: This widget's parent does not implement HasWidgets

java.lang.IllegalStateException: This widget's parent does not implement HasWidgets

 

Ugh…that’s my nasty exception.

Apparently, I was using a class that extends composite, as the books I’m reading suggest. But, if you do, apparently if you add the composite to another page as though it were a panel, well, that won’t work. Either I should have extended a Panel class for my composite container, or I need to implement the HasWidgets interface.

 

import com.google.gwt.user.client.ui.HasWidgets;

 

Apparently, these are the methods involved in the HasWidgets interaface. The actually look like they make sense:

 

@Override
public void add(Widget w) {
    // TODO Auto-generated method stub
}

@Override
public void clear() {
    // TODO Auto-generated method stub
}

@Override
public Iterator<Widget> iterator() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean remove(Widget w) {
    // TODO Auto-generated method stub
    return false;
}

 

I’m just going to leave them blank for now and see if it works.

Monday, May 11, 2009

Hibernate Serialization Policy or its Class object could not be loaded javassist

Here’s a good link that addresses the problem of passing domain model classes with one to many or many to many relationships between your data layer implemented in Hibernate, and the GWT Google Web Toolkit UI:

 

http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/d4cc869ce6372d7f/5022d6980de27167?hide_quotes=no

 

So, it looks like the best way to do this is to simply use hibernate4gwt, which has been renamed to Gilead over on sourceforge.net.

 

http://noon.gilead.free.fr/gilead/index.php?page=tutorial

 

Apparrently it helps to serialize and deserialize your objects, and it works with other serialization technologies, not just Google Web Toolkit.

 

public class User extends LightEntity implements Serializable

 

Ugh…Now I’m getting the following errors:

No source code is available for type net.sf.gilead.pojo.java5.LightEntity; did you forget to inherit a required module?

I guess I better not define my model classes on the client side of my GWT app?

 

Some neat GWT stuff:

 

http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=RefJreEmulation

GWT Source code is not available did you forget to inherit a required module?

I keep getting this error when I try to hit my domain model classes. Is this all because I did not put my model domain classes under the gwt.client package?

We’ll see.

Persisting the SCJP Objectives using Hibernate and JPA

package com.mcnz.exam.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import com.mcnz.exam.common.Answer;
import com.mcnz.exam.common.Certification;
import com.mcnz.exam.common.Objective;
import com.mcnz.exam.common.Question;
import com.mcnz.exam.dao.DAOFactory;

public class DatabaseTester {

    public static void main(String[] args) {

        DatabaseTester.recreateDatabase();
        DatabaseTester.addCertification();
        DatabaseTester.addObjective();
        DatabaseTester.addQuestion();

    }
    public static void addQuestion() {
        HibernateUtil.beginTransaction();
        Objective primaryObjective = DAOFactory.getFactory().getObjectiveDAO().findByPrimaryKey(new Long(1));
        List secondaryObjectives = new ArrayList();
        secondaryObjectives.add(DAOFactory.getFactory().getObjectiveDAO().findByPrimaryKey(new Long(2)));
        secondaryObjectives.add(DAOFactory.getFactory().getObjectiveDAO().findByPrimaryKey(new Long(3)));
        Question question = new Question("What do you call a fish without an eye?", "{x = fish - i}", "It's a fsh.", "{fish - i} = fsh", primaryObjective, secondaryObjectives );
        DAOFactory.getFactory().getQuestionDAO().save(question);
        {
            Answer answer = new Answer("fsh", new Boolean(true), question);
            question.getPotentialAnswers().add(answer);
            DAOFactory.getFactory().getAnswerDAO().save(answer);
        }
        {
            Answer answer = new Answer("Blinky", new Boolean(false), question);
            question.getPotentialAnswers().add(answer);
            DAOFactory.getFactory().getAnswerDAO().save(answer);
        }
        {
            Answer answer = new Answer("One Eyed Fish", new Boolean(false), question);
            question.getPotentialAnswers().add(answer);
            DAOFactory.getFactory().getAnswerDAO().save(answer);
        }
        {
            Answer answer = new Answer("fisheye", new Boolean(false), question);
            question.getPotentialAnswers().add(answer);
            DAOFactory.getFactory().getAnswerDAO().save(answer);
        }
        HibernateUtil.commitTransaction();
    }

    public static void addObjective() {
        HibernateUtil.beginTransaction();
        Certification scjp = DAOFactory.getFactory().getCertificationDAO().findByPrimaryKey(new Long(1));
        {
            Objective objective = new Objective("Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).", 1.1, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }
        {
            Objective objective = new Objective("Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.", 1.2, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.", 1.3, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that declares both static and non-static methods, and - if appropriate - use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list.", 1.4, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.", 1.5, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.", 1.6, "Section 1: Declarations, Initialization and Scoping ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that implements an if or switch statement; and identify legal argument types for these statements.", 2.1, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.", 2.2, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.", 2.3, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.", 2.4, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.", 2.5, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.", 2.6, "Section 2: Flow Control ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.", 3.1, "Section 3: API Contents", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.", 3.2, "Section 3: API Contents", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.", 3.3, "Section 3: API Contents", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.", 3.4, "Section 3: API Contents", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \\d, \\s, \\w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.", 3.5, "Section 3: API Contents", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.", 4.1, "Section 4: Concurrency ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.", 4.2, "Section 4: Concurrency ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.", 4.3, "Section 4: Concurrency ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.", 4.4, "Section 4: Concurrency ", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.", 5.1, "Section 5: OO Concepts", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.", 5.2, "Section 5: OO Concepts", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.", 5.3, "Section 5: OO Concepts", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.", 5.4, "Section 5: OO Concepts", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that implements \"is-a\" and/or \"has-a\" relationships.", 5.5, "Section 5: OO Concepts", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.", 6.1, "Section 6: Collections / Generics", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.", 6.2, "Section 6: Collections / Generics", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.", 6.3, "Section 6: Collections / Generics", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.", 6.4, "Section 6: Collections / Generics", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the \"natural ordering\" of primitive wrapper classes and java.lang.String on sorting.", 6.5, "Section 6: Collections / Generics", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.", 7.1, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given an example of a class and a command-line, determine the expected runtime behavior.", 7.2, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.", 7.3, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.", 7.4, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.", 7.5, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        {
            Objective objective = new Objective("Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.", 7.6, "Section 7: Fundamentals", scjp);
            DAOFactory.getFactory().getObjectiveDAO().save(objective);
        }

        HibernateUtil.commitTransaction();

    }

    public static void addCertification() {
        HibernateUtil.beginTransaction();
        Certification scjp = new Certification("SCJP", "Sun Certified Java Programmer", "6", "Sun");
        DAOFactory.getFactory().getCertificationDAO().save(scjp);
        HibernateUtil.commitTransaction();
    }

    public static void recreateDatabase() {
        HibernateUtil.recreateDatabase();
    }

}

Sunday, May 10, 2009

IndexOutOfBoundsException: Column index: 1, Column size: 1

java.lang.IndexOutOfBoundsException: Column index: 1, Column size: 1
    at com.google.gwt.user.client.ui.Grid.prepareCell(Grid.java:258)

 

So, apparently, this is the error you get when you try to add a widget to a cell in a Grid that does not exist. Serves me right!

 

Changing the Grid to 5,2 instead of 5,1 worked. I guest the method setWidget is zero based, but the Grid constructor in ordinal.

 

final VerticalPanel panel = new VerticalPanel();

        final Grid grid = new Grid(5, 2);
        initWidget(grid);

        grid.setWidget(0, 0, new Label("Query"));
        TextArea queryTextArea = new TextArea();

        queryTextArea.setWidth("1000px");
        queryTextArea.setHeight("200");
        grid.setWidget(0, 1, queryTextArea);

Saturday, May 9, 2009

SCJP Mock Exam Working with Strings and Split

 

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain, has gone.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option e) is correct.

The matching String “n” occurs three times in the String named prompt, and the split command will always return n+1 string fragments, where n is the number of times the argument passed into the split method is found in the String object being split.

*******************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain, has gone.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments[1]);
}

a) d the rai
b) nd the rai
c) d the rain
d) nd the rain
e) A checked exception will be thrown at runtime
f)  An unchecked exception will be thrown at runtime
g) The code will not compile

 

Option b) is correct.

“nd the rai” is the String that will be contained in the second fragment of the String array after the prompt has been parsed.

A common mistake is to think the sequence of characters, which in this case is the letter “n”, is included in the fragment returned from the split method. The character String passed into the split method will not be contained, either at the beginning or the end, of the various String fragments contained in the returned array.

The four String fragments contained in the array returned after the prompt is split on the letter “n” are:

1: A
2: d the rai
3: , has go
4: e.

*********************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "nnd the rain.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments.length());
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

 

Option i) is correct.

There variable fragments represents an array, and to find the size of an array, we use the length property, not the length() method.

If the round brackets, (), following ‘length’ were removed, the code would compile and run, spitting out the number 4 to indicate that splitting the String named prompt on the String sequence “n” would result in four String fragments. Since the String named prompt begins with two consecutive “n” matches, the first two elements in the fragments array would be empty String objects:

1:
2:
3: d the rai
4: .

*****************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "Nnd the rain.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

 

Option d) is correct.

We will always see n+1 array elements after splitting a given String, where n is the number of times the String sequence passed into the split method is matched on the String in question. There are two matches to the String “n” in the prompt String, so, two plus one, which is three, elements will will be contained in the fragments array.

The split method of the java.lang.String class is case sensitive, so an upper case letter will not strike a match with a lower case letter.

**************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,\n has gone.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option e) is correct.

Although from a spelling point of view, the letter “n” appears four times in the String named prompt, the Java Virtual Machine does not consider the “\n” String sequence when performing a split match on the letter “n". This is because “\n” is a special construct in Java known as the ‘escape sequence’, with this particular escape sequence representing the carriage return, or enter key.

Removing the ‘\n’ escape sequence from the prompt String, we are left with three occurrences of the letter “n”, and as a result, n+1, or four, elements are placed in the fragments array.

************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,/n has gone.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option f) is correct.

The trick in this question is to see if you can differentiate between correct and incorrect escape sequence syntax. “/n” is not correct escape sequence syntax for a carriage return, so the Java Virtual Machine treats the ‘n’ in this String as any other match on the letter ‘n’, thus splitting thing String on this element. Along with the three other matches on the letter “n” in the String named prompt, we end up with five elements in the fragments array.

*******************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,\n has gone.";
    String[] fragments = prompt.split("\n");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option c) is correct.

This question looks for a match in the String named prompt on the special character sequence representing the return key, “\n”. A single match is found, and two String are created and placed as separate elements in the array named fragments.

************************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,\* has gone.";
    String[] fragments = prompt.split("\*");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option i) is correct.

This code will not compile, due to the fact that \* is not a valid escape sequence. Only the following eight escape sequences are valid:

\b
\t
\n
\f
\r
\”
\’
\\

*******************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,\n has gone.";
    String[] fragments = prompt.split("\n");
    System.out.println(fragments[2]);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option h) is correct.

The split in this case only generates two String fragments, which will go in elements [0] and [1] of the fragments array. Trying to access element [2] in the fragments array will trigger an unchecked exception to be thrown.

Here is the message you encounter when you attempt to run this particular snippet of code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 2

***************************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain, has gone.";
    String[] fragments = prompt.split("x");
    System.out.println(fragments.length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option b) is correct.

When the split method of a String is invoked using an argument that doesn’t have any corresponding matches on the String in question, the entire String, which in this case is “And the rain, has gone.”, is returned as the first and only element in the array. So, at the end of this method, the fragments array will contain one, and only one, element.

**********************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "And the rain,\u has gone.";
    String[] fragments = prompt.split("\u");
    System.out.println(fragments[5]);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 5
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

Option i) is the correct answer.

It is tempting to think that the answer to this question is h), that an exception will be thrown at runtime, but in fact, this code will never make it to runtime because the darned thing does not even compile.

“\u” is not a valid escape sequence in Java, so it is not a valid entry when used as a character sequence in a String.

Only the following eight escape sequences are valid:

\b
\t
\n
\f
\r
\”
\’
\\

*************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "nnnd the rain.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments[2].length());
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 9
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

 

Option a) is the correct answer.

Even though there are consecutive matches in the prompt String, each individual match triggers a new String fragment to be added to the array. The actual matching String sequence, in this case a single “n”, does not get included in the generated fragment. Since the letter “n” is matched consecutively, there are only empty String elements placed in the array until the fourth “n” is encountered.

The five String elements in the fragment array would be (nothing after the number indicates a blank String element with a length of zero):

1:
2:
3:
4: d the rai
5: .

*************************************************

What would be the result of attempting to compile and run the following code snippet?

public static void main(String[] args) {
    String prompt = "nnnd the rain.";
    String[] fragments = prompt.split("n");
    System.out.println(fragments[3].length);
}

a) An output of 0
b) An output of 1
c) An output of 2
d) An output of 3
e) An output of 4
f)  An output of 9
g) A checked exception will be thrown at runtime
h) An unchecked exception will be thrown at runtime
i) The code will not compile

 

Option i) is the correct answer.

The object named fragments is an array of String objects. To find the number of characters in a String you invoke the length() method, not the length property. The lack of round brackets, (), after call to fragments[3].length, triggers a compile time error.

If the compile error was removed, and the problematic line of code was replaced with: System.out.println(fragments[3].length());, then the output would be the number 9.

Creating the RPS “Dashboard”

Now, one of the things I like about the Rock-Paper-Scissors application that forwards the user to one of four JSPs, win.jsp, lose.jsp, tie.jsp and failure.jsp, is the fact that it very much emphasizes the ability of Java ServerFaces to manage application flow, and control, based on the programatically determined outcome of a ‘doXYZ’ method of a managed bean, to which page a client will be directed after an interaction with the server.

However, despite my adrogodgical affection for the four or five pages Rock-Paper-Scissors application, I must confess that I think having this many pages is a bit of overkill. After all, why do we need to redirect the user to another page after they have just played a round? Why not return them to the same page, but have different content displayed on the page. That way, we can not only show the user the results of their last game, but also display the form objects, like the textfield and the submit button, that are needed to play again.

So, this is what I’m going to do. I’m going to re-jig the Rock Paper Scissors application to use just one and only one web page – the index.jsp page. And all interactions will return the user to this same JSP, albeit, each time they return, different information will appear.

Solved - Exception thrown : javax.faces.FacesException: Assertion Failed

 

If you’re getting this set of exceptions in your Java ServerFaces application, it’s probably just because you have some commandLink or commandButton objects that are not encased within h:form tags.

If you’re using JSF, make sure all of those potential form objects are withing h:form tags, and all of that needs to be within f:view or f:subview tags.

Hope this helps solve the problem!

-Cameron McKenzie

 

 

[5/5/09 14:12:03:218 PDT] 0000001d ServletWrappe E   SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: /tie.jsp. Exception thrown : javax.faces.FacesException: Assertion Failed
    at com.sun.faces.util.Util.doAssert(Util.java:1353)
    at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.encodeBegin(CommandLinkRenderer.java:200)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:717)
    at javax.faces.webapp.UIComponentTag.encodeBegin(UIComponentTag.java:595)
    at javax.faces.webapp.UIComponentTag.doEndTag(UIComponentTag.java:547)

[5/5/09 14:12:03:218 PDT] 0000001d LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
[5/5/09 14:12:03:234 PDT] 0000001d ServletWrappe E   SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: Faces Servlet. Exception thrown : javax.servlet.ServletException: Assertion Failed
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:202)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:966)

  

[5/5/09 14:12:03:250 PDT] 0000001d ServiceLogger I com.ibm.ws.ffdc.IncidentStreamImpl initialize FFDC0009I: FFDC opened incident stream file C:\_irad7\core\runtimes\base_v61\profiles\AppSrv01\logs\ffdc\server1_7c067c06_09.05.05_14.12.03_0.txt
[5/5/09 14:12:03:250 PDT] 0000001d ServiceLogger I com.ibm.ws.ffdc.IncidentStreamImpl resetIncidentStream FFDC0010I: FFDC closed incident stream file C:\_irad7\core\runtimes\base_v61\profiles\AppSrv01\logs\ffdc\server1_7c067c06_09.05.05_14.12.03_0.txt
[5/5/09 14:12:03:250 PDT] 0000001d WebApp        E   [Servlet Error]-[Faces Servlet]: javax.faces.FacesException: Assertion Failed
    at com.sun.faces.util.Util.doAssert(Util.java:1353)
    at 

[5/5/09 14:12:59:015 PDT] 00000023 FileRepositor A   ADMR0009I: Document cells/hp-000Node01Cell/applications/JSF01.ear/deltas/JSF01/delta-1241557978687 is created.
[5/5/09 14:12:59:015 PDT] 00000023 FileRepositor A   ADMR0010I: Document cells/hp-000Node01Cell/applications/JSF01.ear/deployments/JSF01/deployment.xml is modified.
[5/5/09 14:13:00:234 PDT] 0000001d ServletWrappe I   SRVE0253I: [JSF01] [/JSFWeb] [/tie.jsp]: Destroy successful.
[5/5/09 14:13:00:250 PDT] 0000001d ServletWrappe I   SRVE0242I: [JSF01] [/JSFWeb] [/tie.jsp]: Initialization successful.
[5/5/09 14:13:20:812 PDT] 0000001d ServletWrappe I   SRVE0242I: [JSF01] [/JSFWeb] [/win.jsp]: Initialization successful.
[5/5/09 14:13:20:812 PDT] 0000001d ServletWrappe E   SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: /win.jsp. Exception thrown : javax.faces.FacesException: Assertion Failed
    at com.sun.faces.util.Util.doAssert(Util.java:1353)
    at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.encodeBegin(CommandLinkRenderer.java:200)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:717)

[5/5/09 14:13:20:828 PDT] 0000001d LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
[5/5/09 14:13:20:828 PDT] 0000001d ServletWrappe E   SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: Faces Servlet. Exception thrown : javax.servlet.ServletException: Assertion Failed
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:202)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:966)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:463)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3129)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:238)

[5/5/09 14:13:20:828 PDT] 0000001d WebApp        E   [Servlet Error]-[Faces Servlet]: javax.faces.FacesException: Assertion Failed
    at com.sun.faces.util.Util.doAssert(Util.java:1353)
    at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.encodeBegin(CommandLinkRenderer.java:200)

java.io and FileStream questions

****NOTE: All of these examples should be changed to use and Array, not an ArrayList!!!

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) {
        Book scjpGuide = new Book(250);
        FileOutputStream fos = new FileOutputStream("book.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(scjpGuide);
        oos.close();
    }
}

class Page implements Serializable {
    int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option a) is correct.

Any time you deal with classes in the java.io package, there’s a good chance that they will throw a java.io.IOException.

In this case, a call to the constructor of the FileOutputStream has the potential of throwing a FileNotFoundException, and the attempt to write to the ObjectOutputStream has the potential to trigger an IOException.

Surrounding the offending method calls within a try catch block, or simply being lazy and appending a throws Exception clause to the main method would allow the code to compile and run as expected.

 

    public static void main(String args[]) throws Exception {
        try {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

******************************************************************************************

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
        Book scjpGuide = new Book(250);
        FileOutputStream fos = new FileOutputStream("book.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(scjpGuide);
        oos.close();
    }
}

class Page implements Serializable {
    int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option d) is correct.

In this example, all of the required steps that are needed to create an instance of a Book containing 250 pages, and then serialize that instance, are followed correctly.

Key points to note are that both the Page and Book classes implement the java.io.Serializable interface, and none of the properties are marked with the transient keyword. AAny attempt by the JVM to serialize an object that is not Serializable will result in a java.io.NotSerializableException being thrown at runtime.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
        try {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(fos);
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Page implements Serializable {
    int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option c) is correct.

This is a bit of a trick question, as the object passed to the writeObject method is not the scjpGuide as we would anticipate, but instead, is the instance of the FileOutputStream.

A FileOutputStream is not a serializable object, so we end up getting the following runtime exception: java.io.NotSerializableException: java.io.FileOutputStream.

It’s debatable as to whether knowing that the FileOutputStream is a serializable resource or not, so this may itself be a bit of a fringe question. However, a Java programmer should understand why a FileOutputStream would not be the type of object that could be sent across a network and used by some remote JVM. The idea of being able to serialize and deserialize a FileOutputStream is somewhat nonsensical, so a competent SCJP candidate should be able to answer this questions successfully.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page {
    int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option b) is correct.

The book contains many pages, and serializing a book means serializing the various pages of the book. However, the class Page does not implement the java.io.Serializable interface, so when an attempt is made to serialize an instance of a Book, the JVM throws the following unchecked exception: java.io.NotSerializableException: scjp.Page

Two simple strategies to fix the code would be to make the Page class implement the java.io.Serializable interface, or have the Collection of pages in the book class be marked as transient.

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page {
    transient private int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option c) is correct.

Since the Page class is not serializable, an attempt to serialize an instance of the Book class will cause the JVM to barf when an attempt is made to serialize the associate pages.

Although the instance variable in the Page class is marked as being transient, the JVM will still try to Serialize the various Page instances. To get this code to run properly, the Collection of pages would need to be made transient, or the Page class would need to implement the java.io.Serializable interface.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page implements Serializable {
    transient private int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option d) is correct.

In this case, the code will compile and run as expected, serializing a Book instance that contains 250 instances of the Page class, all tucked inside an ArrayList named pages.

One thing to note is that the int variable called number in the page class is marked as being transient. As a result, when each Page instance is serialized, the Page number data will not be saved, and the value will be lost until a de-serialized object explicitly sets the number. Transient variables and instances are not saved when an instance is Serialized, and correspondingly, the data is not re-initialized when an instance is de-serialized.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    public transient Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page implements Serializable {
    public int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option e) is correct.

Since the variable named pages is marked as being transient, the JVM will not attempt to save any of the pages that are associated with an instance of a book. As a result, the writeObject call to the ObjectOutputStream will serialize an instance of the Book class, but no associated Page objects will be serialized.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    public Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

transient class Page implements Serializable {
    public int number;
    Page(int number){this.number=number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option a) is correct.

In this case, the Page class is decorated with the transient keyword; this is not allowed. Classes can only be marked with the public, abstract and final keywords.

 

******************************************************************************************

 

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    transient Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page implements Serializable {
    public transient int number;
    Page(int number){this.number=number;}
    public transient int getNumber() {return number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option a) is correct.

Methods cannot be decorated with the transient keyword, as the getNumber method in the Page class is, causing a compile error.

 

******************************************************************************************

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    public Collection pages = new java.util.ArrayList();
    Book(int numberOfPages){
         for(int i = 0; i<numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page implements Serializable {
    public static transient int number;
    Page(int number){this.number=number;}
    public  int getNumber() {return number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option d) is correct.

This code snippet is really checking to see if you know whether or not a static variable can be transient or not – which of course, it can.

In this case, the pages numbers are transient, but each page will still be serialized when the instance of the Book is serialized, making for one serialized book containing 250 pages.

It should be noted that the use of this.number, given that the number variable is static, will generate a warning when the code is compiled, as we are referencing a static variable as though it were an instance variable. However, that doesn’t stop the code from compiling, and our compiled code will certainly run.

 

******************************************************************************************

What is the result of attempting to compile and run the following code:

package scjp;
import java.io.*;
import java.util.*;
public class Book implements Serializable {

    public Collection pages;
    Book(int numberOfPages){
         for(int i = 0; i < numberOfPages; i++){
            pages.add(new Page(i));
        }
    }
    public static void main(String args[]) throws Exception {
            Book scjpGuide = new Book(250);
            FileOutputStream fos = new FileOutputStream("book.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scjpGuide);
            oos.close();
    }
}

class Page implements Serializable {
    public static transient int number;
    Page(int number){this.number=number;}
    public  int getNumber() {return number;}
}

 

a) The code fails to compile

b) The code compiles but throws a checked exception at runtime

c) The code compiles but throws an unchecked exception at runtime

d) The code compiles, runs, and saves an instance of a book with 250 pages

e) The code compiles, runs, and saves an instance of a book without any pages

f) he code compiles, runs, and saves 250 pages without a reference to the book

 

Option c) is correct.

The collection of pages in the book class is never initialized, so the JVM simply sets this object to null. When we attempt to add pages to the collection of pages, we end up calling a method on a null instance, and predictably, we get the infamous, unchecked, NullPointerException at runtime.

This is a bit of a tricky question. All sorts of concepts are being thrown at you, but in the end, it is something as simple as the failure to initialize an instance variable that is really at the heart of this question. Always be prepared for the slight-of-hand shell games that the makers of the SCJP exam sometimes play on exam candidates. Sometimes the most complex code can obfuscate some of the most obvious problems.

A Car has Cylinders

Tuesday, May 5, 2009

Static Navigation with JavaServer Pages JSF

So, we have seen how a basic request-response cycle happens within a JSF application. During a typical web based interaction, a web client submits a form, which invokes a ‘doXYZ’ method on a managed bean, and the managed bean returns a String from its do method which essentially describes the result of the client-server interaction. Given this String, which in our Rock Paper Scissors game was either the word “win”, “lose”, “tie” or failure, the JSF framework then looks at the appropriate navigation-rule in the faces-config.xml file to figure out which should be rendered for the client.

 

<navigation-rule>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>youwin</from-outcome>
            <to-view-id>/win.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>youlose</from-outcome>
            <to-view-id>/lose.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>tie</from-outcome>
            <to-view-id>/tie.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/failure.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

 

However, not every client-server interaction needs the facilities of a managed bean. Sometimes a web based interaction simply isn’t dynamic. Sometimes you just want to send a user back to a given page in your site. For example, when a user lands on the win, lose, tie or failure JSP page, we’d like to provide a link that asks them if they want to play again. An easy way to do this would by simply having a command button that does not specify a managed bean, but instead, directly describes a navigation outcome by its action attribute (do note that the commandButton needs to be placed within the JSF <h:form> tag):

<h:form>
<h:commandButton value="Play Again?" action="playAgain"/>
</h:form>

 

So, in this case we have a JSF commandButton with the action attribute set to playAgain. We can then simply create a navigation rule indicating that when the win.jsp generates an action of “playAgain”, then the Java ServerFaces framework should send the client to the index.jsp page. The following is the static navigation-rule for the win.jsp as it would need to appear in the faces-config.xml file.

 

<navigation-rule>

    <from-view-id>/win.jsp</from-view-id>
    <navigation-case>
        <from-outcome>playAgain</from-outcome>
        <to-view-id>/index.jsp</to-view-id>
    </navigation-case>

</navigation-rule>

 

Alternatively, on the lose.jsp page, we could use a commandLink, as opposed to a commandButton, to issue the playAgain action to the JSF framework:

<h:form>
<h:commandLink action="playAgain" >
    <h:outputText value="Would you like to play again?"/>
</h:commandLink>
</h:form>

The commandLink is a little more involved, as it requires a nested outputText tag, but in the grand scheme of things, it’s not all that much work. The navigation rule for the lose.jsp would be as follows:

<navigation-rule>

    <from-view-id>/lose.jsp</from-view-id>
    <navigation-case>
        <from-outcome>playAgain</from-outcome>
        <to-view-id>/index.jsp</to-view-id>
    </navigation-case>

</navigation-rule>

Heck, we could even put BOTH a commandLink and a commandButton on the tie.jsp:

 

<h:commandLink action="playAgain" >
    <h:outputText value="Would you like to play again?"/>
</h:commandLink>
<br/>
<h:commandButton value="Play Again?" action="playAgain"/>
</h:form>

The navigation rule entry in the faces-config.xml file for the tie.jsp would be remarkably similar to the win and lose JSP entries:

<navigation-rule>

    <from-view-id>/tie.jsp</from-view-id>
    <navigation-case>
        <from-outcome>playAgain</from-outcome>
        <to-view-id>/index.jsp</to-view-id>
    </navigation-case>

</navigation-rule>

 

Of course, you’re probably seeing a dizzying trend here with static page navigation entries that look eerily the same. Well, if you’re starting to think that there must be some way to simplify a common navigation strategy before the faces-config.xml file becomes a mile long, well, you’d be right.

 

If you have a common from-outcome that might be generated by any number of pages in your application, you can create one, single, navigation-rule that uses a ‘slash/wildcard’ in the from-view-id:

  <from-view-id>/*</from-view-id>

With this configured, any action on any page in your JSF application that triggers the playAction will automatically forward to the page specified in the to-view-id element. So, rather than coding another navigation-rule for the failure.jsp page, let’s just add in the default navigation rule:

<navigation-rule>

    <from-view-id>/*</from-view-id>
    <navigation-case>
        <from-outcome>playAgain</from-outcome>
        <to-view-id>/index.jsp</to-view-id>
    </navigation-case>

</navigation-rule>

Now, after adding a command link to the failure.jsp, we can take advantage of the default navigation case, rather than specifying another entry in the faces-config.xml file:

<h:form>
<h:commandLink action="playAgain" >
    <h:outputText value="Please try again..."/>
</h:commandLink>
</h:form>

If you really wanted to get persnickety, you could just delete the navigation rules dealing with the win, lose and tie JSP pages. I’m going to leave them in just as a reference.

 

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
  "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
  "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>

    <application>
        <locale-config>
            <default-locale>es</default-locale>
            <supported-locale>en</supported-locale>
            <supported-locale>fr</supported-locale>
        </locale-config>
    </application>
    <managed-bean>
        <managed-bean-name>rpsbean</managed-bean-name>
        <managed-bean-class>com.mcnz.jsf.bean.RPSBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>

    <navigation-rule>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>youwin</from-outcome>
            <to-view-id>/win.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>youlose</from-outcome>
            <to-view-id>/lose.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>tie</from-outcome>
            <to-view-id>/tie.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/failure.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

    <navigation-rule>
        <from-view-id>/win.jsp</from-view-id>
        <navigation-case>
            <from-outcome>playAgain</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/lose.jsp</from-view-id>
        <navigation-case>
            <from-outcome>playAgain</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/tie.jsp</from-view-id>
        <navigation-case>
            <from-outcome>playAgain</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>

    <from-view-id>/*</from-view-id>
    <navigation-case>
        <from-outcome>playAgain</from-outcome>
        <to-view-id>/index.jsp</to-view-id>
    </navigation-case>

</navigation-rule>

</faces-config>

Followers