Encode String security using MD5 algorithm in Java

The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It’s very simple and straight forward; the basic idea is to map data sets of variable length to data sets of a fixed length. In order to do this, the input message is split into chunks of 512-bit blocks.


A padding is added to the end so that it’s length can be divided by 512. Now these blocks are processed by the MD5 algorithm, which operates in a 128-bit state, and the result will be a 128-bit hash value. After applying MD5, generated hash is typically a 32-digit hexadecimal number.

Here, the password to be encoded is often called the “message” and the generated hash value is called the message digest or simply “digest”.
public class SimpleMD5Example
{
    public static void main(String[] args)
    {
        String passwordToHash = "password";
        String generatedPassword = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            md.update(passwordToHash.getBytes());
            //Get the hash's bytes
            byte[] bytes = md.digest();
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        System.out.println(generatedPassword);
    }
}

Console output:

5f4dcc3b5aa765d61d8327deb882cf99


Although MD5 is a widely spread hashing algorithm, is far from being secure, MD5 generates fairly weak hashes. It’s main advantages are that it is fast, and easy to implement. But it also means that it is susceptible to brute-force and dictionary attacks. Rainbow tables with words and hashes generated allows searching very quickly for a known hash and getting the original word.

Also, It is not collision resistant: this means that different passwords can eventually result in the same hash.

Still, if you are using MD5 hash then consider adding some salt to your security.

Making MD5 more secure using salt

Keep in mind, adding salt is not MD5 specific. You can add it to other algorithms also. So, please focus on how it is applied rather than its relation with MD5.

Wikipedia defines salt as random data that are used as an additional input to a one-way function that hashes a password or pass-phrase. In more simple words, salt is some randomly generated text, which is appended to password before obtaining hash.

The original intent of salting was primarily to defeat pre-computed rainbow table attacks that could otherwise be used to greatly improve the efficiency of cracking the hashed password database. A greater benefit now is to slow down parallel operations that compare the hash of a password guess against many password hashes at once.
Important: 
We always need to use a SecureRandom to create good Salts, and in Java, the SecureRandom class supports the “SHA1PRNG” pseudo random number generator algorithm, and we can take advantage of it.

Let’s see how this salt should be generated.

private static byte[] getSalt() throws NoSuchAlgorithmException
{
    //Always use a SecureRandom generator
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    //Create array for salt
    byte[] salt = new byte[16];
    //Get a random salt
    sr.nextBytes(salt);
    //return salt
    return salt;
}
SHA1PRNG algorithm is used as cryptographically strong pseudo-random number generator based on the SHA-1 message digest algorithm. Note that if a seed is not provided, it will generate a seed from a true random number generator (TRNG).

Now, lets look at the modified MD5 hashing example:

public class SaltedMD5Example
{
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException
    {
        String passwordToHash = "password";
        byte[] salt = getSalt();
       
        String securePassword = getSecurePassword(passwordToHash, salt);
        System.out.println(securePassword); //Prints 83ee5baeea20b6c21635e4ea67847f66
       
        String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);
        System.out.println(regeneratedPassowrdToVerify); //Prints 83ee5baeea20b6c21635e4ea67847f66
    }
   
    private static String getSecurePassword(String passwordToHash, byte[] salt)
    {
        String generatedPassword = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            md.update(salt);
            //Get the hash's bytes
            byte[] bytes = md.digest(passwordToHash.getBytes());
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb.toString();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return generatedPassword;
    }
   
    //Add salt
    private static byte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException
    {
        //Always use a SecureRandom generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
        //Create array for salt
        byte[] salt = new byte[16];
        //Get a random salt
        sr.nextBytes(salt);
        //return salt
        return salt;
    }
}
Important: 
Please note that now you have to store this salt value for every password you hash. Because when user login back in system, you must use only originally generated salt to again create the hash to match with stored hash. If a different salt is used (we are generating random salt), then generated hash will be different.

Also, you might heard of term crazy hashing and salting. It generally refer to creating custom combinations like:
salt+password+salt => hash
Do not practice these things. They do not help in making hashes further secure anyhow. If you want more security, choose a better algorithm.

JFoenix - JavaFX Material Design Library

In nowadays web application is on top with mobile application but you can't ignore the desktop applications value. And after this post you can't stop you to make your first desktop application if you didn't make before.
In Java have Swing for desktop application but it is dull as a end user point of view. So they launch JavaFx in which we can add own custom CSS with that technology for better designing.
But here i am not talking about JavaFx its the better version of JavaFx design named - JFoenix which give the power to use Googles Material design in our desktop application.

