Posts on this Category



Saving your Neural Network Training Progress

If you are familiar with Neural Networks you know that training one is very time consuming, it can take days, weeks or even months, the time will depend on the purpose of your application and the hardware you have available. But regardless of the time, you don’t want to lose the progress after training your neural network, otherwise you would have to train it again every time you run your application.

In this tutorial I’m going to show a very easy way to store and load your network data. I’m going to use Encog Framework from Heaton Reasearch, it’s a great machine learning framework, if you don’t know it yet, it’s definitely worth checking out.

So let’s get started, if you are reading this tutorial you probably already have your network ready, but for those of you who don’t, here is an example of how to create one:

BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(null, true, 2));
network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 2));
network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 1));
network.getStructure().finalizeStructure();
network.reset();

This is a really simple one, I’m not going to explain the details about this code because that’s not what this tutorial is about, but I promise I’ll write another one explaining more about it.

Now let’s suppose you spent hours training it and you don’t want to lose everything, you can solve this with just one single line of code, here is how you can save the progress:

EncogDirectoryPersistence.saveObject(new File("C:/networkData.eg"), network);

It couldn’t be easier than that! Basically, the only thing you have to do is to pass the path, the file name and the network to the EncogDirectoryPersistence.saveObject method, it will generate and save for you an .eg file containing the network data. If you check the folder after executing this line the file will probably be there.

Loading that file is equally easy, instead of creating your network like did in the example above, you just have to do call the method EncogDirectoryPersistence.loadObject passing the file you want to load, like this:

BasicNetwork network = (BasicNetwork) EncogDirectoryPersistence.loadObject(new File("C:/networkData.eg"));

That’s it! I’ve just recreated my network with the data I saved before, now I could train it a little bit more and then save it again overriding the same file.

Hope you liked the tutorial, leave a comment if you have any doubts, I’ll be very happy to help!

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!

Tutorial: Custom ListView with ImageViews and TextViews

There is no doubt that the ListView is one of the most used Android UI components, in most cases developers find themselves in a situation where they need to customize this component, instead of just showing a list of Strings on the screen they also need to show more information, an ImageView, or even a Button.

In this tutorial I’m going to show how easy it is to customize a ListView, I’ll create a Contact List app with a customized ListView that will display the contacts, instead of just showing the name it’ll also show the phone number and the picture, the result will be like the customized ListView in the image bellow:

Customized ListView
Standard ListView x Customized ListView

As you can see in the image, we’re going to use 2 TextViews and 1 ImageView in this list, so let’s start by creating our ListView component, when we create the Android project it already comes with an activity_main.xml file, that’s where we’re going to add our ListView code.

1
2
3
4
5
6
7
8
9
10
11
12
13
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
 
    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
    </ListView>
</RelativeLayout>

There’s really nothing special here, we’ve just created the ListView and gave the id “list” to it, you could give any id you want, but you should remember it, we are going to use it later.

The next step is to create another xml file that will be our custom layout, let’s call it contactlist.xml, it should look like this:

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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <ImageView
        android:src="@drawable/person"
        android:layout_width="@dimen/picture_width"
        android:layout_height="@dimen/picture_height" />
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/contactName"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
 
        <TextView
            android:id="@+id/contactPhone"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
    </LinearLayout>
</LinearLayout>

It’s just like the first one, but with a few more things, this is the layout that is going to be used to display each of ListView items, you can add as many components as you want to this file, but in this example I’ll keep it simple and use just an ImageView and two TextViews like I said before. Don’t forget to give an id to each component. You’ll also need an image to be displayed on the ImageView, pick one of your preference and put it on the drawable folder, them you should be able reference it in the ImageView src attribute.

Now that our views are done, we can go on and start writing some Java code, the first class we need to create is the Contact.java, it’ll only contain the name and phone attributes.

1
2
3
4
5
6
7
8
9
10
11
12
public class Contact {
 
    private String name;
    private String phone;
 
    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
 
    //GETTERS AND SETTERS
}

Really simple, there’s not much to explain here, all of you should already be familiar with Java.

Now we’re going to create our Adapter, this will be the class responsible for getting the data from our List and putting it into our UI components, let’s call it “ContactsAdapter”:

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
35
public class ContactsAdapter extends ArrayAdapter<Contact>{
 
    int resource;
    String response;
    Context context;
 
    public ContactsAdapter(Context context, int resource, List<Contact> items) {
        super(context, resource, items);
        this.resource=resource;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LinearLayout contactsView;
        Contact contact = getItem(position);
        if(convertView==null) {
            contactsView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(resource, contactsView, true);
        } else {
            contactsView = (LinearLayout) convertView;
        }
        TextView contactName =(TextView)contactsView.findViewById(R.id.contactName);
        contactName.setTypeface(null, Typeface.BOLD);
        contactName.setTextSize(TypedValue.COMPLEX_UNIT_PX,18);
        TextView contactPhone = (TextView)contactsView.findViewById(R.id.contactPhone);
        contactPhone.setTextSize(TypedValue.COMPLEX_UNIT_PX,14);
        contactName.setText(contact.getName());
        contactPhone.setText(contact.getPhone());
        return contactsView;
    }
}

This is a little bit more complicated, there’s quite a lot of things happening here, first note that I’m extending the class ArrayAdapter, we must do this, otherwise our application won’t recognize it as an adapter. Now let’s take a look at the getView method, in the lines 26 and 29 we’re getting the two TextViews from the contactlist.xml by its ids, at this moment we can modify every attribute of these components, as an example I modified the textSize in the lines 28 and 30 and also the typeface in the line 27. But the most important thing in this method is happening on the lines 31 and 32, that’s where I got the values “name” and “phone” from my Contact and passed them to my TextView objects.

Ok, now that we have an Adapter we should be able to write the code that will tie everything together, let’s open our MainActivity.java, we’re only going to modify the onCreate method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    ListView listView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        List<Contact> contacts = new ArrayList<Contact>();
        contacts.add(new Contact("Gloria Miller","86-(216)605-9056"));
        contacts.add(new Contact("Teresa Garrett","86-(131)666-7051"));
        contacts.add(new Contact("Jeremy Diaz","370-(899)196-6943"));
        contacts.add(new Contact("Rose Henry","420-(240)605-2163"));
        contacts.add(new Contact("Maria Kelly","62-(488)190-3222"));
 
        listView = (ListView) findViewById(R.id.list);
        ContactsAdapter adapter = new ContactsAdapter(this,
                R.layout.contactlist, contacts);
        listView.setAdapter(adapter);
    }

In this method I’m creating the contact list and adding each item to it, in this case I’ve hard-coded the data in this class, but in a real scenario it would have come from a database or a web service. Next we need to get our ListView, we’re going to get it by its id, exactly like we did before with the TextViews, and the last step is to instantiate our Adater, its constructor will receive our contactlist.xml and the data as parameters.

That’s it! Now if you run your app the result should be exactly like the image in the beginning of the post.

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.