Gradle to maven conversion and vice versa

How to convert maven to gradle

The first thing is, you have to install gradle. Its easy. I know you can do it.  Go to the installing guide: http://www.gradle.org/docs/current/userguide/installation.html

Now the second step is to run ‘gradle init‘ in the directory containing the POM file. This will  convert the maven build to a gradle build generating a setting.gradle file and one or  ore more build.gradle files.

Thats all.

How to convert gradle to maven

You just need to add  a maven plugin in your build.gradle.

Your build gradle should be like this-

apply plugin: 'java'
apply plugin: 'maven'

group = 'com.bazlur.app'
// artifactId is taken by default, from folder name
version = '0.1-SNAPSHOT'

dependencies {
compile 'commons-lang:commons-lang:2.3'
}

Now run ‘gradle install‘ in the build.gradle folder.

Now you will find in the build/poms subfolder, a file called pom-default.xml which will contain the dependencies.

Now its all yours, copy it, customise it add up new stuff.

How to read call logs programmatically from android

It’s fairly easy. You need add following uses-permission in android manifest to get call history programmatically.

<uses-permission android:name="android.permission.READ_CONTACTS" />

That’s all here.

And then create an activity and layout. We need to query from ContentProvider. And for that I used CursorClassLoader.

Read about CursorLoader from here:  http://developer.android.com/training/load-data-background/setup-loader.html

 

I want to load 4 properties and they are- phone Number, type of call eg. Outgoing or ingoing or missed call, Date and Time of the call and duration of the call.

So first use LoaderManager.LoaderCallbacks<Cursor> interface in your activity. It has three methods.

abstract Loader        onCreateLoader(int id, Bundle args)

//Instantiate and return a new Loader for the given ID.

abstract void      onLoadFinished(Loader loader, D data)

//Called when a previously created loader has finished its load.

abstract void      onLoaderReset(Loader loader)

//Called when a previously created loader is being reset, and thus making its data unavailable.

To initialize a query, we need to call LoaderManager.initLoader() at the very first place.

We are going to add a button and call this in that button events here and after this background framework will be initialized. As soon as the background framework is initialized, it calls your implementation of onCreateLoader(). To start the query, we have to return a CursorLoader from this method.

 


@Override
public Loader onCreateLoader(int loaderID, Bundle args) {
Log.d(TAG, "onCreateLoader() >> loaderID : " + loaderID);

switch (loaderID) {
case URL_LOADER:
// Returns a new CursorLoader
return new CursorLoader(
this,   // Parent activity context
CallLog.Calls.CONTENT_URI,        // Table to query
null,     // Projection to return
null,            // No selection clause
null,            // No selection arguments
null             // Default sort order
);
default:
return null;
}
}

 

We are going access our expected data from a Cursor. And we will get this in the onLoadFinished() method.

 


@Override
    public void onLoadFinished(Loader loader, Cursor managedCursor) {
        Log.d(TAG, "onLoadFinished()");

        StringBuilder sb = new StringBuilder();

        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);

        sb.append("<h4>Call Log Details <h4>");
        sb.append("\n");
        sb.append("\n");

        sb.append("<table>");

        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;

            int callTypeCode = Integer.parseInt(callType);
            switch (callTypeCode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "Outgoing";
                    break;

                case CallLog.Calls.INCOMING_TYPE:
                    dir = "Incoming";
                    break;

                case CallLog.Calls.MISSED_TYPE:
                    dir = "Missed";
                    break;
            }

            sb.append("<tr>")
                    .append("<td>Phone Number: </td>")
                    .append("<td><strong>")
                    .append(phNumber)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Call Type:</td>")
                    .append("<td><strong>")
                    .append(dir)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Date & Time:</td>")
                    .append("<td><strong>")
                    .append(callDayTime)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Call Duration (Seconds):</td>")
                    .append("<td><strong>")
                    .append(callDuration)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<br/>");
        }
        sb.append("</table>");

        managedCursor.close();

        callLogsTextView.setText(Html.fromHtml(sb.toString()));
    }

 

Output:

 

device-2014-04-17-013232

 

Full Source code:  https://github.com/rokon12/call-log

 

Reference: http://android2011dev.blogspot.com/2011/08/get-android-phone-call-historylog.html

How the java code gets executed and performs better?

Please bear with my attempt to inform you a little regarding the execution of Java code.

Java’s code is compiled into byte code, which Java’s virtual machine executes.  This output is an intermediate language (IL) that is neither human readable nor machine-executable. Only the virtual machine understands it.  To execute this output, the virtual machine uses a Just in Time (JIT) compiler to interpret the byte code – so is Java an interpreted language as some people describe it, or is Java a compiled language?  The answer: Java is both.  Its source code is compiled with a static compiler into byte code – and then, the JIT interprets the compiler’s output.

From the previous description, one might be tempted to conclude that the JIT hurts performance, as it compiles during execution, a design that would seem to cause Java to run slowly. This conclusion, while intuitive, is incorrect.  The JIT actually performance quite well. At run time, it compiles byte code into machine code, which is later run by the JVM.   When Java executes, it executes machine code just as native code does – so it should run – discounting the JIT’s compilation costs – as fast as native code does.

However, C/C++ is generally regarding as providing better performance than Java does. The on-the-fly nature of Java’s execution lends credence to this thinking.  Compiling a piece of code into machine code takes a non-trivial amount of time.  If a language executes similar machine instructions but does not need compilation prior to the execution of them, then one can assume that the language in question runs faster than Java does – even when Java’s machine code output is maximally optimized.  However, Java isn’t maximally optimized, but C++ is not maximally optimized either.  No compiler can match the performance a top-notch assembly programmer who is an expert at manipulating the targeted hardware – so both Java and C++ can never be maximally optimized.  Making matters worse, both languages have inherent issues. Java must bear the reality that at least some of its code has to be compiled every time that it runs, and C++ is, when it must be generic, often not fully tailored to its hardware, as Java always is.  Even with the aforementioned handicap, one still expects Java’s compilation cost to give C++ in edge every scenario outside of very poorly coded or compiled C++.