Example

Floating Button


Listview

Cool isn't it huh ?

Demo



JFoenix is an open source java library, that implements Google Material Design using java components. To start using JFoenix, all you have to is download it from GitHub.
You can find JFoneix source files along with a compiled jar file on the following link:

  1. JavaFX Material Design Library download jar
  2. JFoenix android build download
  3. JFoenix Site

Build

Ant

To build JFoenix, we created an Ant file named build.xml and build.bat. JFoenix uses Java version 1.8 u60. Using the command line, you need to move to the JFoenix/make directory and run the batch file build.bat by typing:
build.bat
To run the main demo, go to the JFoenix/make directory and run the batch file run-demo.bat :
run-demo.bat
NOTE :

  • You need to update the build.bat to point to Java 1.8 and Apache Ant directories.
  • Linux is also supported. In the make directory, use ./build.sh and ./run-demo.sh, respectively.

Gradle

To build JFoenix, execute the following command:
gradlew build
To run the main demo, execute the following command:
gradlew run
NOTE : 

  • You need to set JAVA_HOME environment variable to point to Java 1.8 directory.
  • JFoenix requires Java 1.8 u60 and above.

How Can You Use JFoenix?


  • You can download the source code of the library and build it as mentioned previously. 
  • Building JFoenix will generate jfoenix.jar under the build/dist folder. 
  • To use JFoenix, import jfoenix.jar into your project and start using the new material design Java components :).

Gradle

How to Include In Project
repositories {
    mavenCentral()
}
Reference the repository from this location using:
dependencies {
  compile 'com.jfoenix:jfoenix:1.0.0'
}
Hope you like this article and want more then subscribe us.

Drag and Drop 3D Objects Using Three.js

In my previous article on Three.js in which i teach you how to make 3D objects with WebGL using Three.js and if you're new for this then you can read that article from here.
But today we're taking some extra step in this field and now you can learn how to drag drop that 3d objects which you made in previous tutorial.



The Drag and Drop feature is one of important features of nearly every interactive environment. Use the mouse to interact and drag and drop objects is very native. However this feature is not supported in three.js by default. In our tenth lesson we explain how to implement this drag-and-drop function.

Demo



The demo generates randomly located spheres that you can move with your mouse. Simply drag a sphere, move it to another place, and then drop it. To rotate the scene, you can use the mouse as well (we use THREE.OrbitControls).

Preparation

To start with, please create a new index.html file with the following code:

index.html

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta name="author" content="Script Tutorials" />
<title>WebGL With Three.js - Lesson 10 - Drag and Drop Objects | Script Tutorials</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="js/three.min.71.js"></script>
<script src="js/THREEx.WindowResize.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/stats.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
This basic code connects all the necessary libraries.

Skeleton of the scene

Now create another file – ‘script.js’ and put it into ‘js’ folder. Place the following code into the file:

js/script.js

