Tuesday, September 29, 2015

Do some initialization work after the web application initialization process

We can achieve this by using a webListener. See code below:

package com.czetsuya;

import java.text.MessageFormat;
import java.util.ResourceBundle;

import javax.inject.Inject;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.omnifaces.util.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebServletListener implements ServletContextListener {

 private static Logger log = LoggerFactory

 private transient ResourceBundle resourceBundle;

 public void contextDestroyed(ServletContextEvent arg0) {


 public void contextInitialized(ServletContextEvent arg0) {
  log.info("Hello czetsuya");
  log.info("@author: czetsuya@gmail.com");
  log.info("Web context starting...");


How to protect your page using WebFilter in JavaEE

This tutorial is to be use in conjunction with picketlink. Normally we want some pages to be accessible only after a user has logged in. In this case we need a real protection filter.

The class below filters a url path and check if there's a logged in user.

package com.czetsuya.listener;

import java.io.IOException;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.picketlink.Identity;

@WebFilter(urlPatterns = RealmProtectionFilter.REALM_BASE_URI + "/*")
public class RealmProtectionFilter implements Filter {

 public static final String REALM_BASE_URI = "/pages/secured";

 private Instance identityInstance;

 private Identity getIdentity() {
  return this.identityInstance.get();

 public void destroy() {


 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;

  boolean isAuthorized = getIdentity().isLoggedIn();

  if (isAuthorized) {
   chain.doFilter(httpRequest, httpResponse);
  } else {
   forwardAccessDeniedPage(httpRequest, httpResponse);

 private void forwardAccessDeniedPage(HttpServletRequest httpRequest,
   HttpServletResponse httpResponse) throws ServletException,
   IOException {
    .forward(httpRequest, httpResponse);

 public void init(FilterConfig filterConfig) throws ServletException {



The url /pages/secured is validated, if no we redirect to /error/accessDenied.jsf.

Friday, August 28, 2015

How to create a modularized ear project in maven

This post is one way of creating a typical javaee6 maven project that contains ear, web, ejb and api. The output of course is an ear file that contains (web, ejb and api).

How it looks like (assuming our top project is named ipiel):

*Note that ipiel, can also be a child of a another project, which could be a main project where ipiel is just a component.

How to create the 5 listed maven projects above (I'm assuming you have eclipse with maven plugin installed):
1.) ipiel (the main pom project)
  a.) In eclipse create a new maven project, skip archetype selection so it will only create a maven project that has a src folder no main/test.
  b.) groupId=com.ipiel
       version=leave the default

2.) ipiel-api (where interface is declared that is shared between ejb and web)
  a.) Right click the ipiel project and select new->maven module
  b.) Since this will contain java files, select maven-archetype-quickstart, you can filter "quickstart"
  c.) groupId=com.ipiel
       version=leave the default
  d.) Create a class Bird and add a method fly.

3.) ipiel-ejb (the backing/manage bean)
  a.) Right click the ipiel project and select new->maven module
  b.) Since this will contain java files, select maven-archetype-quickstart, you can filter "quickstart"

  c.) groupId=com.ipiel
       version=leave the default
  d.) Add dependency to ipiel-api, and implement the Bird interface, in a class let's say Eagle.

4.) ipiel-web (the ui project, where you define your xhtml files)
  a.) Right click the ipiel project and select new->maven module
  b.) In the maven filter enter "web" and select org.codehaus.mojo.archetypes webapp-javaee6.
       It's a simple web archetype and we need to add some files to it.
    1.) Add a new source folder /src/main/resources.
    2.) Inside /src/main/resources create 2 folders /META-INF and /WEB-INF
    3.) Normally we have beans.xml and web.xml inside /WEB-INF folder and /META-INF contains MANIFEST.MF
  c.) groupId=com.ipiel
       version=leave the default
  d.) Make sure that you add maven-war-plugin in pom.xml.
  <!-- In version 2.1-alpha-1, this was incorrectly named warSourceExcludes -->
  e.) The web project is also dependent on ipiel-api, since it needs to call it's backing bean from the ipiel-ejb project.

