Showing posts with label web development. Show all posts
Showing posts with label web development. Show all posts

Thursday, February 7, 2013

Solution for jQuery plugin conflicts in Wicket

While I was working on a web application based on Wicket, I noticed that jQuery was not functioning in a way I expected. Using FireBug I noticed that a method call to a jQuery plugin failed, because it couldn't find the method. The HTML code I used in the <head>-element looks like this:

  <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="js/jquery-plugin.js"></script>
  <script type="text/javascript">

    function callbackToPlugin() {
      return function () {
        $('#plugin').callToPlugin();
      };
    }

  </script>

The code-fragment includes the jQuery file and the custom plugin file. A function is defined below that returns a callback function that calls the plugin. The code in a Wicket web page class, decides if this callback is used or not. In the code below, the call is rendered in the <head>-element, when the boolean variable "callPlugin" is true.

  @Override
  public void renderHead(IHeaderResponse response) {
    if (callPlugin) {
      response.render(
        OnDomReadyHeaderItem.forScript("$(document).ready(callbackToPlugin())"));
    }
  }

The problem with this code is that Wicket includes its embedded jQuery file in the HTML output automatically, when it detects certain JavaScript function provided by Wicket is used. In this case it includes the jQuery file AFTER the definition of the callback function. What happens is that the definition of the plugin method "callToPlugin" is lost, because the second inclusion of jQuery resets the "$" jQuery variable. This will make our call fail.

The easiest solution I found is to assign another variable to jQuery using the "jQuery.noConflict()" function.

  <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="js/jquery-plugin.js"></script>
  <script type="text/javascript">

    var $j = jQuery.noConflict();

    function callbackToPlugin() {
      return function () {
        $j('#plugin').callToPlugin();
      };
    }

    </script>

Now, the jQuery variable is "$j" instead of "$". Make sure you call the correct method from the Wicket page.

  @Override
  public void renderHead(IHeaderResponse response) {
    if (callPlugin) {
      response.render(
        OnDomReadyHeaderItem.forScript("$j(document).ready(callbackToPlugin())"));
    }
  }

If you have a better solution for this, please let me know in the comments.

Monday, November 5, 2012

Login twice in Wicket

Since the last time I upgraded my Wicket application, I noticed I had to login twice to be authenticated in the application. After careful research using the number one research tool (Google), I found the cause of this problem. The problem is that my login page is stateless. Wicket will create a temporary dummy session for stateless pages, which will not be saved internally in the session store. The solution is to let the session stick after authentication by calling bind in the session:
@Override
public boolean authenticate(String userName, String password) {
    // Your authentication code here...

    // Only reach this when authenticated...

    if (isTemporary()) {
        bind();
    }
}

Saturday, November 3, 2012

Reload JQuery when DOM is changed by Wicket/AJAX

I'm using many jQuery plugins in my Wicket application. When Wicket AjaxBehaviors change the DOM of the page, the initial changes made by the jQuery plugins are often lost. To solve this, we have to initiate the jQuery plugins again when the AjaxBehavior executes. We can do that by appending the plugin initialization JavaScript code like below:
aTextField.add(new OnChangeAjaxBehavior() {
    @Override
    protected void onUpdate(AjaxRequestTarget target) {
        target.add(aContainerThatIsRefreshed);
        target.appendJavaScript("$('.jQueryPluginClass').initiatePlugin();");
    }
});
Change the ".jQueryPluginClass" CSS class, and ".initiatePlugin()" plugin call for your specific project.

Thursday, July 26, 2012

Custom Wicket FeedbackPanel markup

I had to add custom static markup to the Wickets FeedBackPanel for a project I'm currently working on. The markup has to be visible only when the the feedback panel itself is visible. The easiest way to do this is to extend the original class, and provide a corresponding HTML file with the custom markup.
package com.javaeenotes;

import org.apache.wicket.feedback.IFeedbackMessageFilter;
import org.apache.wicket.markup.html.panel.FeedbackPanel;


public class ErrorPanel extends FeedbackPanel {
    private static final long serialVersionUID = 1L;


    public ErrorPanel(String id, IFeedbackMessageFilter filter) {
        super(id, filter);
    }