var lesson10 = {
scene: null, camera: null, renderer: null,
container: null, controls: null,
clock: null, stats: null,
plane: null, selection: null, offset: new THREE.Vector3(), objects: [],
raycaster: new THREE.Raycaster(),
init: function() {
// Create main scene
this.scene = new THREE.Scene();
this.scene.fog = new THREE.FogExp2(0xcce0ff, 0.0003);
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
// Prepare perspective camera
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 1000;
this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
this.scene.add(this.camera);
this.camera.position.set(100, 0, 0);
this.camera.lookAt(new THREE.Vector3(0,0,0));
// Prepare webgl renderer
this.renderer = new THREE.WebGLRenderer({ antialias:true });
this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
this.renderer.setClearColor(this.scene.fog.color);
// Prepare container
this.container = document.createElement('div');
document.body.appendChild(this.container);
this.container.appendChild(this.renderer.domElement);
// Events
THREEx.WindowResize(this.renderer, this.camera);
document.addEventListener('mousedown', this.onDocumentMouseDown, false);
document.addEventListener('mousemove', this.onDocumentMouseMove, false);
document.addEventListener('mouseup', this.onDocumentMouseUp, false);
// Prepare Orbit controls
this.controls = new THREE.OrbitControls(this.camera);
this.controls.target = new THREE.Vector3(0, 0, 0);
this.controls.maxDistance = 150;
// Prepare clock
this.clock = new THREE.Clock();
// Prepare stats
this.stats = new Stats();
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '50px';
this.stats.domElement.style.bottom = '50px';
this.stats.domElement.style.zIndex = 1;
this.container.appendChild( this.stats.domElement );
// Add lights
this.scene.add( new THREE.AmbientLight(0x444444));
var dirLight = new THREE.DirectionalLight(0xffffff);
dirLight.position.set(200, 200, 1000).normalize();
this.camera.add(dirLight);
this.camera.add(dirLight.target);
....
},
addSkybox: function() {
....
},
onDocumentMouseDown: function (event) {
....
},
onDocumentMouseMove: function (event) {
....
},
onDocumentMouseUp: function (event) {
....
}
};
// Animate the scene
function animate() {
requestAnimationFrame(animate);
render();
update();
}
// Update controls and stats
function update() {
var delta = lesson10.clock.getDelta();
lesson10.controls.update(delta);
lesson10.stats.update();
}
// Render the scene
function render() {
if (lesson10.renderer) {
lesson10.renderer.render(lesson10.scene, lesson10.camera);
}
}
// Initialize lesson on page load
function initializeLesson() {
lesson10.init();
animate();
}
if (window.addEventListener)
window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent)
window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;
With this code, we prepared the scene – camera (THREE.PerspectiveCamera), renderer (THREE.WebGLRenderer), controller (THREE.OrbitControls), light (THREE.DirectionalLight), and various event handlers (empty for now, we will add it’s code further).

Skybox

Now, let’s add the skybox – blue-white gradient with shader. First of all, add two shaders in the beginning of our script.js file:
sbVertexShader = [
"varying vec3 vWorldPosition;",
"void main() {",
"  vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
"  vWorldPosition = worldPosition.xyz;",
"  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}",
].join("\n");
sbFragmentShader = [
"uniform vec3 topColor;",
"uniform vec3 bottomColor;",
"uniform float offset;",
"uniform float exponent;",
"varying vec3 vWorldPosition;",
"void main() {",
"  float h = normalize( vWorldPosition + offset ).y;",
"  gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( h, exponent ), 0.0 ) ), 1.0 );",
"}",
].join("\n");
So both shaders (vertex and fragment shaders) will be added to our page. Now we can add
// Display skybox
this.addSkybox();
right after we added our light. Here is the code for the ‘addSkybox’ function:
addSkybox: function() {
var iSBrsize = 500;
var uniforms = {
topColor: {type: "c", value: new THREE.Color(0x0077ff)}, bottomColor: {type: "c", value: new THREE.Color(0xffffff)},
offset: {type: "f", value: iSBrsize}, exponent: {type: "f", value: 1.5}
}
var skyGeo = new THREE.SphereGeometry(iSBrsize, 32, 32);
skyMat = new THREE.ShaderMaterial({vertexShader: sbVertexShader, fragmentShader: sbFragmentShader, uniforms: uniforms, side: THREE.DoubleSide, fog: false});
skyMesh = new THREE.Mesh(skyGeo, skyMat);
this.scene.add(skyMesh);
},

Additional objects

After the skybox, we can add spheres with random radius and position:
// Add 100 random objects (spheres)
var object, material, radius;
var objGeometry = new THREE.SphereGeometry(1, 24, 24);
for (var i = 0; i < 50; i++) {
material = new THREE.MeshPhongMaterial({color: Math.random() * 0xffffff});
material.transparent = true;
object = new THREE.Mesh(objGeometry.clone(), material);
this.objects.push(object);
radius = Math.random() * 4 + 2;
object.scale.x = radius;
object.scale.y = radius;
object.scale.z = radius;
object.position.x = Math.random() * 50 - 25;
object.position.y = Math.random() * 50 - 25;
object.position.z = Math.random() * 50 - 25;
this.scene.add(object);
}
As you see, all the objects were added to the ‘objects’ array. We will use this array for raycaster (THREE.Raycaster) to determinate if an object is intersected with our mouse.

Now pay attention, in order to implement the drag and drop function, we need to determine at what axis (plane) we need to move the selected object. As we know, mouse moves in two dimensions, while our scene works in three. To find an offset of dragging, we will use an invisible ‘helper’ – plane (add this code below the code where we add the spheres):
// Plane, that helps to determinate an intersection position
this.plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(500, 500, 8, 8), new THREE.MeshBasicMaterial({color: 0xffffff}));
this.plane.visible = false;
this.scene.add(this.plane);

