Posts on this Category



Automatically Mapping JPA Entities with Netbeans

Creating the JPA entities manually can be really time consuming, specially if you’re working with a huge database with hundreds of tables. Luckily, Netbeans IDE can automatically create the entities for us, if you want to see how just follow the instructions bellow:

1 – Right click on your package -> New -> Entity Classes from Database:

New Entity Classes From Database
New Entity Classes From Database

2 – A new window will show up, but before you proceed you have to create a data source:

New Data Source
New Data Source

3 – Name it as you like and click on New Database Connection:

New Database Connection
New Database Connection

3 – You’ll be asked to select the database driver and also to provide the connection info, after that just click next and finish:

Providing Connection Info
Providing Connection Info

4 – Now you can already see a list containing your database tables, select the ones you want and click next, another screen with some options will show up but you don’t need to change anything, just hit next again and finish:

Selecting the Tables
Selecting the Tables

5 – That’s it! As you can see you already have the entities:

New Entities
New Entities

Improve Performance by Increasing Glassfish Memory

When a Glassfish domain is created it already comes with a default set of JVM options (including memory related options), as you keep working on your project your application will increasingly grow and consume more memory, until it reaches the point where the default Glassfish memory configuration isn’t appropriate to run your app anymore. If you are facing this problem you can easily increase the memory by following the instructions bellow:

1 – Open the glassfish console on your browser and click on server-config:

Glassfish Console
Glassfish Console

2 – Then click on JVM Settings:

Glassfish server-config screen
Glassfish server-config screen

3 – On the JVM Options tab these are the two options you may want to change: XX:MaxPermSize and Xmx.

Glassfish JVM Options
Glassfish JVM Options

As long as you have memory available on your server you can put any size you want here. After the modifications you just need to restart your server and you’re done!

React.js Tutorial: Consuming JavaEE RESTful Web Services

In this post I’m going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I’ve already written a post showing how to create these web services with EJB 3, if you haven’t seen it yet just click on this link for more details, but if you’re already familiar with Java EE feel free to skip it and create your owm web service.

For this tutorial I’m going to use the following service (Which is almost the same as I created on the other post):

1
2
3
4
5
6
7
8
9
10
11
@Stateless
@Path("/test")
public class WebServiceTest {
 
    @GET
    @Produces("text/plain")
    public String test() {
        return "Web Service Test";
    }
 
}

This is as simple as it gets, just a method returning a string, simple as that! If you deploy the project you’ll be able to see the text “Web Service Test” on your browser by adding /test to the end of your URL:

Java EE REST Web Service Example
Java EE REST Web Service Example

Now let’s create the React.js project to consume this web service. Again, I already have a post about how to get started with React.js, click on the link to see it, though it doesn’t say anything about how to consume web services it can still be useful for those who are not familiar with react.

Since my goal here is to just show how to consume a web service, I’ll keep the react code very simple as well, just copy the following code into your index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>
 
        <script type="text/jsx">
            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/WebServiceEJB-war/test"
                    }).then(function(data) {
                        this.setState({text: data});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });
 
            React.render(<JavaEEWSTest />, document.getElementById('component'));
 
        </script>
    </body>
</html>

As you can see I have 3 functions here: getInitialState, componentDidMount and render. They do exactly what their names sugest, the first one sets all the initial values, the second executes when the component is mounted, and the last one is responsible for rendering the component. The most important for us is the componentDidMount, that’s where the web service is called, and after it receives the response it will be assigned to the variable ‘text’.

We’re almost done, now if you execute it you will probably see the following error (you need firebug installed):

Cross-Origin Request Blocke
Cross-Origin Request Blocke

To see more details about this error click here, to solve it just add the following filter to your Java EE project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

And in the web.xml:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Perfect!! Now if you refresh the page this will be the result:

Simple React.js application getting data from Java EE REST Web Service
Simple React.js application getting data from Java EE REST Web Service

It’s really simple, but the string ‘Web Service Test’ is coming from our web service.

Hope this tutorial was helpful for you, till next time!

Example of ServletContextListener Implementation

According to Oracle official documenentation, the ServletContextListener Interface is responsible for receiving notifications about the ServletContext lifecycle changes, more specifically its initialization and destruction. This can be really helpful for developers in some specific situations, like for example when we need to execute a block of code right before the application starts or shut down.

In this short tutorial I’m going give a really simple example of a ServletContextListener Implementation.

With our Java Web project created let’s create a Java class that implements the ServletContextListener interface, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package tech.fourDev.servletContextListenerSample;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class ServletContextListenerSample implements ServletContextListener{
 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("INITIALIZED");
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("DESTROYED");
    }   
}

This is our listener, you can see that I’ve already implemented the contextInitialized and contextDestroyed methods, as the name suggests the first one will be called when the ServletContext starts and the other one when it gets destroyed.

There is just one more thing to be done before you can run your application, you need to register this listener in your web.xml:

1
2
3
<listener>
    <listener-class>tech.fourDev.servletContextListenerSample.ServletContextListenerSample</listener-class>
</listener>

Perfect! Now if you run your application you’ll see the word “INITIALIZED” printed when you deploy your project and the word “DESTROYED” when you undeploy or redeploy it.