Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 26 September 2023

1Z0-829 exam review

I took and passed the "1z0-829 OCP Java SE 17 Developer" exam last week. I've previously passed the 1z0-817, 1z0-810, 1z0-804 and 1z0-803 exams for the Java SE 11, 8 and 7 (Programmer I and Programmer II) certifications respectably. As a veteran of these exams I thought I'd share my experience.

Notes on the exam and the purchase

Firstly, as someone who has already achieved the 'Developer' certification on a previous version, I have become accustomed to taking 'upgrade' exams wherein the topics are specifically the changes in the language. E.g., Java SE 8 was very functional programming heavy and Java SE 11 had a lot of focus on modularity. 1z0-829 covers the entire spectrum of the language making the topics and possible questions faced much broader.

There can be confusion after purchasing the exam which I want to mention here as there was little help online. After you purchase your exam voucher you will be the administrator to that voucher. As the administrator you will need to assign that exam attempt to yourself via the Oracle Exam Attempt Administrator tool before it shows up on the Oracle University site. Also note that Pearson VUE do not support this exam. You need to schedule within the Oracle University site only.

Is this still worth doing!? I'd say so. Personally I like to take these exams as it keeps my knowledge current and fresh. Plus it looks great on the CV! With releases every 6 months and LTS versions every 3 years Oracle are keeping Java alive and kicking. Many libraries and languages have come around due to Java limitations. Oracle tend to see what is popular and put it in - and now at a more regular basis, e.g.:

  • Google Guava date libraries over java.util.Date and java.lang.Calendar classes due to lack of features - Java Date/Time API in SE 8
  • Scala functional programming - Java added this in SE 8
  • Kotlin concise language features - examples of this are the var keyword added in SE 10, records added SE 11, sealed classes in SE 17

Revision

As mentioned, the exam topics are broad covering many aspects of the language. Newer features of the language are covered so make sure you understand switch expressions, text blocks, pattern matching (with instanceof), and records. Hopefully everything else is just a refresher.

I used the following resources for my studies:

Java SE 17 Developer (1Z0-829) (Video Course) By Simon Roberts: This chap dives into the details using presentation slides, whiteboards and code examples. With 31 lessons adding up to 21 hours it may border on the excessive. There were topics he covered which he mentioned would not be on the exam (and some he didn't but weren't either! This may not be the case for you but I wouldn't spend too much time on Semaphores, Phasers or Exchangers for example). Simon is a former employee of Sun and author of exam questions, so I recommend these videos as accompanied by his whiteboard and 'question times', he does help the viewer understand more complex topics. You can also speed up the videos to reduce that 21 hour watch time!

OCP Oracle Certified Professional Java SE 17 Developer Study Guide: Exam 1Z0-829: After using Scott Selikoff and Jeanne Boyarsky's previous OCP book for SE 11 I knew what I was getting here. The writing style is very conversational, making even the more complicated subjects simple via their more human step by step guidance. Again, accompanying the book are the flashcards and over 1000 exam questions via the Wiley site. These questions are much more difficult than the actual exam, with longer code examples and more choices. My main gripe with this book is the section on Modules. The example of a zoo is quite longwinded and many of the explanations and diagrams seem unnecessary. I understood the concepts but I feel it could have been done more concisely.

There are a few program errors in both which is disappointing but nothing major. If you are unsure of something then best run it in your IDE or read the documentation to be sure.

For me I spent one month preparing for this, refreshing on some of tricky edge cases of the language that never come up in day-to-day life, and understanding the new language enhancements.

Taking the exam

This is a proctored exam taken from home. You need to make sure you personal computer can run the test software. It seems to be a browser-like full screen app that include Zoom-like web cam functionality. You cannot actually install this until the check-in. You can check-in 30 min before the exam and wait in a lobby (oddly shared with other candidates tuning their web cam settings). I was expecting to have to share evidence of my room and ID but neither were requested. The admin gave me a code at the time of my exam to start the test. I did not have any papers to hand and did not notice any drawing or note taking features to the test software. In either case, don't let yourself down by giving any doubt to your honesty and abide by the rules.

Exam difficulty

The pass mark is a little higher for this one compared to previous exams with 68% required from 50 questions. That means you need 34 from 50. The time is only 90 min so do not spend too much time on any question. There should be many questions you'll be able to identify the solution within a matter of seconds so it should level things out. I finished with 20 min spare to go over flagged answers.

Example code

I have example code for the new features (from Java SE 11 to 17) available in this repository.

Wednesday, 11 November 2020

1Z0-817 exam review

I took and passed the "1z0-817 Upgrade OCP Java 6, 7 & 8 to Java SE 11 Developer" exam this week. I previously held the OCP (Oracle Certified Professional) Java 8 (Note: Oracle renamed the OCA (Oracle Certified Associate) and OCP to Programmer I and Programmer II respectively). In this post are some of my thoughts and recommendations.

Revision

The exam topics are purposely vague. This is so Oracle can tweak the exam and test you on broader concepts.

1Z0-817 is specifically an upgrade exam from previous OCP versions to Programmer II in Java 11. Documentation and guides are more abundant for the full Programmer I and II exams (1Z0-815 and 1Z0-816) as there is a higher demand.

These two aspects make studying for 1Z0-817 more challenging. I found and used the following resources:

Oracle University: If you have the funds then the Java University subscription is a great option. Oracle added hundreds of hours of new videos this summer as part of their site and content revamp. You can pick and choose the videos relevant to the course. They also have X2 speed for twice as fast learning! You can also get access to a virtual machine (VM) to work through code examples though I personally found some of the code to be messy and overdeveloped for what I needed - stick to the videos.

java.boot.by: This is an excellent (and free) resource from Mikalai Zaikin who also hosts guides on many many other exams. His well researched descriptions and code examples are a great addition to any study plans. Additionally you can purchase questions with detailed answers from Mikalai for a very low fee.

OCP Oracle Certified Professional Java SE 11 Developer Complete Study Guide: Exam 1Z0-815, Exam 1Z0-816, and Exam 1Z0-817: As you can tell from the lengthy name this book claims to cover all three Java exams and it does it very well. Scott Selikoff and Jeanne Boyarsky's writing style is very conversational, making even the more complicated subjects simple via their more human step by step guidance. Buying the book also gives you access to 500 flashcards (meh) and over 800 exam questions via the Wiley site. These questions are much more difficult than the actual exam, with longer code examples and more choices. I read this book with the Kindle App which has a great note taking feature via highlights which I found invaluable when cramming on exam eve and exam morning.

How long you need to prepare depends on how dedicated you are. The Java Uni videos can be sped up and the book could be blitzed a chapter or two a day. My only recommendation is have more than one source for revision for a deeper understanding on any area and to ensure nothing is missed.

Taking the exam

This was the first exam I've taken at home. You need to make sure you personal computer can run the test software (PearsonVue). On exam day you will need to take photos of your workspace from all angles, plus yourself and a form of identity. Your web cam will be on for the duration of the exam but you soon forget it as you focus on the questions. Make sure no one interupts or enters the room to avoid it being thrown out. They also disallow you from reading the questions outloud. If you want to make notes or write anything down the software includes a whiteboard.

Exam difficulty

The pass mark is 61% so you need at most 49 correct from the 80 questions. With 180 minutes there is no chance you will run out of time. I passed the exam with 89% with well over an hour to spare.

I read through the resources cited above (much of it multiple times) so I was very prepared. Many questions regarding var, the new interface methods (i.e. default, static and private), how to write functional interfaces (Single Abstract Methods - SAM) and lambdas are based on rules. If you know the rules then you can eliminate wrong answers really really fast. Questions regarding the interfaces in java.util.function and the modular service provider pattern will take longer to analyse. You need to know the functional interfaces SAMs - particularly what parameters they take and what they return. You need to know the service provider pattern well so you can identify the module from minor clues. Again, if you do the preparation you'll be fine. Watch out for questions that look out of place such as a question on Threads. These are often subtly hiding a more relevant issue with the code such as a lambda issue or var misuse.


Finally, I took a lot of notes and created a lot of example code. It is available on my GitHub site.

Thursday, 21 November 2019

Compiling JAXB and JAX-WS classes with Maven in Java 11

Due to the deprecation of EE modules from SE, migrating projects to Java 11 can be somewhat trickier when you rely on Maven to compile your JAXB or JAX-WS classes. See https://jaxenter.com/jdk-11-java-ee-modules-140674.html for more information.

Here's how I got round the issues:

Dependencies


These were either the latest at time of writing, or the version that happened to work. Always check Maven Repository before throwing in dependencies - there may be a better version out there.

<javax.activation.version>1.1.1</javax.activation.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
<jaxb-runtime.version>2.3.2</jaxb-runtime.version>
<jaxb2.maven.version>2.5.0</jaxb2.maven.version>
<jaxws.tools.version>2.3.2</jaxws.tools.version>

<dependency>
<groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>${javax.activation.version}</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>${jaxb-api.version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>${jaxb-runtime.version}</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-tools</artifactId>
    <version>${jaxws.tools.version}</version>
    <scope>compile</scope>
</dependency>

JAXB


Our legacy application was using the following dependencies from org.jvnet.jaxb2 to generate the classes based on the xsds/xjc:

<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.12.2</version>

<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
<version>0.6.4</version>

I won't go into detail as to how we configured those as it's not relevant here. Importantly, even by upgrading the versions, at time of writing, these simply do not work in Java 11! Here's the working solution which uses an xjc file to create the files. If you don't have one, they are easily created. There are many xjc guides out there.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>${jaxb2.maven.version}</version>
    <executions>
        <execution>
            <id>mystuff</id>
            <goals>
                <goal>xjc</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/main/resources/xsd/</source>
                </sources>
                <packageName>my.package.name</packageName>
            </configuration>
        </execution>
    </executions>
</plugin>

JAX-WS


This is a bit different because we need the endpoints as well as the JAXB objects. Essentially we need to call wsimport differently than we would have using the fairly straightforward jaxws-maven-plugin.

<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.4.1</version>

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>${maven.exec.version}</version>
    <executions>
        <execution>
            <id>mkdir</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>mkdir</executable>
                <arguments>
                    <argument>-pv</argument>
                    <argument>target/generated-sources/wsimport</argument>
                </arguments>
            </configuration>
        </execution>
        <execution>
            <id>mystuff</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>java</executable>
                <arguments>
                    <argument>-classpath</argument>
                    <classpath/>
                    <argument>com.sun.tools.ws.WsImport</argument>
                    <argument>-extension</argument>
                    <argument>-Xnocompile</argument>
                    <argument>-wsdllocation</argument>
                    <argument>/xsd/file.wsdl</argument>
                    <argument>-s</argument>
                    <argument>target/generated-sources/wsimport</argument>
                    <argument>src/main/resources/xsd/file.wsdl</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>
</plugin>

This plugin literally creates a directory and then calls wsimport from the com.sun.tools.ws.WsImport library.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>${maven.build.helper.version}</version>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated-sources/wsimport/</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

For the code to be picked up use build-helper-maven-plugin as you normally would.

Wednesday, 11 July 2012

The Java EE server classpath is not correctly set up - server home directory is missing.

I received this error when running 'clean dist' for my Java web application from Jenkins but it can also occur in NetBeans:

The Java EE server classpath is not correctly set up - server home directory is missing.
Either open the project in the IDE and assign the server or setup the server classpath manually.
For example like this:
ant -Dj2ee.server.home=<app_server_installation_directory>

The solution I found for this was to add this line to nbproject/project.properties:

j2ee.server.home=http://localhost

After this change the build was successful.

Thursday, 3 May 2012

DriverManager.setLoginTimeout() and DriverManager.getLoginTimeout()


When attempting to connect to a data source which is unreliable, to stop the application from hanging (i.e. waiting for a response from the DriverManager,getConnection(...) method), you can use the login timeout integer. This represents a maximum time in seconds that the data source will wait when attempting to connect to the database.

Description from Oracle Java Docs:

DriverManager.setLoginTimeout ( )  - Sets the maximum time in seconds that this data source will wait while attempting to connect to a database. A value of zero specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout. When a DataSource object is created, the login timeout is initially zero.

DriverManager.getLoginTimeout( )  - Gets the maximum time in seconds that this data source can wait while attempting to connect to a database. A value of zero means that the timeout is the default system timeout if there is one; otherwise, it means that there is no timeout. When a DataSource object is created, the login timeout is initially zero. 

Wednesday, 11 April 2012

Java bubble sort with ArrayList and custom args

Bubble sort: http://en.wikipedia.org/wiki/Bubble_sort

As a bit of fun I wrote my own version of the bubble sort algorithm.

package bubblesort;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Java bubble sort example: This class shows how to sort an array list of
 * Integers using the bubble sort algorithm. Enter numbers as arguments to be
 * sorted.
 *
 * @author rsharp 9/4/12
 */
public class BubbleSort {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        if (args.length > 0) {

            ArrayList<Integer> numbersToSort = new ArrayList<Integer>();

            for (String arg : args) {
                try {
                    numbersToSort.add(Integer.parseInt(arg));
                } catch (NumberFormatException ex) {
                    System.out.println(arg + " is not a number. Please enter only numbers into the bubble sort!");
                }
            }

            //print array before sorting using bubble sort algorithm
            System.out.println("Array before the bubble sort");
            for (int i : numbersToSort) {
                System.out.print(i + " ");
            }

            //sort an array using bubble sort algorithm
            bubbleSort(numbersToSort);

            System.out.println("");

            //print array after sorting using bubble sort algorithm
            System.out.println("Array after bubble sort");
            for (int i : numbersToSort) {
                System.out.print(i + " ");
            }

        } else {
            System.out.println("Please enter a list of numbers to bubble sort!");
        }

    }

    /**
     * This method performs the bubble sort
     * @param numbersToSort
     */
    private static void bubbleSort(ArrayList<Integer> numbersToSort) {

        int temp = 0;
        for (int i = 0; i < numbersToSort.size() - 1; i++) {
            for (int j = 1; j < (numbersToSort.size() - i); j++) {
                if (numbersToSort.get(j - 1) > numbersToSort.get(j)) {
                    //swap the elements!
                    temp = numbersToSort.get(j - 1);
                    numbersToSort.set(j - 1, numbersToSort.get(j));
                    numbersToSort.set(j, temp);
                }

            }
        }
    }
}

You can run this from the command line with arguments. There is error checking for if no or incorrect arguments are sent in:

java bubblesort.BubbleSort 10 2 7 8 3 1 6 9 5 4

Thursday, 15 March 2012

Remove duplicates from an ArrayList

A way I have found of removing duplicates from a Collection is doing this is to put the list into a Set (which does not allow duplicates). If you really need the it to be a List then you can add the Set back to it:

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("test");
arrayList.add("test"); // fill the list..
// etc..
Set<String> set = new Set<String>(arrayList); // add to the set
arrayList.clear(); // clear the list
arrayList.addAll(set); // add the set back into the list without the duplicates

You can also use LinkedHashSet which preserves the order of the Collection:

Set<String> set = new LinkedHashSet<String>(arrayList);

Monday, 12 March 2012

NetBeans: Unrecognised project; missing plugin?

I recently upgraded my NetBeans to 7.1.1 from 6.8. After installation I could not open my web application projects, receiving the error: Project Name: [unrecognised project; missing plugin?].

To fix this you need to add the EAR project plugin (via Tools>Plugins). The plugin is named EJB and EAR. Once installed, the problem should no longer persist.

Wednesday, 29 February 2012

The finalize method

Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before getting collected.

Your class can provide for its finalization simply by adding a method in your class named finalize(). Your finalize() method must be declared as follows:
protected void finalize () throws throwable

The finalize() method is declared in the java.lang.Object class. Thus when you write a finalize() method for your class you are overriding the one in your superclass.

If your class's superclass has a finalize() method, then your class's finalize() method should probably call the superclass's finalize() method after it has performed any of its clean up duties. This cleans up any resources the object may have unknowingly obtained through methods inherited from the superclass.
protected void finalize() throws Throwable {
    . . .
    // clean up code for this class here
    . . .
    super.finalize();
}

Monday, 27 February 2012

Run test via code

You can run your JUnit and JWebUnit tests from your own code. The class org.junit.runner.JUnitCore provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of the type org.junit.runner.Result. This object can be used to retrieve information about the tests.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

class RunTests {

    public static void main(String args[]) {
        Result result = JUnitCore.runClasses(TestClass.class);
        for (Failure failure : result.getFailures()) {
            System.out.println("FAIL!: " + failure.toString());
        }
    }
}

http://www.vogella.de/articles/JUnit/article.html

Thursday, 23 February 2012

Target "profile-j2ee" does not exist in the project

This is an error which you can get when attempting to Profile a project in NetBeans. A solution I found is;

"It seems that something has changed in project's build script, so the project 
is only partially modified for profiling, leading to the message you've 
provided. Probably the easiest way how to enable profiling again is to undo all 
project modifications and let the Profiler to integrate with the project again.

To do it, perform following modifications:

 - in build.xml, remove <import file="nbproject/profiler-build-impl.xml"/> line
 - in ./nbproject directory, remove profiler-build-impl.xml file
 - in ./nbproject/private, remove <data 
xmlns="
http://www.netbeans.org/ns/profiler/1" version="0.4"/> line
 - (optional) remove ./nbproject/private/profiler directory to remove all 
Profiler settings related to the project

Now after clicking the Profile (Main) Project action again, the Profiler 
notifies you about build script modification and profiling should work again."


From: 
http://netbeans.org/bugzilla/show_bug.cgi?id=73742

Wednesday, 22 February 2012

copylibs doesn't support the "rebase" attribute

This can happen when a NetBeans 7.1 project opens a project with an older version of CopyLibs. The solution is;

- Tools->Libraries
- select the "Library location" that you want to fix (not the Global one)
- select the "CopyLibs Task"
- click the "Remove" button on the lower left corner
- click "Ok"

- In the project explorer right click on the "Libraries" virtual folder under
your project
- click "Add Library..."
- click the "Import" button
- select on "CopyLibs Task"
- click the "Import Library" button
- click the "Cancel" button

This can also happen the other way round i.e. when a version of NetBeans less than 7.1 opens a 7.1 project. The solution is;

- Open the file nbproject/build-impl.xml
- remove the rebase attribute and value from the line the error is coming from which is a <copylibs/> tag
 

Tuesday, 13 September 2011

Edit Glassfish JDK path

I recently downgraded my version of Java to compile code for an old project. When I started my Glassfish domain I recieved an error;

The system cannot find the path specified.

When Glassfish is installed it hard-codes its reference to your JDK location. To fix this problem I ended up having to edit a file named asenv.conf (asenv.bat in Windows). The file is located at: /usr/local/glassfish/config/ (C:\glassfish\config\ in Windows).

I 'vi'd into the file and changed the AS_JAVA attribute to my new JDK location;

vi /usr/local/glassfish/config/asenv.conf
AS_JAVA="/usr/java/jdk1.4/"

In Windows you could use these commands to comment out the old reference and add the new one;

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_24\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.4

Tuesday, 6 September 2011

Setting JAVA_HOME and PATH variables in Linux

JAVA_HOME

JAVA_HOME is the directory where your Java JDK is installed. To set this; In a Linux Terminal use the export command to set the variable.

JAVA_HOME=<path-to-java>

If your path is set to /usr/java/jdk1.6.0_24/bin/java, set it as follows:

export JAVA_HOME=/usr/java/jdk1.6.0_24/bin/java

PATH

Set this variable to run Java commands without referencing the absolute location of Java every time i.e. javac MyClass.java rather than /usr/java/jdk1.6.0_24/bin/javac MyClass.java. To do this, also in a terminal append the <path-to-java> to the PATH variable using the export command.

PATH=$PATH:/usr/java/jdk1.6.0_24/bin

To see the changes use the echo command.

echo $JAVA_HOME
echo $PATH

Thursday, 18 August 2011

Writing a unit test using JUnit

To do JUnit tests on your code you first need to include the JUnit libraries which can be retrieved from the JUnit web site (licensed under GNU).

Now you can create your test files. These should be created in the test packages package folder to keep them separate from the actual project code.

package yourprojects.somepackage;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleTest {

    // Create objects needed to perform the test i.e. mock objects
    private static ObjectToTest testObject;

    @BeforeClass
    public static void setUpClass() throws ConnectionException, SQLException {
        testObject = new ObjectToTest(); // Initialise object to test
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        // Any connections made (e.g. such as database) should be closed here
    }

    @Test
    public void testSomeMethod() throws ForumException {
        assertTrue(testObject.someMethod());
        assertIsEmpty(testObject.someMethod());
        assertNotNull(testObject.someMethod());
        assertEquals(true, testObject.someMethod());
        assertSame(new ObjectToTest(), testObject.someMethod());
    }

}

How it works

This class is testing a method (someMethod) in an object (ObjectToTest).

We start off by including all the JUnit libraries we need for the tests.

We then override the setUpClass and tearDownClass methods which organise the test environment for us. In the set up class we initialise the mock objects we need to test. In the tear down class method we close any connections we made during the testing.

Then we write the tests; I typically write one test for each result I expect e.g. testAMethodWithNullArguement(). Keeping the test methods separate makes it clearer what has failed.

The test method in the above example lists many of the more common assert methods I use depending on what kind of output I am expecting from the method being tested.

Wednesday, 17 August 2011

Writing a web unit test using JWebUnit

Firstly, you will need to include the JWebUnit library in your Java project which is available to download (and is licensed under the GNU) here. You will also need the JUnit libraries as JWebUnit is built upon it which can be downloaded here (also under the GNU license).

Then in your test packages create the web test file. I recommend putting the web test file(s) in a web test package to separate them from any JUnit test files you may also have in your test packages.

package yourproject.webtest;

import net.sourceforge.jwebunit.junit.WebTestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class WebUnitExample extends WebTestCase {

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        // set up where JWebUnit should look
        setBaseUrl("http://localhost");
        beginAt("/webapp/thenameofyourproject/");
    }

    @After
    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testAFeatureOfYourProject() {
        System.out.println("Testing a feature of the project");
        // Add some method calls to the JWebUnit API here then call asserts to see if
        // the output is correct      
    }

}