onDocumentMouseMove

Now we need to implement the first event handler: onDocumentMouseMove. When we press the mouse button, we need to define position where we pressed the key, then we create a 3D vector of this point, unproject it, set the raycaster position, and find all intersected objects (where we clicked the mouse button). Then we disable the controls (we don’t need to rotate the scene while we are dragging the selection). The first visible element will be set as the selection, and we need to save the offset:
onDocumentMouseDown: function (event) {
// Get mouse position
var mouseX = (event.clientX / window.innerWidth) * 2 - 1;
var mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
// Get 3D vector from 3D mouse position using 'unproject' function
var vector = new THREE.Vector3(mouseX, mouseY, 1);
vector.unproject(lesson10.camera);
// Set the raycaster position
lesson10.raycaster.set( lesson10.camera.position, vector.sub( lesson10.camera.position ).normalize() );
// Find all intersected objects
var intersects = lesson10.raycaster.intersectObjects(lesson10.objects);
if (intersects.length > 0) {
// Disable the controls
lesson10.controls.enabled = false;
// Set the selection - first intersected object
lesson10.selection = intersects[0].object;
// Calculate the offset
var intersects = lesson10.raycaster.intersectObject(lesson10.plane);
lesson10.offset.copy(intersects[0].point).sub(lesson10.plane.position);
}
}

onDocumentMouseMove

Having the selection (sphere), we can change position of the sphere (to another position where our mouse pointer is). But if there is no any selection, we need to update position of our help plane. It always needs to look directly at our camera position:
onDocumentMouseMove: function (event) {
event.preventDefault();
// Get mouse position
var mouseX = (event.clientX / window.innerWidth) * 2 - 1;
var mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
// Get 3D vector from 3D mouse position using 'unproject' function
var vector = new THREE.Vector3(mouseX, mouseY, 1);
vector.unproject(lesson10.camera);
// Set the raycaster position
lesson10.raycaster.set( lesson10.camera.position, vector.sub( lesson10.camera.position ).normalize() );
if (lesson10.selection) {
// Check the position where the plane is intersected
var intersects = lesson10.raycaster.intersectObject(lesson10.plane);
// Reposition the object based on the intersection point with the plane
lesson10.selection.position.copy(intersects[0].point.sub(lesson10.offset));
} else {
// Update position of the plane if need
var intersects = lesson10.raycaster.intersectObjects(lesson10.objects);
if (intersects.length > 0) {
lesson10.plane.position.copy(intersects[0].object.position);
lesson10.plane.lookAt(lesson10.camera.position);
}
}
}

onDocumentMouseUp

When we release our mouse button, we only need to enable the controls again, and reset the selection:
onDocumentMouseUp: function (event) {
// Enable the controls
lesson10.controls.enabled = true;
lesson10.selection = null;
}
That’s it for today. Hope you find our tutorial useful. If it is then subscribe us.

How to add Dynamic Navigation Drawer Items

In the last few posts, we have executed material navigation drawer with or without using the design support library where items of the navigation drawer were static, that is, they were predefined.
In any case, there are times when you need things to change as indicated by certain client activities or prefrences. In this post, we will progressively add things to a navigation drawer from a database with design support library, MySQLi and PHP scripts.

1)Creating some database tables:

This should always be the very first step whenever there’s a database involved. Here, we create a demo database hosted locally via Apache Web Server using XAMPP to serve the purpose of this post. For XAMPP – https://www.apachefriends.org/index.html.
Below is the screenshot of a demo table  – ‘test‘ – just holding some string values in column ‘Items‘.


2)PHP Script:

Here, We return a JSON response containing names of all the great houses from ASOIAF as declared in the above table.

getItems.php

$db_name = 'test';
$host_name = 'localhost';
$username = 'root';
$password = '';
$table_name = 'test_table';
 
 
$db = new mysqli($host_name,$username,$password,$db_name);
 
if($db->connect_errno>0){
 
    die('Unable to connect -> '.$db->error);
}
 
$queryString="Select * from $table_name";
 
if(!$result = $db->query($queryString)){
 
    die('error'. $db->error);
 
}
 
$temp=0;
$itemArray = array();
 
while ($row = $result->fetch_assoc()) {
    $itemArray[$temp] = $row['Items']; 
    $temp++;
}
 
echo json_encode($itemArray);
 
$result->free();

The response from the above script:

[“House Lannister”,”House Stark”,”House Targaryen”,”House Martell”,”House Tyrell”,”House Tully”]

3)Include Desing Support Library Dependency:

Now, fire up the Android Studio, select an ‘EMPTY‘ activity and include the design support library in your Gradle. Open Module(App) Gradle file and add the below dependencies. (If prompted update your android SDK).
//Code : compile ‘com.android.support:design:23.1.1’

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
   }

4)Creating a Blank Menu Resource:


  1. Create a new Android Resouce Directory of resource type ‘menu‘ in res and name it ‘menu‘.
  2. Create a new menu resource file – ‘drawer_menu.xml‘ in the menu directory.

This blank menu is attached with navigationalView to inflate menu items. We will programmatically add items to this menu later in this post.

5)Modifying Styles:

Open your style.xml file from the values directory and change the parent theme to ‘Theme.AppCompat.NoActionBar’ since we will be implementing a toolbar.

styles.xml

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

6)Adding the internet permission:

Open up your AndroidManifest.xml file and add
<uses-permission android:name=”android.permission.INTERNET”/>
above the application declaration.

7)Designing the Navigation Drawer:

Navigation View inflates navigation items from a menu resource. The hierarchy of elements is shown below:

Basically, a DrawerLayout holds two items – one is the NavigationView and the other Container view.
Container view includes a frameLayout to inflate fragment view and a toolbar. The app: menu attribute of navigation view refers to the blank menu resource created above.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
 
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            />
 
        <FrameLayout
            android:id="@+id/containerView"
            android:background="#FFF"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
 
 
 
    </LinearLayout>
 
    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="left"
        app:headerLayout="@drawable/header"/>
 
</android.support.v4.widget.DrawerLayout>

6)Retrieving required data from the database.

Now the thing is: To dynamically add navigation items, we first get all the elements to be inflated from the database and then add those to the menu by passing our menu as a parameter to an async task.
Here, JsonReader is used to parse the response from the PHP script.

MainActivity.java