    public ErrorPanel(String id) {
        super(id);
    }
}
<wicket:panel>
  <div class="feedbackPanel" wicket:id="feedbackul">
    <b>Error</b>
    <div class="errorlevel" wicket:id="messages">
      <span class="errorlevel" wicket:id="message">A message</span>
    </div>
  </div>
</wicket:panel>
The HTML file is basically the same as the original file. I added an error header as an example.

Friday, December 16, 2011

Running Wicket on Jetty

If you're only using the web functionality provided by an application server, or you want to optimize HTTP performance, it would be a good idea to consider embedding the Jetty HTTP server inside your application. This way, you don't even have to generate a WAR-file and a web.xml file. The application is just a basic Java application, which you can run on any server with a Java VM.

Maven setup

If you're using a Maven project, add the following dependencies to the pom-file in the "dependencies"-element in order to start working right away:

<dependency>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-hightide</artifactId>
  <version>8.0.4.v20111024</version>
</dependency>

<dependency>
  <groupId>org.apache.wicket</groupId>
  <artifactId>wicket-core</artifactId>
  <version>1.5.3</version>
</dependency>

Minimal Wicket application

For our example, we use a minimal Wicket application that consists of one page.

The ExampleWicketApplication.java file:
package com.javaeenotes;


import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;


public class ExampleWicketApplication extends WebApplication {

    @Override
    public Class<? extends Page> getHomePage() {
        return HomePage.class;
    }
}
The HomePage.java file:
package com.javaeenotes;


import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;


public class HomePage extends WebPage {
    public HomePage() {
        add(new Label("message", "Hello World!"));
    }
}
The HomePage.html file:
<html>
<body>
  <span wicket:id="message"></span>
</body>
</html>

The final class we need is a main class with the static main-method, in which we tie the Wicket servlet to the Jetty server.

The Main.java file:
package com.javaeenotes;


import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;