How it works

As you can see this file is very incomplete and will not do anything at the moment but for this example that doesn't matter!

setUp and tearDown are important methods as you can set up what is needed before each test and obviously, 'tear down' i.e. remove those conditions after.

As for the tests themselves, JWebUnit has many methods that can be used to traverse the page (e.g. clickButton, clickLink) and methods to manipulate page elements (e.g. setTextField, selectOption). Just as in JUnit, asserts are used to check that things are how they should be. For a list of JWebUnit methods see their API listings.

Wednesday, 3 August 2011

Using ResourceBundle

I use ResourceBundles to hold my project's properties so that I can make widespread changes to the project by changing only one value.

Examples of what I may use this for could be the project name, email address, directory structures etc. I would not use ResourceBundlesfor constants.

Below is a code example;

File: project.properties
projectName=AnExampleProject

File: Properties.java
package example.properties;
import java.util.ResourceBundle;

public class Properties {
  
   private static ResourceBundle rb = ResourceBundle.getBundle("example.properties.project");

   public static String getProjectName() {
     return rb.getString("projectName");
   }
}

How it works

All properties are put into a .properties file which can be retrieved using ResourceBundle's API. We get a ResourceBundle object by using the ResourceBundle method getBundle, using the path to the properties file as a parameter. With that object, we can then retrieve the properties using the getString method (other types are also available e.g. getInt).

The methods are made static so the properties can be retrieved without instantiating the Properties class every time.

The project name would be retrieved using Properties.getProjectName();