package com.blogspot.geekonjava.navdrawer;
 
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.JsonReader;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        /**
         * Setting up the DrawerLayout,NavigationView and Toolbar.
         */
 
 
        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        /**
         * Accessing the NavigationView menu.
         * The getMenu method returns menu resource used by navigationView.
         * Later,we will add items to this menu.
         */
 
        Menu drawerMenu = navigationView.getMenu();
 
        /**
         * Creating an ArrayList to hold items for the above Menu.
         */
        ArrayList items = new ArrayList();
 
        /**
         * Creating object of NavMenuClass defined later.
         * We pass our drawerMenu and ArrayList items to NavMenuClass.
         * And later , use this object to access both arrayList holding the items and the drawer menu.
         */
         
        NavMenuClass navMenuObject = new NavMenuClass(drawerMenu,items);
 
        /**
         * Creating object of AsyncClass - 'PopulateMenuItems' defined later to get items from the database.
         * Here,we pass the above navMenuObject as parameter to async class.
         */
 
        PopulateMenuItems populateMenuItems = new PopulateMenuItems();
        populateMenuItems.execute(navMenuObject);
 
        /**
         * This is required to handle the onItemClick on Navigation Drawer Items.
         */
 
        NavigationView.OnNavigationItemSelectedListener item_click_listener = new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
 
                /** This a sample code to change fragments depending on the menu item.
                 *
                 *  if(item.toString="someConditionalText")
                 *  {
                 *       FragmentManager mFragmentManager;
                 *       FragmentTransaction mFragmentTransaction;
                 *
                 *       mFragmentManager = getSupportFragmentManager();
                 *       mFragmentTransaction = mFragmentManager.beginTransaction();
                 *
                 *       mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
                 *  }
                 */
                drawerLayout.closeDrawers();
                return true;
            }
        };
 
        /**
         * Attaching the above listener to NavigationView
         */
 
        navigationView.setNavigationItemSelectedListener(item_click_listener);
 
        /**
         * Setting up Drawer Toggle for Toolbar.
         */
 
 
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout, toolbar,R.string.app_name,
                R.string.app_name);
 
        drawerLayout.setDrawerListener(mDrawerToggle);
 
        mDrawerToggle.syncState();
 
 
 
 
    }
 
    /**
     * NavMenuClass holds the NavigationView menu and an ArrayList which holds items to be populated in menu.
     */
 
    class NavMenuClass{
        Menu menu;
        ArrayList items;
         
        public NavMenuClass(Menu menu,ArrayList items){
 
            this.items = items;
            this.menu = menu;
 
        }
         
        public Menu getMenu(){
            return menu;
        }
         
        public ArrayList getItems(){
            return items;
        }
           
    }
 
    /**
     * An async task accepts 3 parameters:
     * Params -> the type of the parameters sent to the task upon execution.
     * Progress -> the type of the progress units published during the background computation.
     * Result -> the type of the result of the background computation.
     *
     * For more on asyncTack checkout this answer from stackOverflow :
     * http://stackoverflow.com/a/6053673/5087027
     *
     **/
 
 
    public class PopulateMenuItems extends android.os.AsyncTask<navmenuclass,void,navmenuclass>{
 
        @Override
        protected NavMenuClass doInBackground(final NavMenuClass... params) {
 
            /**
             * Accessing the navMenuObject passed to this class.
             */
            NavMenuClass navMenuObject = params[0];
 
            /**
             * Accessing arrayList passed with this object to add items.
             */
 
            ArrayList items = navMenuObject.getItems();
 
            try {
 
                /**
                 * Here, declare the URL. If on localhost, just write the localhost ip and add the path.
                 * The url object parses the urlString and throws 'MalformedURLException' if  URL could not be parsed.
                 * OpenConnection returns a connection referred by URL.
                 */
 
                String urlString = "http://192.168.0.100/getItems.php";
                URL url = new URL(urlString);
                URLConnection urlConnection = url.openConnection();
 
                /**
                 * InputStream reads the response in bytes and by InputStreamReader it is converted into characters.
                 */
 
                InputStream inputStream = urlConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
 
                /**
                 * JsonReader is used to parse the below output.
                 * ["House Lannister","House Stark","House Targaryen","House Martell","House Tyrell","House Tully"]
                 * In JSON , array stats with '['(Square Bracket) and object with '{'(Curly Bracket)).
                 * More on JsonReader : http://developer.android.com/reference/android/util/JsonReader.html.
                 */
 
                JsonReader jsonReader = new JsonReader(inputStreamReader);
 
                jsonReader.beginArray();
                while (jsonReader.hasNext()){
                    /**
                     * Get the nextString of the JSON array and add it to the arrayList - 'items'.
                     */
                    String name = jsonReader.nextString();
                    items.add(name);
                }
                jsonReader.endArray();
 
                return params[0];
            }
 
            catch (Exception e){
                Log.e("Exception", e.toString());
            }
 
            return null;
        }
 
        /**
         * @param NavMenuClass accepted by onPostExecute is returned by the above doInBackground method.
         * Here, we add ArrayList items added in doInBackground to Menu.
         */
 
        @Override
        protected void onPostExecute(NavMenuClass NavMenuObject) {
            /**
             *  Accessing menu of NavMenuObject.
             */
             
                Menu menu = NavMenuObject.getMenu();
             
            /**
             *  Accessing items of ArrayList from NavMenuObject.
             */
                 
                ArrayList arrayList = NavMenuObject.getItems();
 
            /**
             *  Adding items to menu by iterating the ArrayList.
             */
 
                for(int temp=0;temp<=arrayList.size()-1;temp++){
                    menu.add(arrayList.get(temp).toString());
                }
 
        }
    }
}
 
//Ignore
 
</navmenuclass,void,navmenuclass>

Hope you enjoy this tutorial and if it useful for you and want some more interesting article then subscribe us.

Run Node.JS in Android app

Android is more customisable and easy to use mobile operating system nowadays. And in upcoming growing language node.js is dramatic up with their great power which uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

And for developer would be feel good when they integrate Node.Js with their android application to use that power with existing application.



Here is the library which do it same for you named as Node-Android library which is used to run Node.js on Android by rewrite Node.js in Java with the compatible API.

Download this library from here

Now lets dive with process of integrate and their features :

Build

Clone the code, open Android Studio (1.*) and import the project.
For Eclipse ADT user, refer to this.

Javascript code injection

> adb shell am start -a android.intent.action.VIEW -n com.iwebpp.nodeandroid/.MainActivity -e js "var run = function () { return 'hello world'; } run();"