public class Main {
    public static void main(String[] args) {
        // Object that holds, and configures the WicketServlet.
        ServletHolder servletHolder =
                new ServletHolder(new WicketServlet());
        servletHolder.setInitParameter(
                "applicationClassName",
                "com.javaeenotes.ExampleWicketApplication");
        servletHolder.setInitParameter(
                WicketFilter.FILTER_MAPPING_PARAM, "/*");
        servletHolder.setInitOrder(1);

        // Web context configuration.
        WebAppContext context = new WebAppContext();
        context.addServlet(servletHolder, "/*");
        context.setResourceBase("."); // Web root directory.

        // The HTTP-server on port 8080.
        Server server = new Server();
        SocketConnector connector = new SocketConnector();
        connector.setPort(8080);
        server.setConnectors(new Connector[]{connector});
        server.setHandler(context);

        try {
            // Start HTTP-server.
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Run the main method in a VM, and connect to port 8080 with a browser to check that the application is working.

Thursday, May 19, 2011

Free resources associated with web clients

Imagine we have the following problem. Resources are kept open for web clients as long as the clients are using them. When they leave, the resources have to be closed.

Technically, we can say as long as the HttpSession is alive in the web container, the resources are kept open. When the HttpSession is invalidated, we need to call a method that frees the resources.

A solution is to use the HttpSessionBindingListener to solve this problem.

The idea is to create a class that implements this interface. The unbound method contains or refers to the clean-up code. Whenever resources are opened, an instance of this class is created and saved to the corresponding session. When the session invalidates, which can happen by timeout, the web container automatically calls the method of the object in order to free open resources.

The class:

package com.javaeenotes;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class Janitor implements HttpSessionBindingListener {

public void valueBound(HttpSessionBindingEvent arg0) {
;
}

public void valueUnbound(HttpSessionBindingEvent arg0) {
// Start some cleaning here.
}
}


Use the HttpSession.setAttribute() method to save an instance of this class to the session.

Saturday, May 14, 2011

Creating a Modal Window page with Apache Wicket

This post aims to clarify creating a modal window with Apache Wicket. Before continuing, minimum basic knowledge about Apache Wicket is required. A modal window is a child window on top of the main window. The modal window requires the user to interact with it, before the user can return to the main window.

The application we're developing consists of two pages:

  • The main page (LaunchPage.java and LaunchPage.html)
  • The modal window page (ModalContentPage.java and ModalWContentPage.html)

The main page defines and displays the content of a variable and it also has a link to open the modal window page.

The modal window page displays the content of the same variable. But when the modal window is closed, the variable is changed by the modal window page.

Let's start by creating the HTML-file of the main page.

<html>
<head>
<title>Launch Page</title>
</head>
<body>
<div wicket:id="modal"></div>
<span wicket:id="passValueLabel">Value of passValue variable.</span>
<a wicket:id="showModalLink">Open modal window.</a>
</body>
</html>

This page defines the modal page with id "modal". The next line is the location where the content of the variable "passValue" is displayed. Finally, a link is defined that opens the modal window.

Next, the corresponding Java class:

package com.javaeenotes;

import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.PropertyModel;

public class LaunchPage extends WebPage {

private String passValue;

@SuppressWarnings("serial")
public LaunchPage() {

passValue = "This value is passed to the modal window.";

// Display the current content of the passValue variable. The
// PropertyModel must be used, as the value can be changed.
final Label passValueLabel;
add(passValueLabel = new Label("passValueLabel",
new PropertyModel<String>(this, "passValue")));
passValueLabel.setOutputMarkupId(true);

// Create the modal window.
final ModalWindow modal;
add(modal = new ModalWindow("modal"));
modal.setCookieName("modal-1");

modal.setPageCreator(new ModalWindow.PageCreator() {
public Page createPage() {
// Use this constructor to pass a reference of this page.
return new ModalContentPage(LaunchPage.this.getPageReference(),
modal);
}
});
modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
public void onClose(AjaxRequestTarget target) {
// The variable passValue might be changed by the modal window.
// We need this to update the view of this page.
target.add(passValueLabel);
}
});
modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
public boolean onCloseButtonClicked(AjaxRequestTarget target) {
// Change the passValue variable when modal window is closed.
setPassValue("Modal window is closed by user.");
return true;
}
});

// Add the link that opens the modal window.
add(new AjaxLink<Void>("showModalLink") {
@Override
public void onClick(AjaxRequestTarget target) {
modal.show(target);
}
});
}

public String getPassValue() {
return passValue;
}

public void setPassValue(String passValue) {
this.passValue = passValue;
}
}

The class file displays the content of "passValue" and creates the modal window class with its methods. Look carefully at the code and comments in the modal window methods. We can see that the passValueLabel is expected to change in the window close callback method. We can also see that the variable is actually changed using a setter in the close button callback method. This happens when the user clicks on the close button of the modal window. Finally, an AJAX link is defined and added to the page.

The second part is the modal window page:

<html>
<head>
<title>Modal Content Page</title>
</head>
<body>
<span wicket:id="passValueLabel">Current content of passValue variable.</span>
</body>
</html>

The modal page only displays the content of the "passValue" variable. The variable is owned by the main page.

package com.javaeenotes;

import org.apache.wicket.PageReference;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

public class ModalContentPage extends WebPage {

public ModalContentPage(final PageReference modalWindowPage,
final ModalWindow window) {

// Retrieve the passValue content for display.
String passValue = ((LaunchPage) modalWindowPage.getPage())
.getPassValue();
add(new Label("passValueLabel", passValue));

// You can use the
// ((LaunchPage)modalWindowPage.getPage()).setPassValue() method to
// change the passValue variable of the launch/caller page.
}
}

This class is pretty simple. The first parameter refers to the main page that created the modal window page. Go back, and look how the modal window page is constructed in the main page. The main page is casted and the variable is retrieved using the getter-method. The content is then displayed in the modal window page.

Now run the code and the main page will look like this:



After clicking the link, the modal window page is opened:



We can see the same variable is displayed in the modal window page. Now, we close the modal window page. Because of this event, the variable is changed as instructed in the callback code:



As expected, the variable is changed in the main window.

Sunday, March 13, 2011

Thread scoped JAX-WS webservices