However, appearances are deceiving; the JVM is a very intelligent environment and the JIT an intelligence compiler. For example, the JVM knows which methods are called frequently, as it maintains a count of each method’s calls.  When this count exceeds a certain threshold, the method’s machine code is kept, so that the JIT does not have to compile the method when it is called again – a decision that greatly reduces the cost of translating byte code into machine code.  Furthering this performance improvement, the JIT optimizes the most frequently used code. The JIT collects statistics to determine which parts of code fit this mold. Intelligent optimization of this ilk can, as Research indicates, yield big gains. Most research states that 80% of execution time is spent executing 20% of the code (“hot code”) – so optimizing these sections of code can yield sizeable performance benefits. The JIT optimizes “hot code.” It executes these sections in a highly optimized way directly on the operating system.  To achieve this goal, the JIT uses statistics to identify the “hot code.” In fact, Java performs even more optimization than efficiently executing “hot code.” It identifies the code that it executes the most and recompiles to run more efficiently than it previously did. These optimizations allow Java to achieve, in certain situations, better performance than C++ gives, without the need to resort to dangerous compiler settings or to dangerous optimization techniques.

Few resources to read:

  1. http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/underst_jit.html
  2. http://pic.dhe.ibm.com/infocenter/java7sdk/v7r0/index.jsp?topic=%2Fcom.ibm.java.win.70.doc%2Fdiag%2Funderstanding%2Fjit_overview.html
  3. http://artiomg.blogspot.com/2011/10/just-in-time-compiler-jit-in-hotspot.html
  4. http://www.javaworld.com/article/2078635/enterprise-middleware/jvm-performance-optimization–part-2–compilers.html

I would like to thank my friend Collin Rusk for his help without which it would not be publish anyway.

Is it necessary to know everything about a programming language before starting to develop an application in it?

I want to build an application in Java that uses Swing, networking and databases (JDBC). However, the catch is that I donot know anything about these three fields. However, I do know some concepts of core java such as interfaces, inner classes, exceptions and debugging, collections, multithreading and I/O Streams.

I want to know if I “really” want to develop this application, should I wait and learn these concepts or should I jump right in? I am facing this as a severe mental handicap and would greatly appreciate some help here.

★ No

Answer by Bazlur Rahman Rokon:

So my suggestion would be, first learn a little stuff on swing, start developing the UI using swing, and then start learning few stuff on JDBC and then integrate your swing app with jdbc. And when you are little advance on these two, you may start networking stuff.
And doing all these, you will face problems, and thus you need to find more and learn more stuff to solve those problems.

Personally I loved this approach.

View Answer on Quora

Let’s play deep sleep

Do you ever take a train, bus, or cab? Do you ever fall asleep? Do you regularly miss your bus stop? Well, sleeping kit is here to help! Enter your destination into the application. When your transport is near your stop, sleeping kit will sound an alarm to alert you. If you’re asleep, the alarm will wake you up. If you’re forgetful, the alarm will remind you. Sleeping kit helps you travel more easily and effectively by removing part of the hassle.

Additionally you can share your location to anyone with sleeping kit easily.

Screenshot_2014-02-24-23-18-07_framed

You wanna give it try, right?


Get it on Google Play

Android Layout Property Initializer Plugin for IntelliJ IDEA

Well, the very first version of IntelliJ IDEA plugin that I wrote over the last two nights, is now available for public use. This is nothing big, just a little, doing for fun. Any feedback would be greatly appreciated.

General instruction

  1. First, download it from here.
  2. Just install it as you normally install plugin. Go to settings, then plugins and then click on the button named “Install from disk” and then locate it.
  3. Restart your IDE.

Now you can create an android project, create an activity and a layout. Design your layout.

Click on the image for further instruction.

output_llOElX

 

or watch in

NB: I have tested with IntelliJ IDEA 13.

Cheers!!

Update:  The plugin now available on Jet-brain plugin repository : http://plugins.jetbrains.com/plugin/7377?pr=idea

The 3rd party tools that I use in my every android application

Ormlite for Android

Well many of you love ORM (Object rational mapper). It’s just another cool orm tool simply works fine with android’s sqlite database.

Link: http://ormlite.com/sqlite_java_android_orm.shtml

RoboGuice

Who didn’t hear of Dependency Injection these days?

RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. You must love it.

Link: https://github.com/roboguice/roboguice/wiki

Log4Android

Simple Logging Wrapper Library for Android. Those who are used to with SLF4J, would love it.

Link: https://github.com/oronno/log4android

Android Asynchronous Http Client

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. It’s really handy and easy to use. It covers almost everything regarding http request response stuff. Its only 25Kb for everything.

Link: http://loopj.com/android-async-http/

Sherlock ActionBar

After android 3.0 you have notice there is a nice stuff called Action bar and most of the android application use it.  It’s a nice extension of android support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API. You gotta love it.

Link: http://actionbarsherlock.com/

A great place to learn and mingle

The Java User Group Bangladesh (JUGBD) is now formed and successfully finished its 2nd meetup in last week. We are doing great, it’s not an exaggeration.

For those who doesn’t know what is JUG, let me brief a little. Java User Groups (JUGs) are basically a group of enthusiastic people who loves java and develop product and service using Java related technology and love to share their knowledge to others. We get together in some place and then talk to each other, eat and have fun.

The primary vision of JUGBD is to continue meeting on very regular basis. As all the people are involved here are too much cool and enthusiastic, it always feels better to talk to each other and learning new things.

In August 2013, we had our first meetup. On this day, we formed the group with a few Java programmers of different software firms and with some students, both of whom were present at the event. Later we decide to have another meetup, which was held on 6th December, 2013. This time we received a huge response from the programmers here in Dhaka, a lot of them were physically present and most of them supported us. We had three speakers at this event. They gave talk on how Java technology influenced other technology, big data (Cassendra) and JVM diagnostic. All of talks were excellent.

A lot of software firm are stepping forward to help our events. Meetup 2.0 was sponsored by Therap Services, LLC. In addition, we got our sponsor for the next meetup already, which is really helpful to our community. We greatly appreciate this sort of help.