Features


  • Node.js 0.10.x compatible API
  • Multi-threading: run separate node context in Java thread
  • libUV native support
  • Timer, set/clear Timeout/Interval
  • EventEmitter
  • Stream
  • HttpParser(rewrite http-parser.c in java)
  • HTTP
  • HTTPP(run http over udp)
  • TCP
  • UDT(udp transport)
  • DNS
  • URL
  • IPv6
  • for API usage, check 
  • WebSocket/WebSocketServer supported, check 
  • Connect middleware
  • Crypto: NACL support, public box,secret box,signature/verify
  • SecureWebSocket over NACL

JS runtime


  1. Rhino supported
  2. Exposed node-android packages: com.iwebpp.node.http, com.iwebpp.node.stream, com.iwebpp.node.net, etc
  3. Exposed node-android classes: com.iwebpp.node.EventEmitter2, com.iwebpp.node.Dns, com.iwebpp.node.Url, etc
  4. Exposed node-android native context in JS standard scope as NodeCurrentContext alias NCC
  5. Exposed Android API: android.util.Log
  6. NodeJS compatible internal modules are available in JS standard scope
  7. Exposed WebSocket classes: com.iwebpp.wspp.WebSocket, com.iwebpp.wspp.WebSocketServer


JS usage

In case Rhino, create class 'MyScript' extends from com.iwebpp.node.js.rhino.Host
Implement 'public String content()' in 'MyScript' to return user script
Execute JS engine in a separate Java Thread with 'MyScript.execute()'
When authoring script, please use NodeCurrentContext(alias NCC) in node-android API

Hope you like this tutorial and if you use this library then please hand on this blog with sample app. Just send us sample app source code. So we can help more people easily.
Subscribe us to get more juicy and fresh article like this.

Why waste to buy Apples iPhone 7 and iPhone 7 Plus

Tech company Apple's iPhone series launched new iPhone 7 and iPhone 7 Plus. The company has the most sophisticated and innovative features in these iPhones d, whether it be the processor or camera or headphone jack.
But in fact, Apple features already  in cheap Chinese smartphones available in the market exists. Falling sales of its handsets was believed that the Apple will bring a new technology, however, so nothing happened.


The heavy spending on research

Currently, about 85 per cent of the smartphone market is dominated by Samsung and Chinese company Huawei.
Because of this, Apple has launched the iPhone in haste. Samsung's most advanced phone Galaxy Note 7 due to a malfunction in the battery has been recalled that Apple wanted to take advantage of the situation, but it does not do.

With this Apple iPhone 7 audio jack removal company doing such publicity as it is a strong technology. While the world today is obsessed with Pokemon Go run Apple 15 years old Super Mario games is saying.

Apple in 2011 for $ 2.4 billion on research and development (16,000 crore) spent the last year has been increased to Rs 54,000 crore.

These features have already arrived: the iPhone 7

1. Dual Lens Camera

Apple's first iPhone 7 Plus has a dual lens camera. But tell you that the Chinese company Huawei and Honor smartphone has brought this technology several years ago.

2. Fast Charging

This technology already exists in the Android smartphones. Moto G 4 and G-4 plus the Turbo Charging technology has come.
Android phones in the market in addition to several features.

3. Display and Design

The display resolution is 1920 x 1080 pixels of the iPhone 7. However, Samsung is one plus the premium smartphones more resolution.

4. Water and dust-proof

This feature Sony, Samsung, Huawei, has already in their handsets. Let me tell you that the Samsung Galaxy Note 7 is even more water-proof capacity.

5. Headphones jack

Apple has said the bold step to remove headphone audio jack. It is connected to the charging jack. IPhone users ie 7 and 7 Plus will not be able to use headphones while charging. But P-9 of Huawei smartphone with dual camera headphone jack has been delivered separately.

6. capacity MicroSD card

Android smartphones are getting better, though, given the storage capacity is extended by Apple. But Android smartphones nowadays are coming up in 2 terabyte memory card can be fitted.

7. Stereo speakers

The smartphone speaker stereo technology is not new. HTC, Huawei smartphones this technology has already been granted.

Hope you like this post. If you want more then subscribe us.

WebJars - Life saviour for Java Dev

Nowadays Java web applications are use many web libraries like jQuery, AngularJs, ReactJS, Backbone.js and Twitter Bootstrap. The conventional approach to utilize those libraries is to find and download the JavaScript and CSS source then simply duplicate it into a project.

And it takes more time to find correct js and css file so now i am telling you savior for saving your time for this named WebJars.



Suppose you want use what I call a web artifact library such as bootstrap in your Java based web app. Bootstrap’s Getting started guide describes how you could use it directly from the proposed CDN or via tools like bower or npm.