Like Servlets, the container uses one instance of a web service class to handle incoming web service requests, which is the default behavior. Ofcourse, you can make the web service thread-safe by adding the synchronized method to the exposed methods like the following code:

@WebService
public class ExampleWS {
public synchronized void doSomething() {
;
}

public synchronized void doSomethingElse() {
;
}
}

By doing this, you eliminate the possibility of parallel or concurrent handling of incoming requests. In order to support concurrent processing, you can mark the web service class as thread scoped by using the @ThreadScope annotation.

import org.jvnet.jax_ws_commons.thread_scope.ThreadScope;

@WebService
@ThreadScope
public class ExampleWS {
public synchronized void doSomething() {
;
}

public synchronized void doSomethingElse() {
;
}
}

The added annotation will force the container to create a new instance of the web service class for every thread (ie. every request). Instances will not be shared by threads.

Thursday, February 17, 2011

Configuring your Java web application as root (/)

By default, if you deploy an application "myWebApp" in an application server like Glassfish, the root URL is http://my.server.com:8080/myWebApp. To change this, you can use the sun-web.xml descriptor file of the application to configure the application as root application of the server. Which means that the application is accessible using the URL http://my.server.com:8080/.

Inside the sun-web.xml file, make sure the context-root element looks like this:

<context-root>/</context-root>


The document type definition (DTD) of the descriptor file can be found here.

If the web application is part of an EAR-file, make sure you configure this in application.xml. Otherwise, the setting in application.xml will override it!

To make the URL even simpler, you can ofcourse change the listen port to 80. The URL to the application will then look like this: http://my.server.com/

Wednesday, February 16, 2011

Listing Open Source Web Frameworks in Java

I've stumbled acros a nice listing of available open source web frameworks for Java:

http://java-source.net/open-source/web-frameworks.

Are there really too many Java web frameworks?

Tuesday, February 8, 2011

Building a contract-first webservice with JAX-WS

In this tutorial, we'll be building a webservice contract-first. This means we build the webservice based on a contract that already exists. This contract is the WSDL file that describes the webservice formally.

The first step is to generate JAX-WS classes using wsgen that comes with the Java EE SDK. You can find the executable in your SDK/Glassfish installation directory. We'll be using the WSDL file of an earlier blogpost. Save this file as: ExampleWSService.wsdl. If you're using Eclipse, you might want to save the files in WebContent/WEB-INF/wsdl in the project directory.


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<definitions targetNamespace="http://javaeenotes.com/"
name="ExampleWSService"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:tns="http://javaeenotes.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types>
<xsd:schema>
<xsd:import namespace="http://javaeenotes.com/" schemaLocation="ExampleWSService.xsd"/>
</xsd:schema>
</types>
<message name="sum">
<part name="parameters" element="tns:sum"/>
</message>
<message name="sumResponse">
<part name="parameters" element="tns:sumResponse"/>
</message>
<message name="greet">
<part name="parameters" element="tns:greet"/>
</message>
<message name="greetResponse">
<part name="parameters" element="tns:greetResponse"/>
</message>
<message name="multiply">
<part name="parameters" element="tns:multiply"/>
</message>
<message name="multiplyResponse">
<part name="parameters" element="tns:multiplyResponse"/>
</message>
<portType name="ExampleWS">
<operation name="sum">
<input message="tns:sum"/>
<output message="tns:sumResponse"/>
</operation>
<operation name="greet">
<input message="tns:greet"/>
<output message="tns:greetResponse"/>
</operation>
<operation name="multiply">
<input message="tns:multiply"/>
<output message="tns:multiplyResponse"/>
</operation>
</portType>
<binding name="ExampleWSPortBinding" type="tns:ExampleWS">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="sum">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="greet">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="multiply">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="ExampleWSService">
<port name="ExampleWSPort" binding="tns:ExampleWSPortBinding">
<soap:address location="http://127.0.0.1:8080/webservice/ExampleWSService"/>
</port>
</service>
</definitions>


This WSDL file imports an XSD file. Make sure this is placed in the same directory as the WSDL file, and name it ExampleWSService.xsd. Also update the location/URL in the WSDL file. This example assumes the application is called webservice and the service name is ExampleWSService.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0"
targetNamespace="http://javaeenotes.com/"
xmlns:tns="http://javaeenotes.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="greet" type="tns:greet"/>