Right now, we are looking to contribute in some open source projects and thus we are looking for problems, ideas. Here is an open invitation to everybody: if you are a java programmer, enthusiastic about learning new stuff and love to talk about technologies, please join us. It’s a great opportunity for us to learn and mingle.

Android – Expandable TextView

There are so many thread in Stack overflow for expandable TextVeiw.

The idea is, initially the TextView will show a small portion of a long text and when it is clicked, it will show the rest of the text.

So here is the code that how I solved it.
Using following class:

package com.rokonoid.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
/**
 * User: Bazlur Rahman Rokon
 * Date: 9/7/13 - 3:33 AM
 */
public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 200;
    private static final String ELLIPSIS = ".....";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }

    private void setText() {
        super.setText(getDisplayableText(), bufferType);
    }

    private CharSequence getDisplayableText() {
        return trim ? trimmedText : originalText;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        bufferType = type;
        setText();
    }

    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        } else {
            return originalText;
        }
    }

    public CharSequence getOriginalText() {
        return originalText;
    }

    public void setTrimLength(int trimLength) {
        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);
        setText();
    }

    public int getTrimLength() {
        return trimLength;
    }
}

And add following line in your attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ExpandableTextView">
<attr name="trimLength" format="integer"/>
</declare-styleable>
</resources>

Put the following in your main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
 <com.rokonoid.widget.ExpandableTextView
 android:id="@+id/lorem_ipsum"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
 </LinearLayout>

And test your activity

package com.rokonoid.widget;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String yourText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                "Ut volutpat interdum interdum. Nulla laoreet lacus diam, vitae " +
                "sodales sapien commodo faucibus. Vestibulum et feugiat enim. Donec " +
                "semper mi et euismod tempor. Sed sodales eleifend mi id varius. Nam " +
                "et ornare enim, sit amet gravida sapien. Quisque gravida et enim vel " +
                "volutpat. Vivamus egestas ut felis a blandit. Vivamus fringilla " +
                "dignissim mollis. Maecenas imperdiet interdum hendrerit. Aliquam" +
                " dictum hendrerit ultrices. Ut vitae vestibulum dolor. Donec auctor ante" +
                " eget libero molestie porta. Nam tempor fringilla ultricies. Nam sem " +
                "lectus, feugiat eget ullamcorper vitae, ornare et sem. Fusce dapibus ipsum" +
                " sed laoreet suscipit. ";

        ExpandableTextView expandableTextView = (ExpandableTextView) findViewById(R.id.lorem_ipsum);
        expandableTextView.setText(yourText);

    }
}

Screenshot of textview with a small portion of long text.
Expandable TextView

Screenshot when you click on the text

Expandable TextView

How to Remove Duplicate Rows from a Table in SQL Server

Introduction

It is obvious that if somehow duplicate rows get inserted into a table, it becomes a major issue to delete those duplicate rows. So this topic will help us to delete those duplicate rows from the specific table.

Background

I used some basic T-SQL (Transact-SQL*) code to accomplish the problem. So you don’t need to worry understand the codes and even you can use just blindly.

Problem

I had a database table with duplicate rows and I wanted to get rid of it. So this is how I solved my issue.

Solution

First, say I have a table named Stores with following column.

Table_Stores

So my first select query:

SELECT * FROM Stores

And Output:

SelectQuery

Now look carefully in above figure, Stores table does contain duplicate records. Check first two columns marked with rad box. Every the columns are the same except Id.

Now let’s find out duplicate rows in a way so that we can easily understand. We are now going to add an extra column in a temporary table, let’s name it RowNumber. RowNumber will hold count of duplicate rows.

So let’s execute the following query:

WITH Temp AS
(
SELECT row_number() OVER (PARTITION BY
Slno
,Region
,Territory
,Town
,ShopName
,ShopAddress
,ShopType
,Slab
,Phone
,DmsCode
,Latitude
,Longitude ORDER BY DmsCode) AS RowNumber, *
FROM Stores
)SELECT * FROM Temp

You see, I haven’t include Id, since it’s not duplicate.

SelectQuery

Now if you look above table RowNumber column, you will able to know which records contain duplicate values on rows with RowNumber greater than 1.

Now if we want to keep unique values in the table and delete others execute following query:

WITH Temp AS
(
SELECT row_number() OVER (PARTITION BY
Slno
,Region
,Territory
,Town
,ShopName
,ShopAddress
,ShopType
,Slab
,Phone
,DmsCode
,Latitude
,Longitude
ORDER BY DmsCode) AS RowNumber, *
FROM nps_new.dbo.Stores
)
DELETE from Temp WHERE RowNumber >1
SELECT * FROM Stores ORDER BY DmsCode

If the query executes, we will find only unique values in the table.

Disclaimer:

I did not explain the queries as I assumed that people who deals with such thing already know SQL.

Random Thoughts – Caffeine

I’m worried about my personal productivity these days. I am a person who used to spend (maybe waste) time doing random things, but still worried about personal productivity. There are people that the term personal productivity meant nothing to them at all. To be honest, I do not like them. I love those people who are always calculative, thoughtful and hardworking. I am kinda person, who at least pretend to be working all the time. By the way, I’m a programmer, I used to work in a close room sitting in a chair staring at a computer screen for hours upon hours. For the common people (who are not a programmer and have no idea what does a programmer actually)  may find it too wired and crazy things and I have some friends who cannot even imagine how a man can sit such long time without moving (my longest record is 18 hours in a day). Recently I did a little digging on YouTube and found that sitting for long without moving minimize productivity. Although I do not believe in their research. I believe only coffee or tea can improve the productivity and it is my secret. You have to know how to make great coffee or a tea. I believe that most people cannot make a good coffee or tea. I make my own coffee or tea. I believe I do make the best coffee / tea, though only a few of my friends agreed. And I don’t offer coffee/tea to everybody.

I have a random thought that programmer productivity is very dependent on caffeine.

My personal productivity is exhausted due to not having coffee too much these days. I feel sleepy during the day time and used to sleep all night. By the way, this is the Holy month of Ramadan and I do fast from dawn to dusk, and that is about 15 hours. And that’s why I cannot have a lot of coffee these days.

In my own definition productivity means, some actions that accomplish goal in a timely manner.