In this post I might want to demonstrate to you other possibility: webjars.

First I will describe how to use it and then give some background information.

Spring Boot

You can find the source for this example on Github.



To add bootstrap as a webjar to your Spring Boot projects simply add the following dependency to your build file:

For gradle it would be :

build.gradle
dependencies {
  compile 'org.webjars:bootstrap:3.3.1'
}

For maven it would be:

pom.xml
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>bootstrap</artifactId>
  <version>3.3.1</version>
</dependency>
Now when you start your application and point your browser to
http://localhost:8080/webjars/bootstrap/3.3.1/css/bootstrap.css 
you should see bootstrap’s css in the browser. This means that in your html files you can these links to access bootstrap:
<link rel="stylesheet" href="/webjars/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="/webjars/bootstrap/3.3.1/js/bootstrap.min.js"></script>

Grails 3

Since Grails 3 is based upon Spring Boot you only need to add the bootstrap webjar dependency to your build.gradle as described in the previous section. Everything else also works exactly the same.

Grails 2

For Grails 2 I could not get it running out of the box using the servlet 3 approach. Anyway here are my attempts so far:
Assume you named your grails application grails244_webjar and thus you can access it from
http://localhost:8080/grails244_webjar/
When you add the compile 'org.webjars:bootstrap:3.3.1' dependency to your BuildConfig.groovy and then try to access
http://localhost:8080/grails244_webjar/webjars/bootstrap/3.3.1/css/bootstrap.css 
you will get a HTTP 404. http://localhost:8080/webjars/bootstrap/3.3.1/css/bootstrap.css did not work for me either. My guess is that it has something to do with the way the GrailsDispatcherServlet is working.

Servlet

But: taking the servlet 2.x approach as described on this page works:

add the dependency compile 'org.webjars:webjars-servlet-2.x:1.1' to your BuildConfig.groovy

Add the WebjarServlet to web.xml (first you need to invoke grails install-templates to get a web.xml) and add the following to it:

src/templates/war/web.xml

<servlet>
  <servlet-name>WebjarsServlet</servlet-name>
  <servlet-class>org.webjars.servlet.WebjarsServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>WebjarsServlet</servlet-name>
  <url-pattern>/webjars/*</url-pattern>
</servlet-mapping>
Then the URL
http://localhost:8080/grails244_webjar/webjars/bootstrap/3.3.1/css/bootstrap.min.css 
works.

Background

A webjar is nothing special. The only important thing to know is that since the Servlet Specification 3.0 all files underneath the path META-INF/resources are treated like static resources and can be accessed directly from the browser without having to do anything special.

Example

You take a servlet 3.0 compliant container like a modern Tomcat, Jetty, etc. Then you create a jar with a file META-INF/resources/hello.txt containing the text hello world. Now create a war file and put this jar file into WEB-INF/lib. When you start your Tomcat or Jetty and point your browser to http://localhost:8080/readme.txt it should display the text hello world.

The idea behind webjars is to package all files like css, js, images needed by the browser together in a jar file. This has the following big advantages:

Advantages


  • You can leverage maven repositories e.g. by putting webjars into maven central or bintray as any ordinary jar file
  • You can leverage your build tool’s (gradle, maven) dependency management support.
  • You do not have to check in js or css files anymore and you do not have to copy these files around during at build time

Because you can leverage your build tool’s dependency management support means that you can also define and use transitive dependencies for your web artifacts

Let’s take bootstrap again as an example. 

Note that it has a transitive dependency to jQuery. And if you have a look at the pom file of bootstrap’s webjar you can see that it has a dependency declaration on jQuery including the exact version it wants:

pom.xml (of bootstrap’s webjar)

<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>jquery</artifactId>
  <version>1.11.1</version>
</dependency>
This means you only have to declare the dependency to bootstrap in your maven/gradle file and get the right jQuery webjar for free.

If you have a look at http://www.webjars.org/ you can see that webjars for many popular Javascript/css frameworks/libraries already exist and are available via maven central.

Conclusion

In my opinion using webjars is a great way to use web artifacts like Javascript and css files because it is possible to leverage the existing maven dependency management tools and it is not necessary to fiddle around with individual files.

Since I discovered webjars they are my preferred way to use web artifacts in Java based projects especially since most of the popular frameworks and libraries are already available as webjars. And even if you want to provide your own web artifacts as webjar you simply have to stick them in a jar file underneath META-INF/resources and you’re done.