5.) ipiel-config (where I normally place persistence and resource files)
  a.) groupId=com.ipiel
       version=leave the default
  b.) Create a new maven module, and select maven-archetype-quickstart, you can filter "quickstart"
I defined where my resources are in this project:

6.) ipiel-ear (the output project)
  a.) Create a new maven module project, skip archetype selection, so we have a basic maven project
  b.) groupId=com.ipiel
       version=leave the default

Friday, July 24, 2015

Android Studio - Displaying List View Inside AlertDialog

Android Studio - Displaying List View Inside AlertDialog

1.) Follow this code:
>Note: custom_dialog_layout.xml is the layout that will pop-up
>Note: row.xml is the item used for populating row
AlertDialog.Builder  builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Holo));

builder.setTitle("Custom Dialog");

View customView = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_dialog_layout, null, false);

ListView listList1 = (ListView)customView.findViewById(R.id.listView1);
String[] stringArray1 = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter adapter1 = new MyListAdapter(MainActivity.this, R.layout.row, stringArray1);


builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {


builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {


Android Studio - Creating Material Design App Bar

Android Studio - Creating Material Design App Bar

1.) Set-up the color that we'll use for the app bar:
>Create a new xml inside values and name it color.xml
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>

2.) Using the previously declared color, change the style.xml to apply the colors:

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <!-- Customize your theme here. -->

3.) Make a tool bar:
>Create a new xml layout file and name it tool_bar.xml
<span style="font-size: x-small;"><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"

4.) Use the tool bar:
>Insert this code to wherever xml layout you want to display the tool bar

5.) Adding additional buttons inside the app bar:
>Go to menu_main.xml and add/paste the code below

Tuesday, July 07, 2015

How to generate jax-rs documentation using maven

To generate the jax-rs documentation automatically using maven, we need to add some plugins in the build section of the project's pom file.

To avoid running this plugin every time you invoke mvn install, you can create a separate profile for it.

Here's the plugin definition:




And here's the content of enunciate.xml.
<?xml version="1.0"?>
<enunciate label="novaglobalapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  <include pattern="org.broodcamp.api.rest.**" />

  <docs docsDir="restapi" title="Broodcamp REST API" />
  <c disabled="true" />
  <csharp disabled="true" />
  <obj-c disabled="true" />

Wednesday, July 01, 2015

Swift - Displaying Actionsheet for Ipad and Iphone

Swift - Displaying Actionsheet for Ipad and Iphone

A simple tutorial on making an alert view of type action sheet that works for iphone and ipad.

1.) First you'll need a button where you can attach your pop over when you're using iPad (in iPhone it not necessary). Then you'll have to create an outlet for the button (in my example i named it "btn_button") so we can determine the pop over location based on where the button is placed inside the viewcontroller.