Programmers Freedom

There is no such thing as true freedom. This is probably a true realization. In my understanding, freedom means, minimizing the level of dependence. As a programmer, we used to think we have a true freedom in computer stuff, as it seems we can do whatever we want to do. It is true, in fact, at least in theory, but in practice we simply cannot do. We think about a problem and make a conceptual design in our head to solve that particular problem, and then select a programming language to implement. This is a typical scenario.

But the problem is to map our conceptual model into a programming language. This is not an easy task to do as we are heavily dependent on programming infrastructure. Sometimes we have to wait for the language designer to update certain things (we used to joke about Java updates), and if we require additional power from the IDE, we must wait for IDE vendor. Most importa­­ntly programming language has simple and few notations that can be expressed in comparison with our natural language. Most of the cases we the programmers spent our time to find ways to express our conceptual model in terms of programming level abstractions which is difficult and not creative and more or less waste of time.

So where’s our freedom? Are we not locked in some ways.

Java Installation in Ubuntu

Method 1

Step 1: download jdk from: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

 

Step 2 : go to downloaded folder using command line terminal :

 cd ~/Download 

Step 3: install jdk

sudo tar -xzvf  jdk-7u21-linux-i586.tar.gz --directory=/usr/local/

sudo ln -s /usr/local/[jdk_folder_name]/ /usr/local/jdk

* change the folder name according to extracted jdk folder name,
 

Step 4: open .bashrc

sudo gedit .bashrc

Step 5: add following line end of the .bashrc file

export JAVA_HOME=/usr/local/jdk

Save and close .bashrc file.

Step 6: compile .bashrc file

source .bashrc

 

Step 7:  now test whether java is installed properly or not: goto terminal and time following line

java -version

if java is installed properly, java runtime information will be displayed.


if not… follow second method:
Method  2:

Step 1:  Preparing your system

First you need to remove openjdk for this run the following command from your terminal

 sudo apt-get purge openjdk*

Step 2:  If you installed java 7 from any other PPA and you are having problem with java then you have to do following steps before installing the PPA mentioned here

sudo rm /var/lib/dpkg/info/oracle-java7-installer*

sudo apt-get purge oracle-java7-installer*

