Controlling System Access with IPTables

There might be times when you want to control outgoing or incoming traffic from a linux machine. Iptables is answer to that.

To check current settings

sudo iptables -L

To Add a rule

iptables -A OUTPUT -p tcp –dport 8000 -j DROP

Lets get into details

iptables: command

-A: Add the rule

OUTPUT: Type of rule, OUTPUT or INPUT

-p: protocol tcp/ udp

–dport: port number (8000 here)

-j: DROP or ACCEPT

So Above command tell system to not allow any outgoing traffic on port 8000.

iptables -A OUTPUT -p tcp –dport 1935 -s 1.2.1.0 -j ACCEPT

-s: source

-d: destination

The above rule states to allow outgoing packets on port 1935 to a specific IP.

If we have centos based system

Edit rules

sudo vi /etc/sysconfig/iptables

Restart

sudo /etc/init.d/iptables restart

A simple cache utility class in Java

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * This class maintains in memory cache. 
 * @author kamalmeet
 *
 */

public class CommonCache {
	
	//The map that will store the cache
	private static Map<String, Object> cache=null;
	
	private static CommonCache reportCache=new CommonCache();
	
	/**
	 * Make sure the class is singleton so only one instance is shared by all. 
	 */
	private CommonCache()
	{
		cache=Collections.synchronizedMap(new HashMap<String, Object>());
	}
	
	/**
	 * Get the singleton instance.
	 * @return
	 */
	public static CommonCache getInstance()
	{
		return reportCache;
	}
	
	/**
	 * Add new element to cache.
	 * @param key
	 * @param value
	 */
	public void addToCache(String key, Object value)
	{
		cache.put(key, value);
	}
	
	/**
	 * Remove an element from cache.
	 * @param key
	 */
	public void removeFromCache(String key)
	{
		cache.remove(key);
	}
	
	/**
	 * Clean up cache.
	 */
	public void invalidateCache()
	{
		cache=Collections.synchronizedMap(new HashMap<String, Object>());
	}
	
	/**
	 * Get the element from cache.
	 * @param key
	 * @return
	 */
	public Object getFromCache(String key)
	{
		if(cache.containsKey(key))
			return cache.get(key);
		else
			return null;
	}
	
}

Android- Select and Upload Image

Here is a simple code to select and upload image from android activity

Add layout as activity_main.xml

<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/uploadImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true" />

    <Button
        android:id="@+id/selectImageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Select Image" />

    <Button
        android:id="@+id/uploadButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload Image" />

</LinearLayout>

Complete activity class will look like

package com.example.kamalmeet.myapplication;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ImageView image;
    private static final int IMAGE_REQUEST_CODE = 10;
    private Button uploadButton;
    private Bitmap bitmap;
    private Button selectImageButton;

    // number of images to select
    private static final int PICK_IMAGE = 1;

    /**
     * called when the activity is first created
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // find the views
        image = (ImageView) findViewById(R.id.uploadImage);
        uploadButton = (Button) findViewById(R.id.uploadButton);

        // on click select an image
        selectImageButton = (Button) findViewById(R.id.selectImageButton);
        selectImageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImageFromGallery();

            }
        });

        // when uploadButton is clicked
        uploadButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new ImageUploadTask().execute();
            }
        });
    }

    /**
     * Opens dialog picker, so the user can select image from the gallery. The
     * result is returned in the method onActivityResult()
     */
    public void selectImageFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    /**
     * Retrives the result returned from selecting image, by invoking the method
     * selectImageFromGallery()
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String picturePath="";
            Log.v("************:", "image" + selectedImage);
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            bitmap=BitmapFactory.decodeFile(picturePath);
            image.setImageBitmap(bitmap);


        }
    }



    /**
     * The class connects with server and uploads the photo
     *
     *
     */
    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        private String webAddressToPost = "http://10.0.2.2:8080/GCPWeb/service/uploadImage/";

        // private ProgressDialog dialog;
        private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Uploading...");
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                URL url = new URL(webAddressToPost);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                ByteArrayBody bab = new ByteArrayBody(data, "test.jpg");
                entity.addPart("file", bab);

                entity.addPart("someOtherStringToSend", new StringBody("your string here"));

                conn.addRequestProperty("Content-length", entity.getContentLength() + "");
                conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());

                OutputStream os = conn.getOutputStream();
                entity.writeTo(conn.getOutputStream());
                os.close();
                conn.connect();


                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    return readStream(conn.getInputStream());
                }


            } catch (Exception e) {
                e.printStackTrace();
                // something went wrong. connection with the server error
            }
            return null;
        }


        private String readStream(InputStream in) {
            BufferedReader reader = null;
            StringBuilder builder = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return builder.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "file uploaded",
                    Toast.LENGTH_LONG).show();
        }

    }

}

And in gradle dependencies add

   compile 'org.apache.httpcomponents:httpmime:4.2.3'

Setting up new Datasource – connection pool in JBOSS 7

If you have a new JBoss 7.x (I am using 7.1.0) installation, you would like to first create an account for admin console. It is easy