2.) Inside the button's action, paste the following lines of code:

 let optionMenu = UIAlertController(title: "Choose Your Option", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let option1 = UIAlertAction(title: "Option 1", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            println("Option 1")
        let option2 = UIAlertAction(title: "Option ", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            println("Option 2")
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad )
            if let currentPopoverpresentioncontroller = optionMenu.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = btn_button
                currentPopoverpresentioncontroller.sourceRect = btn_button.bounds;
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.Up;
                self.presentViewController(optionMenu, animated: true, completion: nil)
            self.presentViewController(optionMenu, animated: true, completion: nil)
The code is pretty straight forward:
-First we declare a UIAlertController where we can put our buttons.
-Second we created the buttons (Option1, Option2, and Cancel) and then we add the buttons inside the alert controller.
-Last we use the UI_USER_INTERFACE_IDIOM to determine if the device/emulator is an ipad or an iphone and do the necessary presentation for each particular device.

Wednesday, June 17, 2015

How to migrate your Godaddy web hosting to DigitalOcean

Lately I've been reading some good articles about DigitalOcean as a cheap VPS option in online hosting and so I decided to try and subscribe to one.

Since my wordpress website hosting is already expiring I decided to moved the hosting to DigitalOcean and renew the domain name in Godaddy.

Here's how I point my Godaddy domain to DigitalOcean VPS hosting and migrate my wordpress website:

*You must already have a DigitalOcean account with linked payment method (can be either a credit card or paypal).
*Copy all your wordpress files from Godaddy.
*Make a backup of your wordpress database.

  1. Create a droplet in digital ocean.
    1. Distribution = 15.04 x64
    2. Applications = Wordpress 14.04
    3. I chose $5 / month
  2. Follow this article to configure your server: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-14-04.
  3. Migrating your wordpress website:
    1. Using winscp, upload your files in your server's /var/www folder.
    2. Make sure that www-data user can write to the folders where it needed to, for example uploads. Note: use chmod. Note by default the uploaded files are owned by root, use chown and change the ownership to www-data.
      1. >chown www-data:www-data /var/www -R, change the owner and group of /var/www folder from root to www-data. This is done recursively.
      2. >chmod 774, means owner and group (read, write, execute) while others (read-only).
    3. Following the tutorial in #2, you should now have phpmyadmin installed. Restore your wordpress backup.
  4. We then need to point your domain name to the new ip address in digital ocean.
    1. To get your droplet's ip address, go to your digital ocean's droplet's page 
  5. Now that you have your ip address, go to DNS, and add a domain record like this: 
  6. We are done with digital ocean and we will now point godaddy's domain to digital ocean's server.
  7. In Godaddy expand Domains tab.
  8. Chose your domain then click Manage.
  9. In Settings tab, under Nameservers click Manage.
  10. Setup Type=Custom, then add the 3 nameservers below
  11. After adding hit SAVE.
  12. You should now see the 3 name servers in the next screen.
Wait for 5minutes, then try logging-in in your linux hosting, and in the terminal run:
>whois makeupchum.com

The command above should give you your digital ocean's ip address and name servers.

And that's it! Your wordpress website must now be running in digital ocean. That's in less than 30mins :-)

Common problems I've encountered:

  1. 2 widget were broken, need to set the content again
  2. some folders are not writeable when I uploaded need to execute chmod.
Want to try DigitalOcean? Register with this link.

Thursday, June 04, 2015

How to generate wadl via maven plugin

So you've written your web service and would now want to create the wadl for it.

 Assuming you have your web project in eclipse with maven integrated this is what you have to do: 1.) Add the lines below to your pom, you may want to create it's own profile. For example api.

2.) Looking at the plugin configuration above, we now have 2 define 2 files:
<?xml version="1.0" encoding="UTF-8"?>
<applicationDocs targetNamespace="http://wadl.dev.java.net/2009/02">
 <doc xml:lang="en" title="czetsuya-tech api">czetsuya-tech api</doc>

<?xml version="1.0" encoding="UTF-8" ?>
<grammars xmlns="http://wadl.dev.java.net/2009/02" />

3.) Now all you need to do is run the command below in command prompt:
>mvn -Papi clean compile com.sun.jersey.contribs:maven-wadl-plugin:generate
// note that we use api profile as defined above.

Thursday, May 28, 2015

How to return soapFault in a jax ws web service in JavaEE

The code below is an example of how you can throw a soapFault exception when an error is encountered in your web service  call.

There are basically 2 things 2 take note, see comments in code.

//#1 - inject WebServiceContext
private WebServiceContext webServiceContext;

//#2 get the soapMessage, add a soapFault in body and throw the soapFault exception.
SOAPMessageContext jaxwsContext = (SOAPMessageContext) webServiceContext.getMessageContext();
SOAPMessage soapMsg = jaxwsContext.getMessage();
try {
 SOAPFault soapFault = soapMsg.getSOAPBody().addFault();
 Name qname = soapMsg.getSOAPPart().getEnvelope().createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
 throw new SOAPFaultException(soapFault);
} catch (SOAPException e) {
 // TODO Auto-generated catch block