sudo rm /etc/apt/sources.list.d/*java*

sudo apt-get update

Step 3:  Install oracle java 7 in ubuntu 13.04/12.10/12.04

Open the terminal and run the following commands

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

sudo apt-get install oracle-java7-installer

now give a smile :) :) :D

Executing Linux command from Java

You know Linux commands are always fun. We always play on terminals. How about executing from our favorite language java?

Then you need following class


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CommandExecutor {
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[] { "/bin/sh", "-c", command };
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader input = new BufferedReader(new InputStreamReader(
proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));

String s = null;
while ((s = input.readLine()) != null) {
sb.append(s);
sb.append("\n");
}

while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}

Now you can execute any command using this class.
For example-

public static void main(String[] args) {</pre>
String output = CommandExecutor.execute("ps aux | head -3");
 System.out.println(output);
 }

And output will in your console like:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  24600  2212 ?        Ss   Apr12   0:00 /sbin/init
root         2  0.0  0.0      0     0 ?        S    Apr12   0:00 [kthreadd]

Check out Birds Puzzle on Google Play

I have got an android app named Birds Puzzle in the android market. It is a kid friendly image slide puzzle game for Android displaying a set of bird picture slides that you move into the correct order.

 ic_luncher

Instruction:

in the very first window there is a menu, you have to press on new puzzle, and then a cover flow with different birds will appear, you have to select one. When you will select one, a new window will appear showing you the correct order of slides. And then you have to press play button in the top right corner of action bar, and puzzle will begin. You have to complete the puzzle with the time limit show in action bar. If you can solve the image within the limit, a dialog will appear showing the name of birds and a short description of birds with playing its voice.

Checkout : Birds Puzzle on Google Play

How to decompile android apk to java source code?

I wrote another post with the same title here and it got a lot of comments and people wanted to know more, and some point some visitors was confused. so here is the easiest copy-paste solution.

  1. Download dex2jar from http://code.google.com/p/dex2jar/downloads/list
  2. Extract dex2jar-version.zip to a folder. for example /home/codexplo/( for linux), or  C:\ (for windows)

unzip -x dex2jar-version.zip -d /home/codexplo

  1. use dex2jar to generate .jar file. dex2jar will generate a file named someApk-dex2jar.jar in the working folder.
   linux sh /home/codexplo/dex2jar-version/d2j-dex2jar.sh /home/codexplo/someApk.apk
   windows C:\dex2jar-version\d2j-dex2jar.bat someApk.apk
  1. use a decompiler to view the source.

that’s it

Reference : http://code.google.com/p/dex2jar/wiki/UserGuide

How to enable usb debugging in ubuntu for nexus 7

get the terminal, type:

sudo vi /etc/udev/rules.d/70-android.rules

or

sudo gedit /etc/udev/rules.d/70-android.rules

and then add the following line:

SUBSYSTEM==”usb”, ATTR{idVendor}==”18d1″, ATTR{idProduct}==”4e42″, MODE=”0666″

DNS Explained

DNS মানে হলো Domain Name System.

এটি ইন্টারনেট এর সবচেয়ে গুরুত্বপূর্ণ জিনিস। এটি ছাড়া ইন্টারনেট যেকোন মুহূর্তে ধসে পরতে বাধ্য। ডিএনএস না থাকা মানে No Internet, No facebook, No Google. সুতরাং বুঝা যাচ্ছে ডিএনএস দি-ই-ই-ই-ই-ই-ই ইম্পট্যার্ন্ট!

তাহলে ডিএনএস কি?

আমরা সবাই জানি (যারা জানি না তারা নিজ দায়িত্ব জেনে নিন) প্রত্যেকটি কম্পিউটারের একটি আইপি এড্রেস থাকে। আইপি এড্রেস এর মাধ্যমে একটা কম্পিউটার আরেকটি কম্পিউটারকে চিনতে পারে। ধরা যাক ফেইসবুক, ফেইসবুক একটা এপ্লিক্যাশান, আলোচনার সুবিধার্থে ধরে নিলাম একটা মাত্র কম্পিউটারে ফেইসবুকটি চলে, আর কম্পিউটারের একটা আইপি এড্রেস আছে। সুতরাং আমাদের যে কম্পিউটারে ফেইসবুক চলে, সেই কম্পউটারের আইপি এড্রেসটি জানতে হবে যদি আমরা ফেইসবুক ব্যবহার করে চাই। আইপি এড্রেস হতে হয় ইউনিক। দুনিয়াতে যেহেতু কোটি কোটি কম্পিউটার, সুতরাং এই আইপি এড্রেস ইউনিক করতে গিয়ে এমন হয়েছে যে আমরা যারা সাধারণ মানুষ(যারা পাই-এর মান ২০০ ঘর পর্যন্ত মনে রাখতে পারে, তারা অসাধরণ) কোন ভাবেই মনে রাখতে পারি না। যেমন ফেইসবুকের আইপি এড্রেস হলো- 173.252.110.27 গুগলের হলো 173.194.34.164. সুতরাং হাজার হাজার ওয়েব সাইট যেগুলা আমরা প্রতিনিয়ত ব্রাউজ করি সেগুলার একটা নির্দিষ্ট আইপি এড্রেস থাকে। আমাদের কারো পক্ষেই এতো আইপি এড্রেস মনে রাখা সম্ভব না। আমরা যেহেতু বুদ্ধিমান, সুতরাং একটা উপায় বের করে ফেলেছি, আর সেটিই হলো ডোমেইন নেম সিস্টেম। আমরা প্রত্যকটি আইপি এড্রেস এর জন্যে একটি করে সুন্দর নাম দিয়ে রাখি, তাতে করে আমাদের মনে রাখতে সুবিধা হয়। ডোমেইন নেম সিস্টেম হলো একটা Distributed ডাটাবেইস এবং নেটওয়ার্ক সিস্টেম যেখানে আপইপি এড্রেসের সাথে একটা নাম লেখা থাকে এবং এতে করে আমাদের ফেইসবুকের আইপি এড্রেস মনে রাখতে হয় না, আমাদের facebook.com মনে রাখলেই চলে।

এখন এটি তাহলে কিভাবে কাজ করে? আমারা যখন ব্রাউজারের এড্রেস বারে http://www.facebook.com লিখি, তখন ব্রাউজার এবং অপারেটিং সিস্টেম চিন্তা করবে, এর আইপি এড্রেস আগে তারা থেকে জানে কিনা(will first determine if they know what the ip address is already)। এটি কম্পউটারে কনফিগার করা থাকতে পারে কিংবা মেমরীতে থাকতে পারে(it could be configured in computer or it could be in memory(cache)). এখন আসি, যদি ব্রাউজার এবং অপারেটিং সিস্টেম দুটির কেও-ই না জানে, তাহলে কি হবে?

What happens next?

ব্রাউজার অপারেটিং সিস্টেম এর কাছে ডোমেইন এর আইপি এড্রেস চেয়ে বসে থাকবে, আর অপারেটিং সিস্টেম এমনভাবে কনফিগার করা থাকে যে, সে একটি Resolving Name Server এর কাছে আস্ক করে পারে ডোমেইন নেইম এর জন্যে।

Resolving Name Server এর কাজ হলো ডিএনএস লুকআপ করা। এটি ওপারেটিং সিস্টেমের সাথে কনফিগার করা থাকে।

কিন্তু Resolving Name Server আইপি এড্রেস জানতেও পারে আবার নাও জানতে পারে। অপশন দুইটা। যদি মেমরিতে থাকে থাকে, তাহলে সাথে সাথে অপারেটিং সিস্টেমকে আইপি এড্রেসটি দিয়ে দেবে। না থাকলে সাথে সাথে রুট নেইম সার্ভারক কুয়েরি করবে। কিন্তু রুট নেম সার্ভার সাথে সাথে রিপ্লাই দিবে, I don’t know. But I do know where to find the com name severs. কম নেইম সার্ভার হচ্ছে টপ লেভেল ডুমেইন নেইম সার্ভার। রিসলভিং সার্ভার রুট সার্ভার এর কাছে সব ইনফরমেশন নিয়ে কেশ করে রাখে যাতে করে দ্বিতীয় বার রুট সার্ভারের কাছে যেতে না হয়। এরপর সে টপ লেভেল ডুমেইন সার্ভারের (TLD) কাছে কুয়েরি করে। এবং যথারীতি টপ লেভেল ডুমেইন সার্ভার রিপ্লায় দেয়… a a ah.. I don’t know, But I do know where to find the facebook.com name server.

নেক্সট লেভেল নেইম সার্ভারের নাম হলো, Authoritative Name Server. সুতরাং আগের মতোই রিসলভিং সার্ভার TLD এর কাছ থেকে সব ইনফরমেশন নিয়ে Authoritative Name Server এর কাছে কুয়েরি করে, এবং সাথে সাথে Authoritative Name Server বলবে, Hey! I know where that is! Tell your browser to go to the IP address: 173.252.110.27.

রিসলভিং নেইম সার্ভার ANS এর কাছে এই ইনফরমেন নিয়ে নিজের কাছে কেশ করে রাখে এবং অপারেটিং সিস্টেমকে বলে, অপারেটিং সিস্টেম তখন আইপি ব্রাওজারকে বলে, আর ব্রাওজার সাথে সাথে সেই আইপিতে হিট করে(কানেকশান ক্রিয়েট করে,Http protocol একটা বিশাল ফিরিস্তি, পরে কোন একসময় বলবো)।

Pretty Cool, huh!!

যদিও প্রসেসটা একটু জটিল, কিন্তু নেইম সার্ভার সিস্টেম কে এমন ভাবে বানানো হয়েছে, যাতে করে এটি চোখের পলকেই কাজ করে ফেলে।

সুতরাং চারটা জিনিস, Resolving Name Server, The ROOT server, The TLD server and Authoritative Name Server.

এর কোন একটি যদি কলাপস হয়, হে হে, সাথে সাথেই সব ইন্টারনেট নাই হয়ে যাবে।

Problems with unicode encoding in spring projects

I had a problem with the encoding of Unicode characters. I developed a simple web application with support for multiple languages​​, which is called internationalization or i18n. In this application, the data were saved in a database, and then re-shown. But I get exceptions on production and it was a unicode utf-8 character encoding problem.
By the way, my application was developed using spring and hibernate and jpa2. It was kind of a nightmare and I was getting the exceptions frequently and I was completely no where-zone. At least, after searching and using many sources, I found out the solutions.

So here is the solutions–

First you need add some extra parameter in your database url. For example–

jdbc\:mysql\://localhost\:3306/mydatabase?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8

Secondary you’ve to add a filter in your web.xml

<filter>

<filter-name>CharacterEncodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>CharacterEncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

And finally you have to make sure you have added following line in your jsp pages

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

and finally follow the command in your terminal

You should now be logged into the MySQL prompt. Here type the following commands :

mysql> use user_db;

mysql> alter database user_db default character set utf8 collate utf8_unicode_ci;

Query OK, 1 row affected (0.00 sec)

This should have done it.

okay, that’s how I solved the issue.

A brief introduction of String in Java

What is string?

String is traditionally a sequence of characters. In Java string is an object and it is widely used in Java. String class is defined in java.lang package and implicitly available for all program.

String can be created in two ways.

  1. By string literal
  2. by new keyword

String literal

String literal is created by double quote, for example-

String aStrign = “A String is Created”:

each time you create an new string, the JVM first check the constant pool whether it is already in constant pool. If is already in available, JVM doesn’t create new string, instead, it just refer the old string as it is already available.

So, if we create strings like-

String a = “A”;

String b = “A”

here, first we created a string which referenced to the reference value a. now if we need another string and if we create like 2nd line of the example, JVM will first check whether there is already a string object in the constant pool which contained “A” available or not, if it is already there, no new string will be created, instead, our new string is referenced by the old one.

Now what is object pool?

Object pool is another kind of data structure managed by Java virtual machine. We all know about constant who ever writes codes in his life time. Constant pool are used for frequent access and less memory consumptions. If a constant is already available in Constant pool, JVM doesn’t need to create a new object.

By new Keyword

String can be create by new keyword as all the other objects are created. Example –

String aString = new String(“Rokon”);

Here is something we need to know.

String is immutable object. Immutable means if a object once created, it will never get changed.

So when we create a string object, it will just never get changed. So now if we assign a new value to an string, the scenario is like, for example –

aString = “A new value is assigned”;

here, a new string object will be created with the value “A new value is assigned” and the object will be referenced to aString and the previous String will be ready for garbage collector.

String concatenation : String concatenation is easy in Java, what you need to do, is adding a plus-

for example –

String firstName ="Bazlur";

String lastName = "Rahman";

int age = 45;

String textToPrint = "My Name is "+ firstName + " " + lastName + " and my age is "+ age;

System.out.println(textToPrint); 

Output: My Name is Bazlur Rahman and my age is 45

here every concatenation,a new object is created and old one gets ready for gc.

So if we need a thousand of concatenation, JVM will create thousands of new object which required huge memory. To avoid this issue, there is two Class available, they are, StringBuilder and StringBuffer.

Mutability and immutability : A long time ago, once I chatted with my friend. I think its something worthy about.

(08:08:44 PM) Bazlur Rahman: hey

(08:08:53 PM) crusk8: hey

(08:08:59 PM) Bazlur Rahman: how are u ?

(08:09:39 PM) Bazlur Rahman: do u know difference the between mutable and immutable object ?

(08:12:20 PM) crusk8: I was just looking at the idea on wikipedia. looks like the idea for immutable objects is to create an object, set to what you want, use it, and then let it alone

(08:13:16 PM) Bazlur Rahman: i have some basic idea though … but question is when to use them?

(08:14:16 PM) Bazlur Rahman: mutable object can be changed using mutator, and immutable object cant be changed… this is the main motivation ..right ..

(08:15:19 PM) crusk8: yeah. I guess you could use an immutable objects to modify other objects, but, for safety, that immutable object itself couldn’t be modified

(08:17:30 PM) Bazlur Rahman: yup.. don’t you think, immutable object is responsible for less performance.. every time, new object is created, old object is dropped, reference is changed, garbage collector is called…

(08:18:27 PM) crusk8: yeah. if you’re going to use an immutable object. you should use it cases where that object will almost never change

(08:20:10 PM) Bazlur Rahman: but is it good practice using immutable object always? because it is thread safe, I don’t need to do locking, it is protected,

(08:20:49 PM) Bazlur Rahman: and sometime it has good performance… like we dont need to make defensive copy ..

(08:21:39 PM) crusk8: you probably wouldn’t need to do locking on that object. for languages like c++ it would be const protected

(08:21:55 PM) crusk8: you only need to do locking when that object tries to modify other objects

(08:24:05 PM) Bazlur Rahman: so whats the point of using mutable or immutable object. should I always immutable object ?

(08:26:39 PM) crusk8: mutable objects are ones that need to be modified a lot. immutable ones are that rare if ever need to be modified. an immutable object could act like a controller for the mutable objects

(08:26:58 PM) crusk8: it can change them but the mutable objects can’t change it

(08:29:47 PM) Bazlur Rahman: I’m still confused, in which situation, I should use immutable object..? for security issues ?

(08:30:45 PM) crusk8: yeah. you’re the limiting the ways that an object can modified. only through reallocating the object

(08:31:03 PM) crusk8: not through mutators

(08:34:12 PM) Bazlur Rahman: hmm but it has some complexity while implementing immutable object I think ..

(08:35:23 PM) crusk8: I’m not sure if immutable means that object can’t modify its own internal variables. while processing something internal settings can;t be changed

(08:35:43 PM) crusk8: or just that the outside world can’t change things directly

(08:36:12 PM) crusk8: I suppose only data could be local to the function

By the way,

Here I’m going to tell you some advantage and disadvantage of immutable object.

Advantage:

Protection : you can send and immutable object to any class without worrying about it being altered by that class and you never have to make defensive copy.

Thread safe: Its fully thread safe, any number of threads can access them simultaneously, without any synchronization.

Disadvantage :

Constructor injection : it requires constructor injection while you are going implement inversion of control. In immutable object, there is no way to use mutator.

Implementation complexity : its very much boring to implement immutable object.

Some worthy reading list:

http://www.javatpoint.com/StringBuffer-class

http://www.javacup.co.in/stringhandling.html

10 Things about Design

  1. “Simplicity is the ultimate sophistication.” – da Vinci
  2. The best deliverable are prototypes.
  3. Sketching is the most effective design method.
  4. Creativity comes from everywhere.
  5. Design is writing.
  6. Interruption is the enemy of productivity.
  7. Being healthy leads to better work.ay
  8. A great culture is the byproduct of great behavior.
  9. Design is at the heart of great companies.
  10. Design is never done.

Courtesy: Joshua Kaufman

 

 

A list of really good user interface design resources

Here is the list of links I found from a question in Quora

  1. http://www.iconfinder.com/
  2. http://ui-cloud.com/
  3. http://fireworkswireframingkit.com/
  4. http://www.webalys.com/design-interface-application-framework.php
  5. http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
  6. http://bestblogbox.com/freebies/all-in-one-web-elements-kit/
  7. http://www.teehanlax.com/blog/ipad-gui-psd/
  8. http://bestuipsd.blogspot.in/2011/07/125-free-web-ui-element-psd-packs.html
  9. http://dribbble.com/tags/free
  10. http://365psd.com/
  11. http://www.premiumpixels.com/
  12. http://pinterest.com/exuberantfool/gui-toolkit/
  13. http://designmodo.com/freebies/
  14. http://designmodo.com/impressionist-free/
  15. http://designmodo.com/the-bricks/

 

Well-Grounded Java Developer

Reading Well-Grounded Java Developer by Benjamin J.Evans, Martijin Verburg. You must read this book if you are really  a java fanatic.

you can read the review of this book here: http://www.javaworld.com/community/node/8416

State Diagram of Java Thread

Figure:  Java thread state diagram

Runnable:  A thread becomes runnable when start() is called. It doesn’t mean that thread gets running immediately, rather it is pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

Running: A thread started its execution when scheduler picks. It runs until it is blocked or voluntarily gives up its turn with this static method Thread.yield( ).

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish. A call to current Object.wait( ) method causes the current thread to wait until some other thread invokes current Object.notify( ) or the current Object.notifyAll( ) is executed.

Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

Blocked on I/O: it moves to runnable after I/O condition like reading bytes of data etc. changes.

Blocked on synchronization: it moves to running when a lock is acquired.

Dead: The thread is finished working.

 

Chain of responsibility pattern

Pattern name: Chain of responsibility

What it is: Avoid coupling the sender of request to its receiver by giving more than one object to a chance to handle request. Chain of receiving objects and pass the request along the chain until and object handle it.

Family of patterns: Behavioral Patterns

Structure of patterns:

Figure: structure of chain of responsibility pattern

Handler— define an interface for handle request

Concrete handler— concrete handler implements the handler interface and handle the request it is responsible for if it can handle the request, otherwise it sends the request to its successor.

Clients— send the request to the first object of the chain that may handle the commands

When to use this pattern: this pattern is recommended when—

  •  Multiple objects can handle a request and the handler doesn’t have to be specific object
  •   A set of object should be able to handle a request with the handler determined at runtime
  •  A request  not being handled is an acceptable outcome

Downside: this pattern has mixed blessing. The request could reach the end of the chain and not be handled at all.

Real Life Example: let’s think a scenario; I have an email client which store email in different folders to store emails. If it is from Gmail, it will store in Gmail folder and if it is from business.com, it will store in business.com folder. So have different email handlers, they do basically same type of job. We can solve this problem using chain of responsibility pattern.

Code Example:

Interface Handler


package com.codexplo.patterns.behavioural.chainofresponsibility;

public interface EmailHandler {
public void setNext(EmailHandler emailHandler);

public void handleRequest(String email);
}


 

 

 

Concrete Handler 1


package com.codexplo.patterns.behavioural.chainofresponsibility;

public class GmailEmail implements EmailHandler {
private EmailHandler next;

@Override
public void setNext(EmailHandler emailHandler) {
this.next = emailHandler;
}

@Override
public void handleRequest(String email) {
if (email.contains("@gmail.com")) {
System.out
.println("Email is from gmail.com, so it will go in Gmail folder");
} else {
next.handleRequest(email);
}
}
}



Concrete Handler 2


package com.codexplo.patterns.behavioural.chainofresponsibility;

public class BusinessEmail implements EmailHandler {

private EmailHandler next;

@Override
public void setNext(EmailHandler emailHandler) {
this.next = emailHandler;
}

@Override
public void handleRequest(String email) {
if (email.contains("@business.com")) {
System.out
.println("Email is from Business.com, so it will go in Business.com Folder");
} else {
next.handleRequest(email);
}
}
}



Email Processor


package com.codexplo.patterns.behavioural.chainofresponsibility;

public class EmailProccessor {
private EmailHandler successor;
private EmailHandler first;

public void addHandler(EmailHandler handler) {
if (this.first == null) {
this.first = handler;
} else
this.successor.setNext(handler);
this.successor = handler;
}

public void handle(String email) {
first.handleRequest(email);
}
}



Email Client


package com.codexplo.patterns.behavioural.chainofresponsibility;

public class EmailClient {
private EmailProccessor proccessor;

public EmailClient() {
createProccessor();
}

private void createProccessor() {
proccessor = new EmailProccessor();
proccessor.addHandler(new BusinessEmail());
proccessor.addHandler(new GmailEmail());
}

public void emailRecieved(String email) {
proccessor.handle(email);
}

public static void main(String[] args) {
EmailClient client = new EmailClient();
client.emailRecieved("rokonoid@gmail.com");
client.emailRecieved("rokonoid@business.com");
}
}



CloudBess maven deployment Command

Deploy :


clean install bees:deploy

deploy skipping test :


clean install bees:deploy -Dmaven.test.skip=true

Java Tutorial for Absolute Beginners Part 2

Think twice before diving into ocean, check JOEL Test score

As we are graduating this year, most of us spend a significant amount of time looking for a job and certainly I do. There are always jobs out there but are they all good for you? You know the answer, some of them are too good and some of them are average and some of them are really poor. By the way, I’m talking about software developer’s job.  So getting a good job always is our priority which will make use of your talents and expertise. The ideal environment will be professionally stimulating and will offer opportunity for career advancement.

There is a term named Joel Test, most of you already heard about, if not stay with me.

This is a very neat and clean test, very easy to get a quick yes or no to each question.

They questions are –

  • Do you use source control?
  • Can you make a build in one step?
  • Do you make daily builds?
  • Do you have a bug database?
  • Do you fix bugs before writing new code?
  • Do you have an up-to-date schedule?
  • Do you have a spec?
  • Do programmers have quiet working conditions?
  • Do you use the best tools money can buy?
  • Do you have testers?
  • Do new candidates write code during their interview?
  • Do you do hallway usability testing?

A score of 12 is perfect, 11 is tolerable, but 10 or lower and you’ve got serious problems.

The truth is that most software organizations are running with a score of 2 or 3, and they need serious help, because companies like Microsoft run at 12 full-time.

Personally I want to get a job where the score at least 10 out of 12, what’s yours?

So before dive, check the score of that company you’re supposed to join.

To Get More Help, please visit: http://www.joelonsoftware.com/articles/fog0000000043.html

For those who are disappointed for the lack of lambda expressions and some other functional features in Java

Today I just found a cool java library which made me really happy. It’s called op4j: Bending the Java spoon.  It is a Java library aimed at improving quality, semantics, cleanness and readability of Java code, especially auxiliary code like data conversion, structure iteration, filtering, mapping, etc.

For example…

We have a list of string and all of the strings are dates in dd/MM/yyyy format and we wanted to convert them into java.util.Calendar objects. And some string may be null and we don’t want nulls to be included in final results and one more things, we don’t want dates in the futures, only the past ones in the final results.

So here three things we need to do:

  • Convert all the string dates in java.util.Calendar object
  • Remove nulls
  • Remove futures dates.

So let’s see how we can do it in normal java.


                List<String> list = new ArrayList<String>();
		list.add("17/10/2012");
		list.add("16/10/2011");
		list.add("15/10/2010");
		list.add("14/10/2007");
		list.add(null);
		list.add("13/10/2009");

		Calendar now = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		Calendar calendar = Calendar.getInstance();

		Set<Calendar> set = new LinkedHashSet<Calendar>();
		Date date = null;
		for (String element : list) {
			if (element != null) {
				try {
					date = dateFormat.parse(element);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				calendar.setTimeInMillis(date.getTime());
				if (!calendar.after(now)) {
					set.add(calendar);
				}
			}
		}

Same thing we can do it with op4j but writing only 2 line of code


Calendar now1 = Calendar.getInstance();
		Set set1 = Op.on(list).toSet()
				.map(FnString.toCalendar("dd/MM/yyyy"))
				.removeAllNullOrTrue(FnCalendar.after(now1)).get();

and a lot of other example are here: http://www.bendingthejavaspoon.com/

and adding op4j

<dependency>
	<groupId>org.op4j</groupId>
	<artifactId>op4j</artifactId>
	<version>1.2</version>
</dependency>

Happy Coding !!

How to encrypt password in Java

One of the most important security features used today are passwords. It is important for both you and all your users to have secured and unguessable passwords.  Passwords are always meant as sensitive personal data and so the way broadly used today is password encryption.  We encrypt password using one way techniques, this is, digests.  In this way, we only encrypt a password and there is absolutely no reason for a password being decrypted. Thing is kinda like, user insert a password, the passwords gets encrypted immediately, and then the encrypted password gets persisted or anything else.

So do so a lot of encryption algorithms has been developed depending on needs. The most used ones are:

  • MD5 algorithm
  • SHA Family: SHA-1 algorithm and SHA-2 variants (SHA-224, SHA-256, SHA-384 and SHA-512)

MD5 and SHA1 is most adequate choice for password digesting.

As a lot implementation of these algorithms in different language has done already, I was looking for java. Today I found a very much simplified and easy to use java library which is production-ready. You can use in your project. Its Jaspt.

Let me show you some example use-


package com.codexplo.crypt;

import org.jasypt.util.password.BasicPasswordEncryptor;
import org.jasypt.util.password.ConfigurablePasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;

public class PasswordEncryption {
public static void main(String[] args) {

// for basic encryptions
BasicPasswordEncryptor encryptor = new BasicPasswordEncryptor();
String password = encryptor.encryptPassword("helloworld");
System.out.println("Password encrypted by Basic password encryptor: "
+ password);

// you can verify password
boolean isOkay = encryptor.checkPassword("helloworld", password);

// for Stron encryptions
StrongPasswordEncryptor encryptor2 = new StrongPasswordEncryptor();
String password2 = encryptor2.encryptPassword("helloworld");
System.out.println("Password encrypted by String password encryptor: "
+ password2);

// Even you can configure algorithm
ConfigurablePasswordEncryptor encryptor3 = new ConfigurablePasswordEncryptor();
encryptor3.setAlgorithm("SHA-512");
String password3 = encryptor3.encryptPassword("helloworld");
System.out
.println("Password encrypted by Configurable password encryptor: "
+ password3);
}

}

and the Output:


Password encrypted by Basic password encryptor: tUu09eR+G+AYwOOBEdhMo1LlenTq/UOa
Password encrypted by Strong password encryptor: kD6BFzSDjAqq6d3UF9m1D5YZE593W6XTbMjoXQ6OnSRu/E7pSJJQtpqWvJ72YKGT
Password encrypted by Configurable password encryptor: Ycx9oO2GUsxzEDFIyRKVkcPQuK0TcoUFrZBBmGCjk6zJrhAXCaQbnG0vdyjmeFKl5qnu7mmi8Et9yEZB26wgg2lDLt5DSj0N

To use Jaspt, add following maven dependency in your pom.xml


<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.0</version>
</dependency>

To know more about it: http://www.jasypt.org/