<xs:element name="greetResponse" type="tns:greetResponse"/>

<xs:element name="multiply" type="tns:multiply"/>

<xs:element name="multiplyResponse" type="tns:multiplyResponse"/>

<xs:element name="sum" type="tns:sum"/>

<xs:element name="sumResponse" type="tns:sumResponse"/>

<xs:complexType name="greet">
<xs:sequence>
<xs:element name="arg0" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="greetResponse">
<xs:sequence>
<xs:element name="return" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="sum">
<xs:sequence>
<xs:element name="arg0" type="xs:int"/>
<xs:element name="arg1" type="xs:int"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="sumResponse">
<xs:sequence>
<xs:element name="return" type="xs:int"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="multiply">
<xs:sequence>
<xs:element name="arg0" type="xs:int"/>
<xs:element name="arg1" type="xs:int"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="multiplyResponse">
<xs:sequence>
<xs:element name="return" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:schema>


Now use the wsgen command to generate the server stubs. I generally put the complete command in a Windows batch file, so I can easily rerun the command in the future if necessary. Now, execute the following command:

wsimport -p com.javaeenotes.ws -d build/classes -s src WebContent/WEB-INF/wsdl/ExampleWSService.wsdl


This will generate all classes needed to setup the webservice. Next is to create a class that implements the webservice.


package com.javaeenotes;

import javax.jws.WebService;

import com.javaeenotes.ws.ExampleWS;

@WebService(name = "ERSService",
targetNamespace = "http://javaeenotes.com/",
serviceName = "ExampleWSService",
portName = "ExampleWSPort",
endpointInterface = "com.javaeenotes.ws.ExampleWS",
wsdlLocation = "WEB-INF/wsdl/ExampleWSService.wsdl")
public class WsImplementation implements ExampleWS {

@Override
public int sum(int arg0, int arg1) {
return 0;
}

@Override
public String greet(String arg0) {
return null;
}

@Override
public int multiply(int arg0, int arg1) {
return 0;
}
}


This class implements the webservice interface we generated from the WSDL file. Using simple annotations, we can easily deploy it without editting any deployment descriptors. Nothing more is needed for successful deployment. If you used the default URL in the WSDL file, you can now reach the webservice using this URL:

http://127.0.0.1:8080/webservice/ExampleWSService?wsdl

I recommend SOAP-UI to test the webservice.

Saturday, February 5, 2011

RESTful webservices using JAX-RS

This tutorial demonstrates how RESTful services are created using JAX-RS. We'll be using Glassfish as our primary application server. This tutorial is limited to reading representational objects. For implementation information about CRUD-operations and REST, I recommend the following online book.

The tutorial consists of the following steps:

1. Define URLs
2. Define data format
3. Configure JAX-RS in web.xml
4. Create REST POJO's
5. Test application with URLs


1. Define URLs

The first step is define the URLs we'll be using in accessing the REST objects. For this example, we define four relative URLs:

1. All departments: /departments/
2. Department by ID: /departments/{id}
3. All employees: /employees/
4. Employee by ID: /employees/{id}

The {id} is the ID parameter, which should be an integer number.


2. Define data format

In this step we have to choose how we want to format the object for the client. Commonly, this will be either XML or JSON. The latter one is definitely preferred if AJAX is handling the output. But for this tutorial, we'll be using XML.


<department id="12345">
<link rel="self" href="/departments/12345" />
<name>Solutions Development</name>
</department>



<employee id="1580">
<link rel="self" href="/employees/1580" />
<firstName>Gin Lung</firstName>
<lastName>Cheng</lastName>
<department id="12345">
<link rel="self" href="/departments/12345" />
</department>
</employee>



3. Configure JAX-RS in web.xml

Now, we need to configure the application server to support RESTful services by putting the following XML-code in the web.xml file inside the <web-app>-element:


<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rs/*</url-pattern>
</servlet-mapping>


This tells our application server that we want URLs that start with /rs/ are handled by the JAX-RS Servlet.


4. Create REST POJO's

Create the POJO's that contain the methods behind the URLs. For demonstration purposes, the output is hardcoded. Normally, content is retrieved from a database, and converted to XML with JAX-B.

DepartmentService.java

package com.javaeenotes;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/departments")
public class DepartmentService {

@GET
@Produces("application/xml")
public String showDepartments() {
// Return all departments.
return "<department id=\"12345\">"
+ "<link rel=\"self\" href=\"/departments/12345\" />"
+ "<name>Solutions Development</name>"
+ "</department>";
}

@Path("{id}")
@GET
@Produces("application/xml")
public String showDepartment(@PathParam("id") int id) {
// Return department by ID.
return "<department id=\"" + id + "\">"
+ "<link rel=\"self\" href=\"/departments/" + id + "\" />"
+ "<name>Solutions Development</name>"
+ "</department>";
}
}



EmployeeService.java

package com.javaeenotes;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/employees")
public class EmployeeService {

@GET
@Produces("application/xml")
public String showEmployees() {
// Return all employees.
return "<employee id=\"1580\">"
+ "<link rel=\"self\" href=\"/employees/1580\" />"
+ "<firstName>Gin Lung</firstName>"
+ "<lastName>Cheng</lastName>"
+ "<department id=\"12345\">"
+ "<link rel=\"self\" href=\"/departments/12345\" />"
+ "</department>"
+ "</employee>";
}

@Path("{id}")
@GET
@Produces("application/xml")
public String showEmployee(@PathParam("id") int id) {
// Return employee by ID.
return "<employee id=\"" + id + "\">"
+ "<link rel=\"self\" href=\"/employees/" + id + "\" />"
+ "<firstName>Gin Lung</firstName>"
+ "<lastName>Cheng</lastName>"
+ "<department id=\"12345\">"
+ "<link rel=\"self\" href=\"/departments/12345\" />"
+ "</department>"
+ "</employee>";
}
}



5. Test application with URLs
If you deployed your application on a default install of Glassfish on your computer, the objects can be retrieved using the following URLs:

http://localhost:8080/restfulservices/rs/departments
http://localhost:8080/restfulservices/rs/departments/12345
http://localhost:8080/restfulservices/rs/employees
http://localhost:8080/restfulservices/rs/employees/1580

If you use Firefox to do this, remember that Firefox will render XML-tags invisible. Try to view the source of the page.

Monday, January 31, 2011

SyntaxHighlighter integration in Blogger.com

In a earlier blogpost, we've talked about using SyntaxHighlighter to make your programming code snippets more readable on your web pages. This blogpost will integrate SyntaxHighlighter into a blog hosted on blogger.com (like this blog).

Simply said, SyntaxHighligther is a set of JavaScript/CSS files you have to include on your webpage. You can host it on your private server, or you can use the scripts already online. I linked to the files in the online SVN repository of SyntaxHighlighter: http://syntaxhighlighter.googlecode.com/svn-history/trunk/.

The first step is to edit the HTML template of your blog. Starting from your dashboard, go to Design and then Edit HTML. This will present a page where you can edit the template. Scroll to the end of the code, paste the following piece of code just before the </body>-tag:
<!-- START SyntaxHighlighter -->
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/shCore.css' rel='stylesheet' type='text/css'/> 
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shCore.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushCpp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushCSharp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushCss.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushJava.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushJScript.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushPhp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushPython.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushRuby.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushSql.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushVb.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushXml.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushPerl.js' type='text/javascript'></script> 
<script language='javascript'> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.1.364/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>
<!-- END SyntaxHighlighter -->

This piece of code will load the SyntaxHighlighter files, and update the markup of your code snippets enclosed by <pre> or <textarea>. Before it works, you have to mark them as code by supplying the following attributes to the mentioned two tags, like this:
<pre class="java" name="code"> ... </pre>

I have not included every syntax file available. If you need support for other programming languages, you have to extend the JavaScript code above to include them. The available scipts can be found here: http://syntaxhighlighter.googlecode.com/svn-history/trunk/Scripts/

Friday, January 14, 2011

Piwik - Web Analytics

Piwik is the open source alternative to Google Analytics. It's a GPL-licensed, real time web analytics software run on PHP and MySQL. It's not a SAAS (Software As A Service), so you have to download and install it on your own webserver.

The installation takes about five minute to complete. At the end, a JavaScript code is generated, which you need to include in the page you want to track.

For more information: http://piwik.org

Monday, September 6, 2010

SoapUI

SoapUI is a tool that has a lot in common with the tool discussed in my previous blog post. SoapUI also lets you analyze traffic. But this time, it's all about web services traffic like SOAP, and RESTful web services.

One neat feature is importing WSDL-documents in order to create automatic simulation requests. A generated request template can be filled out, before SoapUI sends it to the server. The response of the web service will be nicely printed on the screen for you to analyze. This way, you can easily test or try out your web service.



Links:

Friday, August 27, 2010

WebScarab

WebScarab is a tool created by OWASP that can be used to analyze the HTTP(S) traffic between your browser and the web server. In order to intercept traffic, you have to configure WebScarab as a proxy server in your browser. Whenever a request is send to the web server by your browser, WebScarab intercepts the request and holds it for reviewing or even modifying before actually sending the request to the web server. The complete request can be analyzed in all its detail, which includes HTTP headers.



It's a great tool for debugging complex problems or reviewing the security of your applications. Download WebScarab here.

Thursday, August 19, 2010

SyntaxHighlighter

I have a colleague, who is always monitoring 2392 blogs, 503 RSS-feeds, and 3922 websites. So he doesn't miss out on the little things that make life or work just a little bit more efficient. His laptop and PC have over 293 little tools installed, which enables him to get his work done three clicks faster than the regular guy. He is Tool Man Tony.

Yesterday, he forwarded me an e-mail notification of one of his (many) RSS-feeds, which drew my attention. It was a blog post about a syntax highlighter tool, like the one found in your favorite IDE (Integrated Development Environment). But this one is different. This one is meant for highlighting code in web pages.

The tool is called SyntaxHighlighter. It's basically JavaScript files you can include in your blog or website to highlight code fragments, which make your code much more readable. Additionally, it can also number the lines of your code fragments automatically. All of this happens client-side. A screenshot of highlighted code:



SyntaxHighlighter supports most popular programming languages. The complete list of supported languages can be found here.

Installing and using SyntaxHighLighter is easy, and consists of the following basic steps:

  1. Download the installation files here.
  2. Extract the files and include them to your web page: shCore.js and shCore.css.
  3. Add brushes (syntax files) for the languages you want to highlight.
  4. Use <pre> or <script> tags to enclose your code fragment.
  5. Call the JavaScript method SyntaxHighlighter.all() to invoke SyntaxHighlighter.

As you can see, SyntaxHighlighter is loosely coupled to your web page, and is very easy to use.

Thanks Tool Man Tony for the tip!

Official SyntaxHighlighter site: http://alexgorbatchev.com/SyntaxHighlighter/

Wednesday, June 16, 2010

Setting response MIME-type in Java ServerFaces

To set the MIME-type in JSF, use the following code in your JSP-page:

<% response.setContentType("text/plain"); %>

In this example, the MIME-type is set to plain text. The browser will treat the page as plain text and will not render the page as a HTML-page.

Here is a list of common MIME-types.

Wednesday, June 9, 2010

Getting client information in Java ServerFaces

I always log client information in JSF applications in debug mode. I use the following code in a managed bean to retrieve the IP-address, hostname and HTTP-headers from the browser.

// Get the request-object.
HttpServletRequest request = (HttpServletRequest)
(FacesContext.getCurrentInstance().
getExternalContext().getRequest());

// Get the header attributes. Use them to retrieve the actual
// values.
request.getHeaderNames();

// Get the IP-address of the client.
request.getRemoteAddr();

// Get the hostname of the client.
request.getRemoteHost();

Saturday, May 8, 2010

Java ServerFaces Tutorial

An excellent tutorial about Java ServerFaces can be found at RoseIndia.net: JSF Tutorial. I use this link regularly as reference. When I search information about how to do something in JSF, I often end up on this site. It's an excellent resource about everything related to software engineering.