Thursday, December 10, 2015

Swift Sliding Menu

Swift Sliding Menu

1.) First, Download the SWRevealViewController library from github

2.) Inside the folder, move the SWRevealViewController.h and SWRevealViewController.m to your project. Create a header file and insert the following line

#import "SWRevealViewController.h"

3.) You'll be needing the following ViewControllers

4.) In the storyboard, select the view which has a label SWRevealViewController and change its class to SWRevealViewController. Next, control-drag from SWRevealViewController to sw_rear.

Select the "reveal view controller set segue". Select the segue and change its identifier to "sw_rear" under the identity inspector.

Next, repeat the same procedures to connect SWRevealViewController with the navigation controller of the news view controller. Again, select “reveal view controller set segue” when prompted.Set the identifier of the segue to “sw_front”.

5.) Inside the viewdidload of the swift file of sw_front, insert the following lines of code:

if self.revealViewController() != nil { = self.revealViewController()
    menuButton.action = "revealToggle:"

6.) To be able to switch to different cell, drag to the navigation controller of the view controllers and select the “reveal view controller push controller” segue under Selection Segue.

Monday, November 02, 2015

How to handle an xmlrcp wordpress attack on nginx server

I'm not really a system administrator and these steps are just based on my personal experience in securing our own wordpress websites.

Lately there has been a lot of attacks on wordpress sites (since it's a popular framework) specially on windows machine. So we decided to migrate on a linux machine. Obviously got a lot of attacks still, one of the nasty one is a DoS (denial of service), and here's how we handled it:

  1. Install akismet plugin.
  2. Install wordfence plugin - this one is really good.
  3. If you know how to type commands on linux, run tail -f /var/log/nginx/access.log. This will should the most frequent request together with its IP take note of it and under WordFence->Blocked IPs, add it.
  4. Install and configure ip tables. 
  5. Block the ip in ip tables (INPUT section):
    sudo iptables -A INPUT -s [IP ADDRESS] -j DROP
    //or insert as a first rule
    sudo iptables -I INPUT 1 -s [IP ADDRESS] -j DROP
    //check if configured correctly
    sudo iptables -L --line-numbers
    //to remove a rule
    iptables -D INPUT [line-number]
  6. Configure nginx.conf to block xmlrpc request (make sure that you are not using it). Normally you don't. Create nginx.conf in your webroot with the following contents:
    # nginx configuration
    location /xmlrpc.php {
    deny all;
    Here's an htaccess to nginx converter, just in case you need:
  7. Setup fail2ban. Google on how-to. Here's my favorite:

How to setup a subdomain in your nginx server

Lately I've created a sub-domain for one of my website. I hope you follow this blog on how to setup your nginx wordpress site. In the same server where I host my, I've added a And here is how:

  1. I created a new folder in /var/www/subdomain where I install a new copy of wordpress. Note that /var/www/html contains my maindomain.
  2. The duplicate the config site in the blog I mentioned above (my-site), so now I have subdomain ni /etc/nginx/sites-available.
  3. Make the following modifications (first 2 lines):
    listen 80;
    listen [::]:80;
  4. Basically, you can't have 2 virtual configurations with default_server marker.
  5. Your sub domain should now be accessible.

How to setup your wordpress website in nginx server

Long ago I learned of the advantages of nginx over apache, just google it. Planned to migrate our sites but didn't manage to do it until last weekend. So here's what I did to do that:

I'm assuming you already have a functional wordpress with mysql setup and html / php files in /var/www/html (the usual).

First we need to install nginx and php:

sudo apt-get install nginx php5-fpm

Next, configure nginx virtual config, like in apache. Default config file is at /etc/nginx/sites-available/default, copy it and edit like below:

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/my-site

//modify my-site
server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www/html;
        index index.php index.html index.htm;


        location / {
                # try_files $uri $uri/ =404;
                try_files $uri $uri/ /index.php?q=$uri&$args;

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/html;

        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;

//remove default enabled site
rm /etc/nginx/sites-enabled/default

//enable my-site
ln -s /etc/nginx/sites-available/my-site /etc/nginx/sites-enabled/

//restart or reload
sudo service nginx restart
sudo service php5-fpm restart

Your website should now be up and running in nginx.

*Keep your eye on missing comma ;.

Saturday, October 24, 2015

How to copy a folder from jboss deployment to your local machine

The code below will copy a folder from a deployed application in jboss to a local folder in your machine. This is useful if you want to deploy something, perhaps a set of configuration files on your local machine on deployment.

File destinationDir = new File(destinationFolder);
if (!destinationDir.exists()) {

 //get the folder path from resource
 String sourcePath = Thread.currentThread().getContextClassLoader().getResource("./jasper").getPath();
 File sourceFile = new File(sourcePath);
 if (!sourceFile.exists()) {
  //get the vfs path
  VirtualFile vfDir = VFS.getChild("/content/"
    + ParamBean.getInstance().getProperty("meveo.moduleName", "meveo")
    + ".war/WEB-INF/classes/jasper");
  URL vfPath = VFSUtils.getPhysicalURL(vfDir);
  sourceFile = new File(vfPath.getPath());
  if (!sourceFile.exists()) {
   throw new Exception("missing source");
 //copy the resource files to local machine
 FileUtils.copyDirectory(sourceFile, destinationDir);

Friday, October 23, 2015

How to download a file from the server using javaEE

The following snippet will accept a filename in the server's directory, set it as the content of the FacesContext for the user to download.

public String downloadXMLInvoice(String fileName) {
 File file = new File(getXmlInvoiceDir().getAbsolutePath() + File.separator + fileName);
 try {
  FacesContext context = FacesContext.getCurrentInstance();
  HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
  res.setContentLength((int) file.length());
  res.addHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");

  OutputStream out = res.getOutputStream();
  InputStream fin = new FileInputStream(file);

  byte[] buf = new byte[1024];
  int sig = 0;
  while ((sig =, 0, 1024)) != -1) {
   out.write(buf, 0, sig);
 } catch (Exception e) {
  log.error(Epic failed :-) ", e.getMessage(), file.getAbsolutePath());
 return null;

Wednesday, October 21, 2015

How to use xpath to read nodes from xml file

XPath is a java library that let us read a complicated xml document with ease.

In our simple example below we have an xml that contains computers with some random tags like os.

  <lenovo model="g50">
  <lenovo model="g5040">

For example if we want to get the lenovo node with year 2014, we then need to use the xpath feature with a parameter=/computers/windows/lenovo[year/text()='2014'].

package com.broodcamp.xstream_demo;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

 * @author Edward P. Legaspi
public class XPathDemo {

 public static void main(String[] args) {
  try {
   new XPathDemo();
  } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException
    | TransformerException e) {
   // TODO Auto-generated catch block

 public XPathDemo() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
   TransformerException {
  ClassLoader classLoader = getClass().getClassLoader();
  File fXmlFile = new File(classLoader.getResource("xpath_demo.xml").getFile());

  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(fXmlFile);

  Transformer trans = TransformerFactory.newInstance().newTransformer();
  StringWriter writer = new StringWriter();
  trans.transform(new DOMSource(doc), new StreamResult(writer));
  System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));

  XPath xPath = XPathFactory.newInstance().newXPath();
  XPathExpression expr = xPath.compile("/computers/windows/lenovo[year/text()='2014']");
  Object result = expr.evaluate(doc, XPathConstants.NODE);

  NodeList nodes = (NodeList) result;

  for (int i = 0; i < nodes.getLength(); i++) {
   System.out.println("nodes: " + nodes.item(i).getTextContent());


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) {"Hello czetsuya");"@author:");"-----------------------------------------------");"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 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