1. goto Jboss server in browser (say localhost:8080)
2. Click on admin console (It will tell you to execute add-user.bat or add-user.sh which is inside jboss/bin folder)
3. You will select option a for ManagementRealm user.
4. This is tricky, when it asks for realm, you have to type ManagementRealm (I made this mistake to type something random)
5. Now provide username and password

Go to admin console and you can see existing datasources.

Creating a new datasource would require you to add driver jar file in module folder under appropriate structure, and add a module.xml. For you help, JBoss 7 comes with a preinstalled database driver which you can see under module/com/h2database/h2/main/, here you can see jar file and module.xml. I had to create org/postgresql/main/ and add jar and module.xml.

Now go to standalone.xmlunser /jboss/standalone/configuration and look for existing database drivers

<driver name=”h2″ module=”com.h2database.h2″>
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>

You will add information for your drivers here like

<driver name=”postgresql” module=”org.postgresql”>
<xa-datasource-class>
org.postgresql.xa.PGXADataSource
</xa-datasource-class>
</driver>

Similarly you will see datasource configuration for exisitng database like

<datasources>
<datasource jndi-name=”java:jboss/datasources/ExampleDS” pool-name=”ExampleDS” enabled=”true” use-java-context=”true”>
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>

Similarly you will add information for your database.

Reference:

https://developer.jboss.org/blogs/amartin-blog/2012/02/08/how-to-set-up-a-postgresql-jdbc-driver-on-jboss-7

Returning auto generated id in spring – mybatis

Faced a problem with returning the autogenerated id for new rows being created for a postgres table through spring – mybatis.

@Insert("insert into user (name) values (#{name})")
public void insertActor(User user);

One solution ofcourse was to simply get nextval from the sequence, but I wanted something cleaner where I need not be worried about multithreading issues.

Solution one Tried: One good solution found for postgres was using “Returning” keyword with Insert statement

insert into user (name) values (#{name}) Returning id;

Somehow that did not work with mybatis.

Solution that worked:

@Options(useGeneratedKeys=true, keyProperty = "userId", keyColumn="id")
@Insert("insert into user (name) values (#{name})")
public void insertActor(User user);

@Options, with useGeneratedKeys flag worked just fine. keyProperty defined the property name in Java and keyColumn name defined name of column in table.

Branch predictor

Whenever in our code a conditional statement is executed, Branch Precitor tries to predict which way the flow will go and executes that even before conditional statement actually returns the output. This is done to stop wastage of time in waiting for conditional statement execution.


From wikipedia
– In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Here is a good example to see what Branch predictor can do

package Permissions.Permissions;

import java.util.Arrays;
import java.util.Random;

public class test {

public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];

Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c) data[c] = rnd.nextInt() % 256; // !!! With this, the next loop runs faster // Arrays.sort(data); // Test long start = System.nanoTime(); long sum = 0; for (int i = 0; i < 100000; ++i) { // Primary loop for (int c = 0; c < arraySize; ++c) { if (data[c] >= 128)
sum += data[c];
}
}

System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}

}

Try uncommenting the sort array part and see the difference.

Source- stackoverflow

Java- How to read an xlsx file

Here is a sample code to read xlsx file from java

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UploadSchools {

public static void main(String s[])
{
UploadSchools u=new UploadSchools();
u.readExcel(“/home/kamalmeet/schools.xlsx”);
}

public void readExcel(String path)
{
try{

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
Row currentRow = rows.next();

Iterator cells = currentRow.cellIterator();
while (cells.hasNext()) {

Cell currentCell = cells.next();
System.out.print(currentCell.toString()+”\t”);
}
System.out.println(“”);
}
workBook.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Note that I am simply printing string value of the cells. You can check the cell type and read the value accordingly. For example, add following utility method

private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + “”;
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + “”;
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + “”;
}
else {
return null;
}
}

References :

http://stackoverflow.com/questions/12526310/returning-decimal-instead-of-string-poi-jar

http://java67.blogspot.in/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html

Aspect Oriented Programming- Implementation

In my last post I talked about AOP basics. Here I will try to take up aspectj implementation of AOP.

Continuing from last example where I had a simple employee class.

public class Employee {
int id;
String name;

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
System.out.println(“Employee:”+ name+” is working”);
}
}

In last post I mentioned how Employee will need to maintain a bookKeeper to maitain start and end work. Whereas same can be achived throuogh AOP in a cleaner way, that is without disturbing Employee at all.

You will need to add aspectj libraries. If you are using Maven it is easy


org.aspectj
aspectjrt
RELEASE


org.aspectj
aspectjtools
RELEASE

If you are using spring, you will need to tell config file that I am using aspects. In my case I am using java based configuration so I will add following in config file.
@Configuration
@EnableAspectJAutoProxy

And then modify your BookKeeper code to tell it that it should execute its methods before and after any class’s method under test package executes.

@Component
@Aspect
public class BookKeeper {

java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
@Before(“execution(* com.test.*.*(..))”)
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new Timestamp(date.getTime()));
}

/**
* This method indicates when employee has stopped working
*/
@After(“execution(* com.test.*.*(..))”)
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new Timestamp(date.getTime()));
}

}