Executor in Java Multithreading

05 June 2018

What is an Executor ? What is an Executor ?

read more

How to run Spring boot Application

Ekansh Rastogi | 02 June 2018

How to run a Spring Boot Application using Maven/ Gradle

read more

Git : Ignore changes to a file that is already tracked in repository

Ekansh Rastogi | 15 May 2017

If you are trying to ignore changes to a file that's already tracked in the repository (e.g. a dev.properties file that you would need to change for your local environment but you would never want to check in these changes) than what you want to do is: git update-index --assume-unchanged If you wanna start tracking changes again git update-index --no-assume-unchanged Reference Reading If you are trying to ignore changes to a file that's already tracked in the repository (e.g. a dev.properties file that you would need to change for your local environment but you would never want to check in...

read more

Angular : How to start angular CLI on custom port

Ekansh Rastogi | 07 April 2017

How to start Angular 2 Application on a Custom port other than 4200 You can start the angular project using the angular cli using command ng serve The above command will start the project on port 4200. If you want to start the application on a prot different that 4200 then you can start the project using the following command. ng serve --port <port-number> where <port-number> can be any valid port that is not in use.

read more

Angular : How to Inject Nested Service in Component

Ekansh Rastogi | 23 March 2017

How to Inject Nested Services in Component Let's create a service url.service.ts that will will be injected in other services. import { Injectable } from '@angular/core'; @Injectable() export class UrlService{ // business logic } Now lets create another service http.service.ts that will Inject this service. import { UrlService } from './url.service.ts'; export class HttpService extends UrlService{ // business logic } Now, we need to inject the HttpService in some component to make http calls. So now we can inject the HttpService in component as shown below. import { Component ,OnInit } from '@angular/core'; import { UrlService } from './url.service.ts'; import { HttpService } from './http.service.ts'; @Component({ selector : 'some-selector', ...

read more

Angular : Getting started with Angular with Angular CLI, Installation and Hello World Example

Ekansh Rastogi | 15 March 2017

Install and Setup Angular Before we start, lets install the angular cli with the following command npm install -g @angular/cli Angular CLI is a tool that can make a new project, compile your typescript files, configure your typescript compiler run your code with live preview, build and package your project. Note Make sure you have latest node and npm installed, at least node version 6.9.x and npm version 3.x.x. To see the versions you can run commands node -v and npm -v for node and npm versions respectively. WarningWhile installation you might get the...

read more

Node : How to uninstall a nodejs global dependency

Ekansh Rastogi | 10 March 2017

Uninstall global node dependency To uninstall a node dependency installed with -g command you can use the following command. npm uninstall -g <dependency> The above command will remove that dependency from your system. Uninstall node dependency To remove a dependency from your project you can use the following command. npm uninstall <dependency> This will remove the dependency and remove its entry from the package.json file.

read more

Node : How to Upgrade NodeJs and Npm and How to install latest NodeJs on Linux, Ubuntu

Ekansh Rastogi | 10 March 2017

Points to Remember If you are installing node for the first time then, use the NodeSource PPA and first choose the version of node you want to install. Following are the sources for the node versions for Node.js v4 curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - for Node.js v5 curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash - for Node.js v6 curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - for Node.js v7 curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash - Once this is done, then update your repositories by command sudo apt-get update Now, finally install NodeJs and Npm using the following command ...

read more

Groovy : What is Identity Operator and difference between == in Java and Groovy

Ekansh Rastogi | 07 March 2017

What is Identity == operator In Java, == operator is used for checking the reference of objects. In Groovy, it is used to check if the object are equals, i.e it is the implementation of equals() method in java. == operator in In java, checks the reference of the objects. In groovy, == is equivalent to .equals() and checks if the two objects are equal is operator In java, does not exist In groovy, checks the reference of the objects which is == in java equals() method In java, checks if the two objects are...

read more

Groovy : What is Coercion operator and how to use it

Ekansh Rastogi | 07 March 2017

Point to Remember Coercion Operator is used for casting Custom Coercion rules can be applied to a class by defining asType method in a class. Syntax of coercion operator is as What is Coercion Operator Coercion operator is used to do type casting of objects in groovy. It converts objects of one type to another type. Lets take a look at the following examples int a = 123 String s = (String) a The the above example, the assignment of a to s will give a ClassCastException in java but when you run the same in groovy it will...

read more

Groovy : What is Direct field access operator and how to use it

Ekansh Rastogi | 03 March 2017

Direct field access operatorIn groovy when we access the property of any object as object.property then groovy under the hood calls the getter method of the property even if we have not specified it. The default getter and setter methods return the property and set the property respectively.Let's have a look at the example. ​class User { String name String email String getName(){ return "Name is $name" } }User u = new User(name : 'ekiras' , email : 'ekansh@ekiras.com')println u.name When you execute the above code you will get the output Name is ekiras. NoteWhat happens under the hood is...

read more

Groovy : What is Elvis Operator and difference b/w Elvis and Ternary operator

Ekansh Rastogi | 03 March 2017

Ternary Operator Ternary Operator is the short hand of the if-else block, where a condition is evaluated to true or false and following statement is executed. Syntax of the ternary operator is below <boolean expression> ? <executed when condition is true> : <executed when condition is false> A typical example of if-else block is shown below where we check if a variable is null or not. String s = "hello" if( s != null ) println s else println "not found" We can replace the above code with the ternary operator as shown below String s = "hello" println s !=null ? s :...

read more

Groovy : What is Safe Navigation operator or Null check Operator

Ekansh Rastogi | 03 March 2017

Safe navigation operator The safe navigation Operator is used to avoid null pointer exceptions. Many a times you come across the need to access the value of an object if it is not null. Syntax for the Safe Navigation Operator is <object>?.<property> Here the could be any object and could be any property of the object. Let's have a look at the below example, class User { String name; } User u = new User(name : "ekiras") if(u != null) println u.name // prints ekiras In the above code we have to write the if block to check if the user object is null...

read more

Gradle : How to upload the Jar or War file to custom path in local machine

Ekansh Rastogi | 02 March 2017

Points to Remember Default location for gradle dependencies is ~/.gradle or /home/{user}/.gradle. We can specify the location from where to gradle should find dependencies and where it should upload the created artifacts. How to upload an Artifact to a custom location in file system buildscript { repositories { maven { url uri("$buildDir/repo") } } } group 'com.ekiras' version '1.0-SNAPSHOT' apply plugin: 'groovy' apply plugin: 'maven' repositories { mavenCentral() } dependencies { // dependencies } uploadArchives { repositories { mavenDeployer { repository(url: uri("$buildDir/repo")) } } } In the above example, uploadArchives { repositories { mavenDeployer { repository(url: uri("$buildDir/repo")) } } } This tells gradle that it will upload the created...

read more

Gradle : How to make a custom War file

Ekansh Rastogi | 01 March 2017

Points to Remember War task extends Jar You can create war files with any configuration defined in configurations { } closure You can also add files to an existing war file. You can select the files that needs to be included or excluded while creating a war file How to create a War file in Gradle To create a war file you have to create a task of type War as shown below // include java plugin apply plugin : 'java' task createWar(type : War){ destinationDir = file("$buildDir") baseName = "my-war" version = "1.1" caseSensitive = true ...

read more

Groovy : What is Groovy Truth and define Custom Groovy Truth

Ekansh Rastogi | 23 February 2017

What is Groovy TruthGroovy has its own way of defining what is true and what is false, this is called the Groovy Truth. In Java, we have to write statements like if(obj ==null), in groovy you can simply write if(obj) and you can define in what conditions this object will evaluate to true and when it will evaluate to false. InfoTo define your custom logic for groovy Truth you need to define methodboolean asBoolean(){ // your logic here} What is True in GroovyFollowing evaluated to true in groovy boolean true Not null objects Non 0 numbers Not null and not...

read more

Browserify : How to use Node.js require dependencies in Browser as Javascipt

Ekansh Rastogi | 15 February 2017

How to get Browserify Use the following to download browserify. npm install -g browserify Automate Browserify Dependency You can also create a package.json file by the following command. npm init This will create a basic package.json file. now run the command npm install --save browserify --save option will download the file and save its reference in package.json. Now on other machine you just need to run the command npm install and it will download the browserify plugin and save it on your machine. This will download the browserify in node_modules folder. Now we can use browserify to download our node dependencies. For...

read more

Gradle : How to use Gradle Cargo Plugin to Deploy war on Tomcat

Ekansh Rastogi | 15 February 2017

This post is based on the Gradle Cargo Plugin by bmuschko Include the Plugin You need to include the plugin in your build.gradle. buildscript { repositories { jcenter() } dependencies { classpath 'com.bmuschko:gradle-cargo-plugin:2.2.3' } } apply plugin: 'com.bmuschko.cargo' buildscript block should be the first thing in the build.gradle file. Include the Gradle Cargo plugin dependencies Add the following in your gradledependencies block dependencies { def cargoVersion = '1.4.5' cargo "org.codehaus.cargo:cargo-core-uberjar:$cargoVersion", "org.codehaus.cargo:cargo-ant:$cargoVersion" } Define the Tomcat Container To deploy The war files to Tomcat you need to create a dsl by name cargo and define the mandatory containerId. Note ContainerId will define the version of tomcat you want...

read more

Tomcat : How to start Tomcat as a service on Windows 7,8,10

Ekansh Rastogi | 15 February 2017

Step 1 : Download and Extract tomcat Download tomcat from the link in .zip format. Once download is complete extract the tomcat in the location you want, preferably C:\Tomcat\. Step 2 : Install Tomcat as a Service Go to the tomcat directory C:\Tomcat\bin. in the address bar write cmd. This will open the command prompt window. Now in the command prompt window type the command service.bat install <Service -Name> Here <Service-Name> can be any name that you want to assign to your Service. When you run this command you will see the following output. Check the installed Service Now, lets see if the service is created...

read more

Gradle : How To Exclude Files and Packages from a Jar file

Ekansh Rastogi | 03 January 2017

How To Exclude File from a Jar file. Gradle task Jar has a property excludes which takes an array as an input and exclude these files from the Jar file it creates. Let's assume the following directory structure Following example excludes files from the Jar file. task createExcludingFiles(type :Jar){ from ('src'){ excludes = ["main/java/com/ekiras/demo/D.java","main/java/com/ekiras/demo/E.java"] }} This will exclude files D.java, E.java from the jar file. Run the gradle task using command gradle -q createExcludingFiles. The Jar file created will have the following files. META-INF/META-INF/MANIFEST.MFmain/main/java/main/java/com/main/java/com/ekiras/main/java/com/ekiras/demo/main/java/com/ekiras/demo/A.javamain/java/com/ekiras/demo/C.javamain/java/com/ekiras/demo/F.javamain/java/com/ekiras/demo/B.javamain/java/com/ekiras/demo/p1/main/java/com/ekiras/demo/p1/X.javamain/java/com/ekiras/demo/p1/Z.javamain/java/com/ekiras/demo/p1/Y.javatest/test/java/main/resources/test/resources/ Exclude Package in Jar file task createExcludingPackage(type :Jar){ from ('src'){ excludes = ["main/java/com/ekiras/demo/D.java" ,"main/java/com/ekiras/demo/p1/**"] }} Run...

read more

Gradle : How to create a Jar file

Ekansh Rastogi | 02 January 2017

How to name a Jar file Lets take the following jar file for explaning the jar naming conventions. customName_wrapper_2.0.1_SNAPSHOT.jar A jar file has the following properties Property Description baseName customName appendix wrapper version 2.0.1 classifier SNAPSHOT archiveName - Here property archiveName if specified will override all the other naming conventions like baseName etc. It should be a fully qualified name of the Jar including the extension (.jar) Other Properties of Gradle Task :: Jar Property Description destinationDir Destination where jar is to be created manifest Include Manifest file from Directory from where files are to be read Creating a Jar...

read more

Tomcat : How to start Tomcat on more than one Port.

Ekansh Rastogi | 02 January 2017

How to start Tomcat on more than one Port. Tomcat settings can be found in TomcatFolder/conf/server.xml file. Root element of the configuration is Server tag. You can add multiple Service under Server tag for running tomcat on more than one port. Default Service Configuration should look as follows <Service name="Catalina"> <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> <Engine name="Catalina" defaultHost="localhost"> <Realm className="org.apache.catalina.realm.LockOutRealm"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" /> </Host> </Engine> </Service> The above configurations states the folllowing things Service name="Catalina"...

read more

Tomcat : How to change default port 8080 of Tomcat

Ekansh Rastogi | 02 January 2017

How to change default port 8080 of Tomcat Look for the file server.xml in folder path-to-Tomcat/conf/ This file containes the configuration for tomcat. Look for the following lines in this file. <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> Connector port="8080" defines the port on which the tomcat will run. If you want to run tomcat on any port other than 8080 then you can just change the port number here. e.g Running Tomcat on port 8090 <Connector port="8090" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> e.g Running Tomcat on port 9000 <Connector port="9000" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> Also Read How to change default port...

read more

Tomcat : How to change Deployment directory from webapp to custom Directory.

Ekansh Rastogi | 31 December 2016

How to change Working Directory of Tomcat to Custom Directory Default Tomcat working directory is webapp. If you want to change this to some other directory then you can follow the steps below. Open the server.xml file. You can find this file in conf/ directory of your tomcat folder. Find the following line in the file <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> It states the following things name="localhost" - name of the server appBase="webapps" - working directory of tomcat where applications are deployed unpackWARs="true" - if tomcat should unpack war files. autoDeploy="true" - if tomcat should auto deploy changes How to...

read more

Gradle : How to list files inside a Jar, Zip Tar Files in Gradle Task

Ekansh Rastogi | 16 December 2016

How to load and read files in Gradle Project. The Gradle Project Api has the following methods for using files. file() - to load and read a particular file files() - to load and read multiple files fileTree() - to load and read file hierarchy in a directory or folder zipTree() - to load and read a zip file (includes Jar , War and Ear files) tarTree() - to load and read a tar file How to list files inside a Zip file Jar File and Tar file Lets say we have a file structure as shown in image below....

read more

Gradle : Difference between File, FileCollection and FileTree in Gradle

Ekansh Rastogi | 08 December 2016

Difference Between File, FileCollection and FileTree in Gradle File FileCollection FileTree File is from java.io package FileCollection is from org.gradle.api.file package FileTree is from org.gradle.api.file package File represents a single file. FileCollection represents a collection of files FileTree represents hierarchy of files in a directory or folder. Difference Between File, FileCollection and FileTree Suppose we have a directory structure as shown in image below. We can write a gradle task as shown below task loadFiles(){ doLast{ File file = file('src/main/resources/sample1.txt') println file.name println "\n" FileCollection collection = files('src/main/resources/sample1.txt','src/main/resources/sample2.txt') collection.each { println it.name } println "\n" FileTree tree = fileTree('src') tree.each...

read more

Gradle : How to read all files in a directory using FileTree

Ekansh Rastogi | 08 December 2016

Introduction to FileTree in Gradle Api FileTree is an interface that extends FileCollection and introduces methods like matching() and visit(). It class represents a hierarchy of files in a given directory. It includes files in same folder and all sub folders. How to get all files in a Directory To load all files in a given directory and its sub directories you can use FileTree. Syntax for FileTree is as shown below. FileTree tree = fileTree('path/to/dir') The FileTree can get files in following ways from relative path from We can write a gradle task to list all the files in...

read more

Gradle : What is a FileCollection in Gradle Api

Ekansh Rastogi | 08 December 2016

Introduction to FileCollection FileCollection is an interface that extends Iterable<File>, AntBuilderAware and Buildable interfaces. How to load files in a FileCollection Suppose we have a file structure as shown in image below We can load multiple files for operation using the following syntax FileCollection collection = files('relative/path/file1','absolute/path/file2',new File('file3')) As shown in the example above we can load files in three ways From a relative path From a absolute path From a File object. We can write a gradle task to read all files in a folder or directory as follows task fileTree(){ doLast{ FileTree tree = fileTree('src') tree.each { println...

read more

Gradle : How to load and read a file in gradle task

Ekansh Rastogi | 08 December 2016

How to read a file in Gradle Task To load a file, you can take following three approaches Load file using relative path File file = file('relative/path/file') Load file using absolute path File file = file('absolute/path/file') Load a file using File object File file = file(new File('somePath')) Lets see how these three approaches work task loadFiles << { println file('src/main/resources/file1.properties') println file('/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties') println file(new File('src/main/resources/file1.properties'))} When we run the above task using command gradle -q loadFiles it will give the following output /home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties How to read a File in gradle task Say, we have a file sample.txt in src/main/resources folder...

read more

Gradle : How to check if the operation system is Windows, Linux or Mac Os.

Ekansh Rastogi | 07 December 2016

How to check if the operation system is Windows, Linux or Mac Os. org.gradle.internal.os.OperatingSystem is an interface in gradle. This interface provides methods to get th einformation about the operating system. This interface provides the following method to get the information about the operating system. task osInfo(){ doLast{ println OperatingSystem.current(); println OperatingSystem.current().name; println OperatingSystem.current().isLinux(); println OperatingSystem.current().isMacOsX(); println OperatingSystem.current().isWindows(); }} When we run the task with the command gradle -q osInfo it will give the following information. :osInfoLinux 4.4.0-51-generic amd64LinuxtruefalsefalseBUILD SUCCESSFULTotal time: 0.68 secs

read more

Gradle : Introduction to Gradle Build Lifecycle

Ekansh Rastogi | 06 December 2016

Gradle Build Lifecycle Phases A gradle build has three phases Initialization - In this phase the gradle build is initialized. Gradle scans the project and its sub projects to create a Project instance of each project and sub project. Configuration - In this phase the gradle build is configured. In this phase a Task tree is created which determines how and when to run the tasks. Execution - In this phase the gradle build is executed. This phase actually runs the tasks configured in the configuration phase. What are the Gradle Build Phases Lets take the following example build.gradle println...

read more

Gradle : How to make a task that depends on another task

Ekansh Rastogi | 06 December 2016

How to write a Gradle Task A gradle task can be written in the following two ways task hello(){ doLast(){ println "Hello World" }} Or you can write a task as follows task hello << { println "Hello World"} Here in example 2, << operator is simply an alias for doLast. Write a Gradle Task that depends on another Gadle Task Lets take an example of the following gradle file. build.gradle task openFile(){ doLast{ println "Open file" }}task readFile(dependsOn : 'openFile'){ doLast{ println "Read File" }}task closeFile(dependsOn : ['openFile','readFile']){ doLast{ println "Close File" }} Here in this example, we have...

read more

Gradle : What are task alias short forms

Ekansh Rastogi | 05 December 2016

What is a Gradle Task alias Suppose we have a gradle file as below build.gradle task copyAllFiles(){ doLast{ println "copyAllFiles" }}task copySomeFiles(){ doLast{ println "copyAllFiles" }}task copyParticularFiles(){ doLast{ println "copyAllFiles" }} Now to run the above tasks we have to run the following commands gradle -q copyAllFilesgradle -q copySomeFilesgradle -q copyParticularFiles However we can also run the gradle tasks by unique names that diffrenetiates the tasks for example gradle -q cAF // short form for copyAllFilesgradle -q cSF // short form for copySomeFilesgradle -q cPF // short form for copyParticularFiles but if we run a task with a short name...

read more

Gradle : How to define a list of Default tasks in Gradle

Ekansh Rastogi | 04 December 2016

What is a Gradle Default task ? In gradle, we can have default tasks. A default task is a task that will run if no task is specified. We can define any task a gradle default task using the following defaultTasks 'task1','task2' The defaultTasks takes a list of tasks as a parameter. These tasks will be run if no task is specidied to run. build.gradle defaultTasks 'banner','attribution'task banner(){ doLast { println "______ _ _"; println "| ____| | (_)" println "| |__ | | ___ _ __ __ _ ___ ___ ___ _ __ ___" println "| __| | |/...

read more

Gradle : How to disable Gradle Daemon

Ekansh Rastogi | 04 December 2016

How to disable Gradle Daemon There are two ways in which you can disable gradle daemons. Using Environment VariableTo disable gradle daemon using env variable you can add a new flag -Dorg.gradle.daemon=false to GRADLE_OPTS env variable. GRADLE_OPTS="-Dorg.gradle.daemon=false" Using gradle.properties To diable gradle daemon using gradle.properties, you can edit the gradle.properties file that is under the directory <User-Home>/.gradle/. You need to set the following property in the file. org.gradle.daemon=false Also Read Introduction to Gradle Gradle : What is a Gradle Daemon ? How to continue a build even if a failure occurs How to import a gradle file in another gradle...

read more

Gradle : How to list all running Gradle Daemon processes

Ekansh Rastogi | 04 December 2016

How to list all running Gradle Daemon processes To see a list of all the running gradle Daemon processes you can use the following command. gradle --status This will give you a list of all the running processes with their versions as shown in the sample output below. PID STATUS INFO 3461 IDLE 3.0 31881 BUSY 3.0 Here the output is PID - the process id of the gradle daemon process. STATUS - status of the Gradle Daemon, Idle states that this gradle daemon can be used for making builds. BUSY states that it is currently used for running some...

read more

Gradle : How to stop a running Gradle Daemon ?

Ekansh Rastogi | 04 December 2016

How to stop a running Gradle Daemon ? To stop all the runnung gradle daemon processes you can using the following command. gradle --stop This will stop all the gradle daemon processess that are running with the same gradle version as version of gradle that runs this command. Also Read Introduction to Gradle Gradle : What is a Gradle Daemon ? How to continue a build even if a failure occurs How to import a gradle file in another gradle file

read more

Gradle : What is a Gradle Daemon ?

Ekansh Rastogi | 04 December 2016

Points to Remember Gradle runs on JVM and several other dependencies. Gradle has to do boootstrap stuff whenever gradle is started. This startup process takes time and makes the build slower. To overcome these points gradle daemon was introduced. What is a Gradle Daemon ? Gradle daemon is a long lived background background process that can be reused for building gradle projects faster. Gradle wrapper saves the time for starting a new gradle instance every time and saves time required for bootstrapping and initialization.Such bootstrap tasks include Initialization of JVM Cache Project information Cache files , tasks Project structures etc...

read more

Gradle : How to run a specific gradle task or multiple tasks

Ekansh Rastogi | 30 November 2016

How to run a specific gradle task When you want to run a particular task only then you can run that task using the following command. gradle -q <task-name> -q option tells gradle that you want to run only the tasks that are provided. In this example we have instructed gradle to run only one task How to run multiple gradle tasks Multilple gradle tasks can be run using the following syntax. gradle -q <task-name> <task-name> <task-name> In second example we have told gradle to run 3 tasks, they are run in the order they are provided. However if one...

read more

Gradle : Difference between doFirst() and doLast() methods

Ekansh Rastogi | 30 November 2016

Point to Remember doFirst() and doLast() are the methods of org.gradle.api.Task interface. Both these methods take a Closure as a parameter. When a task is called this closure is called. A Gradle task is sequence of Action objects and when a task is run all these actions are called in a sequence by calling Action.execute(T) What are doFirst() and doLast() methods in a Gradle task. doFirst(Closure action) This method will add your closure as an action to the beginning of the action sequence. All the code that is written in this closure is executed first when the task is executed....

read more

Gradle : How to continue a build even if a failure occurs

Ekansh Rastogi | 30 November 2016

How to continue a build even if a failure occurs Many a times there is a need to continue running a build process even if some of the tasks fails. To run a build even if the some of the tasks fail we can use the --continue switch. It will execute all tasks even if some of them fails. Normal behavior is that build stops as soon as first failure is encountered. It will show the report of encountered failures at the end of the build. When a task fails all the tasks that depends on this task will not...

read more

Gradle : What is a Gradle Task and how to write a custom task

Ekansh Rastogi | 30 November 2016

What is a Gradle Task. Lets first create a gradle file build.gradle with the following contents in it. group 'com.ekiras'version '1.0-SNAPSHOT'apply plugin: 'java'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { testCompile group: 'junit', name: 'junit', version: '4.11'} Now, lets run the the following command from terminal in the root directory where build.gradle is saved. gradle tasks It will give the list of all the tasks that are defined. It includes both gradle default tasks and custom tasks. Now, you can run any defined task using the command. gradle <task-name> How to write a Custom Task in Gradle. A task in gradle is...

read more

Gradle : How to import a gradle file in another gradle file

Ekansh Rastogi | 29 November 2016

How to Import Gradle file in another gradle file. To import a gradle file in a gradle file you can use the following command in .gradle. We have a gradle file build.gradle and we are including two other gradle files tasks.gradle and test.gradle. apply from : 'tasks.gradle'apply from : 'https://ekiras.github.io/temp/test.gradle' Here, in line 1, we have imported tasks.gradle which lies in the same directory as build.gradle and in line 2 we have imported a test.gradle from a remote server. (Git hub pages in this case, it can be an s3 url or your server file url) Test Imported gradle file...

read more

Java 9 : How to Terminating or Destroy a Running Process

Ekansh Rastogi | 28 November 2016

Points To Remember You cannot destroy or terminate the current process not even forcefully. You can destroy a process by using the methods destroy() or forcefully using destroyForcibly(). Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process Destroy a Process There are two methods in interface ProcessHandle that can be used to destroy a process. destroy() - to destroy a process noramally destroyForcibly() - to destroy a process forcefully....

read more

Java 9 : How to get Process Information from Process Id in Java

Ekansh Rastogi | 16 November 2016

Points to Remember You need to run this code with Java 1.9 ProcessHandle.of(Long processId) method will return an object of Optional<ProcessHandle>. Optional is a class introduced in java 8 which is a container object which may or may not contain a non-null value. It has methods boolean isPresent() which returns true if a value is present else returns false. T get() method returns the object if present or else throws NoSuchElementException. Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How...

read more

Java 9 : How to start a new Process and get process id

Ekansh Rastogi | 16 November 2016

Points to Remember This post used Java 1.9 since ProcessHandle was introduced in Java 1.9. Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process Get the Current Process Information. In this example we will try to get information about the current process. For this we will use the m import java.io.IOException;/** * @author ekiras */public class StartProcess { public static void main(String[] args) { try { Process process =...

read more

Java 9 : How to get Current Process Information

Ekansh Rastogi | 14 November 2016

Points to Remember Java 9 introduced the new Process Api in java.lang package. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes. Read More Get the information of the current process Create a new process and then terminate it Terminating the current process Destroy a process forcefully Get children of a process Get the Current Process Information. In this example we will try to get information about the current process. For this we will use the method ProcessHandle.current() method, this will return the object ProcessHandle which can be used to get the information of...

read more

Java 9 : How to list all processes running on the OS

Ekansh Rastogi | 14 November 2016

Points to Remember Java 9 introduced the new Process Api in java.lang package. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes. Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process List all Processes running on the OS. To get all the processes running on the OS you can use the static method allProcesses() of the ProcessHandle, this will return a Stream<ProcessHandle> stream...

read more

Java 9 : How to use Java 9 Process Api

Ekansh Rastogi | 14 November 2016

Introduction to Java 9 Process Api The New Java 9 Processes API will help provide Identifies the processess Control of Native processes Monitoring of processes List Children of processess Start a new Process Destroy a running process Access to the process input,output and error streams. On Exit Handle when a process is destroyed or completed. Testing Process API operations In this post java program we are testing the following operations List all processess running in the OS. Print the information of the current process. Create a new process and then terminate it. Do some action when the process is destroyed...

read more

Java 9 : How to create and run a custom Module

Ekansh Rastogi | 06 November 2016

What is a Module in Java 9 ? Java Modules are a part of Project Jigsaw. A module is a named, self-describing collection of code and data. Its code is organized as a set of packages containing types, i.e., Java classes and interfaces; its data includes resources and other kinds of static information. What are the Type of Modules in Java 9 ? There are two types of Java Modules Java Standard Modules, they start with string java. Java Non-Standard Modules, they start with string jdk. Creating a Custom Module. We can make the following types of modules Module that...

read more

Java 9 : What is Project Jigsaw ?

Ekansh Rastogi | 06 November 2016

Project Jigsaw : Points to Remember It is introducded in Java 9. Its main aim is to modularize the Java SE Platform. This will modularize the JDK, and we can use only those modules that we need instead of the full JDK installation. Scale platform to run on smaller applications and devices. Also Read Creating Custom Java Modules Design Implementations of Project Jigsaw. New java commands related to Project Jigsaw added are the following --module-path <module path>... A : separated list of directories, each directory is a directory of modules. --upgrade-module-path <module path>... A : separated list of directories, each...

read more

SpringDataJPA : One to Many Mapping in Spring Boot Hibernate JPA with Spring Data

Ekansh Rastogi | 03 November 2016

Also Read One To One Mapping Let's create two entities/domains Employee and Department such that they have the following relation between them. Department has-many Employees which means an Employee can belong to only one Department and a Department can have many Employee and Department is the owner of the relation between the two. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity. Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity. In this case, Address will contian the Employee Id in >its...

read more

GIT : How to generate SSH key in Windows for GIT

Ekansh Rastogi | 25 October 2016

Points to Remember Download and install Puttygen to generate the SSH key to be used in GIT. Save the Private Key in a safe location and do not miss it. STEP 1 : Open Puttygen to generate Key Puttygen is a opensource plugin of Putty and is used to create Public/Private keys for WinSCP. When you open the puttygen you will see the following screen as shown in image below Now Select the following Select SSH-2 RSA (Type of key to generate tabs) 1024 (Number of bits to use to generate key) Click Generate button to generate the key. STEP...

read more

Logstash : No sincedb_path set, generating one based on the file path while reading csv file

Ekansh Rastogi | 07 October 2016

No sincedb_path set, generating one based on the file path Suppose you have a file at location $PATH/a.csv and we want to read and export data( elastic search server).Let's say you are trying to read this log file through the following configuration input { file { path => ["/some/path/a.csv"] start_position => "beginning" }} So, when you run this for the first time, this will work perfectly. The point to note here is that, when you have run this for the first time, logstash will automatically create a sincedb_path file at your home directory and it might look like .sincedb_1a892d89f927eb484cb12a7b7385ab72. This...

read more

SpringDataJPA : One to one Mapping in Spring Boot Hibernate JPA with Spring Data

Ekansh Rastogi | 28 September 2016

Also Read One To Many Mapping Let's create two classes Employee and Address, such that they have the following relation between them. Employee has-a Address which means a one-to-one mapping between the two and Employee is the owner of the relation. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity. Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity. In this case, Address will contian the Employee Id in its table as shown in the table structure below. This means that Employee...

read more

SpringDataJpa : How to override the domain mapping defined in Parent Entity class with MappedSuperclass

Ekansh Rastogi | 22 September 2016

Points To Remember Your Parent class should be annotated with @MappedSuperclass. Follow the Tutorial : How to handle Inheritence with Entities to know how to wrap common properties of entities to a base class. To override any property you musta. Apply the @AttributeOverride annotation on the class that need to override the propertyb. set name property of @AttributeOverride as the name of the field in super class.c. set the column property of @AttributeOverride to override the column definition of the attribute. Let's say our Base class looks as follows package com.ekiras.domain.base;import javax.persistence.*;import java.util.Date;/*** @author ekiras*/@MappedSuperclasspublic abstract class BaseDomain { @Id...

read more

SpringDataJpa : How to handle inheritance with Entities

Ekansh Rastogi | 22 September 2016

Points to Remember Mark your Base Entity class with annotation @MappedSuperclass. Define all common fields and their getter setters in this class. Make the base class abstract. Make all fields as protected so that they can be accessed in inheriting class without getters and setter. You can also define @PrePersist and @PreUpdate in this class. Fields that should be in the Base Entity Your Base Entity class should have only those field that need to be common for all your entities that will inherit this class. Sample Base Entity that you should use might look as follows package com.ekiras.domain.base;import javax.persistence.*;import...

read more

Java : How to create a Jar with single or multiple files

Ekansh Rastogi | 19 September 2016

How to create a jar file. We can make a jar file with a single class using the following commands Here can be replaced by the name of the jar file you want. 1. Create a jar file with single file jar --create --file=<FileName> <file-1> 2. Create a jar file with multiple files jar --create --file=<FileName> <file-1> <file-2> 3. Create a jar file with all files in a directory jar --create --file="<FileName> -C /path/to/dir/ ." Here -C specifies the directory and . specifies that it need to include all the files in te directory. Some of the shorthands for the...

read more

Design Patterns : Builder Pattern

Ekansh Rastogi | 18 September 2016

Points To Remember It is a Creational Design Pattern It must be used when you have multiple overloaded constructors or setters Its main purpose it to hide from the user, how the object is to be created. It is advised to make your constructors private when you are using Builder Design Pattern. What is Builder Design PatternIt is a creational design pattern. So it is only responsible for how an object must be created.There may be scenarios where there is a class with many instance variables that may be needed to create an object of the class. For this you...

read more

Groovy : Difference between findAll() and collect() methods

Ekansh Rastogi | 17 August 2016

findAll() This method will find all the items in the groovy collection that matches the IDENTITY closure. collect() This method iterates through a collection and transforms each entry element to a new element using IDENTITY closure as a transformer. It returns a new collection of elements copied from the original collection. Difference between finalAll() and collect() methods findAll() collect() findAll() will return the collection or subset of collection that satisfy the Identity closure or a condition collect() will return a new collection or sub set of collection. findAll() will not modify the entry elements of the collection collect() will modify...

read more

SpringBoot : How to create a Filter in Spring Boot Application

Ekansh Rastogi | 14 August 2016

Points To Remember Implement the class Filter. Add @Configuration annotation to the class to register it as a filter bean. Call method  filterChain.doFilter(resquest,response) to continue the request flow Call method sendError to send error, ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST); Call method sendRedirect to redirect request to error handler ((HttpServletResponse)response).sendRedirect("/errorUrl"); How to create a Filter in Spring Boot ApplicationIN order to make a filter, we have create a class SecurityFilter view plaincopy to clipboardprint? package com.ekiras.filter;      import org.springframework.core.Ordered;   import org.springframework.core.annotation.Order;   import org.springframework.stereotype.Component;      import javax.servlet.*;   import javax.servlet.http.HttpServletResponse;   import java.io.IOException;      /**   * @author ekansh   */   @Component   @Order(Ordered.HIGHEST_PRECEDENCE)   public class SecurityFilter implements Filter {          private static final boolean CONDITION = true;          @Override       public void init(FilterConfig filterConfig) throws ServletException {          }          @Override       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {           if(CONDITION==true)               chain.doFilter(request,response);           else{               ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_BAD_REQUEST);           }          }  ...

read more

SpringBoot : What is Spring Boot

Ekansh Rastogi | 10 August 2016

Spring Boot : IntroductionSpring Boot can be referred as Spring on Steroids. Spring boot is a wrapper written over spring modules to allow users to create fast paced spring applications without doing the redundent configurations needed to setup the application.Features provided by Spring Boot CLI applications - enables to create a single class application. Embedded Tomcat and Jetty Auto configurations for most of the libraries like mysql, mongo, amqp etc No Xml required for setup or configurations. Ability to package the application as both war and jar. Dependency Management using starter projects and BOM's. For example, When you create a spring application...

read more

Ionic : How to get list of all plugins installed

Ekansh Rastogi | 04 August 2016

How to get list of all plugins installed for Ionic App You can get a list of all plugins that you have installed on for your ionic app by the following command cordova plugin list Make sure you are in your app directory. Output of the above command will result as follows. cordova-plugin-admob 2.2.0 "AdMob"cordova-plugin-admobpro 2.18.0 "AdMob Plugin Pro"cordova-plugin-device 1.1.2 "Device"cordova-plugin-extension 1.5.1 "Cordova Plugin Extension"cordova-plugin-google-analytics 0.8.1 "Google Universal Analytics Plugin"cordova-plugin-splashscreen 3.2.2 "Splashscreen"cordova-plugin-statusbar 2.1.3 "StatusBar"cordova-plugin-whitelist 1.2.3-dev "Whitelist"cordova-plugin-x-socialsharing 5.1.2 "SocialSharing"cordova-plugin-x-toast 2.5.2 "Toast"cordova-sqlite-storage 1.4.2 "Cordova sqlite storage plugin"ionic-plugin-keyboard 2.2.0 "Keyboard" Also you can view the file android.json inside the folder path-to-app/plugins/ and you will...

read more

Arrays : Finding the Element in array where next element is +1, +0 or -1

Ekansh Rastogi | 03 August 2016

Problem Statement You are given an array where each element follows the rule that given any index, the number at that index will either be  +1 of the number at that index. +0 of the number at that index. -1 of the number at that index. Suppose the array is  Sample Input arr       = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4}; search = 5 Sample Output 6  (First occurrence of search ) Sample Input arr       = {1,2,1,2,1,2,1,2,1,2}; search = 5 Sample Output 1  ( Element is not found in the array) Algorithm Star iterating from start of the array. Check if the value...

read more

Spring : Difference between @Autowired, @Inject and @Resource

Ekansh Rastogi | 14 July 2016

Points To Remember @Inject is not a spring feature you need to include javax inject dependency in order to use @Inject. @Autowired is Spring annotation used to inject dependency just like @Inject. It use @Qualifier annotation to differentiate between the beans. @Resource is also Spring annotation, but it uses bean name to inject dependencies and differentiate between beans. Problem Statement :: StructureIn order to show how @Autowired @Inject and @Resource annotations work  we will create 3 services Interface PersonService, this is the interface for all person related operations. Class EngineerService, this is the service that will do operations for engineer. Class ManagerService,...

read more

SpringBoot : What are Profiles in Spring Boot Application

Ekansh Rastogi | 28 June 2016

What are Profiles in Spring BootProfiles can be seen as different environments in spring boot application. Suppose you are working on an application where you have different staging environments like Dev, QA, UAT, Production etc. So you will have different configurations for each environment, for this kind of applications what you need is having different values that can be switched depending upon some flags. In early days, people used to write configurations for all environments and comment the unused environments. But with Spring Boot we can do this without commenting any code by use of Profiles. Suppose we have database...

read more

SpringBoot : How to display static html file in Spring boot MVC application

Ekansh Rastogi | 23 June 2016

Points To Remember In order to serve static files like js, css, images etc ,all your files should be under the resources/static folder. Spring application can serve all the static files inside folders resources/static/ resources/public/ In order to serve html files from spring boot application  your html files should be under static/public folder you need to add view controller to serve html file How to display static html file in Spring boot MVC application Step 1 : Extend Class WebMvcConfigurerAdapter You should create a class that extends WebMvcConfigurerAdapter Your class should have @Configuration annotation. You class should not have @EnableMvc annotation. Override...

read more

ShellScript : How to write to the beginning of a file in Linux

Ekansh Rastogi | 06 June 2016

How to write to the beginning of a file using shell script in LinuxSuppose, we have a file release.txt and we want to write to first line of the of the file whenever a new release is made. sed -i '1i\'"text to write " filename Using the above command as sed -i '1i\'"newVersion-RELEASE" release.txtThis will append the text to the first line of the file release.txt In the example shown above , we have added a new version 2.0.0-RELEASE to version.txt file .If you want to do this using a shell script then you can do it as follows #!/bin/bashfunction writeAtBeginning(){...

read more

SpringBoot : How to run Spring boot application to custom port

Ekansh Rastogi | 23 May 2016

Points To Remember Default port for spring boot application is 8080. You can change the port number in the following ways from application.properties command line arguments How to run Spring boot application to custom portIn order to run a spring boot application on a custom port you can specify the port in application.properties. server.port=8090 If you are using environment specific properties file then you can define server.port property in each of your properties file.You can alternatively set the port from command line arguments like below gradle -Dserver.port=8090 bootRun This will override any configuration of port given inside the properties file or application.yml file....

read more

SpringSecurity : How to disable Session Creation for Stateless Authentication

Ekansh Rastogi | 12 April 2016

How to disable Session Creation for Stateless AuthenticationWe need to disable session creation for authenticating requests based on token based authentication.This can be easily configured by the following configurations. view plaincopy to clipboardprint? package com.ekiras.ss.security.config;      import com.ekiras.ss.security.filter.TokenAuthenticationFilter;   import org.springframework.context.annotation.Bean;   import org.springframework.core.Ordered;   import org.springframework.core.annotation.Order;   import org.springframework.security.config.annotation.web.builders.HttpSecurity;   import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;   import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;   import org.springframework.security.config.http.SessionCreationPolicy;   import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;      /**   * @author ekansh   * @since 11/4/16   */   @EnableWebSecurity   @Order(Ordered.LOWEST_PRECEDENCE-100)   public class RestSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {          @Override       protected void configure(HttpSecurity http) throws Exception {              http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);          }               }   package com.ekiras.ss.security.config; import com.ekiras.ss.security.filter.TokenAuthenticationFilter; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * @author ekansh * @since 11/4/16 */ @EnableWebSecurity @Order(Ordered.LOWEST_PRECEDENCE-100) public class RestSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {...

read more

SpringSecurity : Authenticate User with Custom UserDetailsService

Ekansh Rastogi | 06 April 2016

Points To Remember Create class that implement UserDetailsService and override loadUserByUsername() method. Throw UsernameNotFoundException if no user was found by username. Register this class as a bean by overriding WebSecurityConfigurerAdapter. Authenticate User with Custom UserDetailsService Step 1 : Create Entities for User and Role Create Entity User package com.ekiras.ss.domain;import javax.persistence.*;import java.util.Set;/** * @author ekiras */ @Entitypublic class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String username; private String password; private boolean enabled; @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL) @JoinTable(joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<role> roles; // GETTERS and SETTERS} Create Entity Role package...

read more

SpringSecurity : Configure JDBC Authetication using MYSQL Query

Ekansh Rastogi | 05 April 2016

Create Database Schema and tables First we will create a Database Schema as shown in the image below. We have to create 3 Tables in database. user - to hold the user data. role - to hold the data of roles that a user can have. user_roles - to hold the mapping of user and roles. Configure JDBC Authetication using MYSQL Query. Step 1 : Add the Dependencies compile('org.springframework.boot:spring-boot-starter-data-jpa') runtime('mysql:mysql-connector-java') Step 2 : Add the Datasource properties spring.jpa.hibernate.ddl-auto=updatespring.datasource.url=jdbc:mysql://localhost/demo_ssspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.maxActive=10spring.datasource.max-idle=4spring.datasource.min-idle=2spring.datasource.test-while-idle=truespring.datasource.test-on-borrow=truespring.datasource.validation-query=SELECT 1spring.datasource.time-between-eviction-runs-millis=60000spring.datasource.min-evictable-idle-time-millis=300000spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext Step 3 : Add the Datasource Bean to SpringSecurity Configurer class @Autowired private DataSource dataSource; Add queries to be fired for...

read more

SpringSecurity : How to list the User Authorities in Controller,Filter and Services

Ekansh Rastogi | 04 April 2016

How to get the User Authorities in Controller,Filter and Services You can get the user authorities from the SecurityContextHolder. getContext().getAuthenication().getAuthorities() will return the authorities for the currently logged in user. You cannot add the user Authority to this collection of user Authorities. public Object authorities(){ Set<grantedauthority> authorities = (Set<grantedauthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); if(authorities.contains("ADMIN")){ // do something return ""; }else if(authorities.contains("USER")){ // do something else return ""; }else{ // do something else return ""; } } As shown in the example above you can get the user authorities by the following method. Collection authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities(); Also Read Configure Spring Security with Spring...

read more

SpringSecurity : Implement Role Hierarchy with In-Memory Authentication

Ekansh Rastogi | 01 April 2016

Implement Role Hierarchy with In-Memory Authentication In order to configure role hierarchy, you need to make a bean RoleHierarchy define a expressionhandler to read role hierarchy package com.ekiras.ss.config;import org.springframework.context.annotation.Bean;import org.springframework.security.access.expression.SecurityExpressionHandler;import org.springframework.security.access.hierarchicalroles.RoleHierarchy;import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.web.FilterInvocation;import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;/** * @author ekiras */@EnableWebSecuritypublic class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{ private SecurityExpressionHandler<filterinvocation> webExpressionHandler() { DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy()); return defaultWebSecurityExpressionHandler; } @Bean public RoleHierarchy roleHierarchy(){ RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); roleHierarchy.setHierarchy("ADMIN > USER"); return roleHierarchy; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("ekansh") .password("password") .authorities("USER", "ROLE"); auth.inMemoryAuthentication() .withUser("admin") .password("admin") .authorities("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception {...

read more

SpringSecurity : Configure In Memory Authentication

Ekansh Rastogi | 01 April 2016

Configure Spring Security to Authenticate user using In-Memory Authentication. To implement inMemory authentication, all you need to do is extend WebSecurityConfigurerAdapter. override configure(AuthenticationManagerBuilder) method add username, password and roles/authorities for authentication. After adding the following class to your application, you will be able to login using these username password pairs. package com.ekiras.ss.config;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/** * @author ekiras */@EnableWebSecuritypublic class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("ekansh") .password("password") .roles("USER", "ROLE"); auth.inMemoryAuthentication() .withUser("admin") .password("admin") .roles("ADMIN"); }} As shown in the code above, we have configured two user-password pairs, username : user , password : user...

read more

SpringSecurity : How to configure Spring Security with Spring boot

Ekansh Rastogi | 01 April 2016

How to integrate Spring Security with Spring boot Add the following dependency in your build.gradle compile('org.springframework.boot:spring-boot-starter-security') Basic Spring Security Configurations Add the dependency in your build.gradle Run your application gradle bootRun for gradle and mvn spring:run for maven The default username is user and the password will be printed in the logs as shown in the image above. So in this case you can login using username = userpassword = // printed in logs Note A new password will be created each time the application restarts. Spring Security Configurations with defined username and password Add the following in your application.properties...

read more

SpringBoot : Read JSON object from POST Request in Filter

Ekansh Rastogi | 26 March 2016

Points To RememberAdd the following dependency to the gradle project. compile('com.fasterxml.jackson.core:jackson-databind:2.7.1-1') Read JSON in Filter and bind it to POJO class You can read the JSON inside a Filter class in SpringBoot by  Create a BufferedReader object by reading request object. Create an ObjectMapper object. Read JSON from bufferedReader object and bind it to any POJO class. view plaincopy to clipboardprint? package com.ekiras.test;      import com.fasterxml.jackson.databind.JsonMappingException;   import com.fasterxml.jackson.databind.ObjectMapper;      import javax.servlet.*;   import java.io.BufferedReader;   import java.io.IOException;      /**   * @author ekansh   * @since 26/3/16   */   public class MyFilter implements Filter {             @Override       public void init(FilterConfig filterConfig) throws ServletException {           // some init code        }          @Override       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {           // declare a reader             BufferedReader reader;           try{               // get reader from the request object               reader = request.getReader();               // create an object mapper instance               ObjectMapper mapper = new ObjectMapper();               // read values from the reader object and map the response to desired class.               mapper.readValue(reader,Object.class);           }catch (JsonMappingException e){               e.printStackTrace();           }       }          @Override       public void destroy() {  ...

read more

How to use & configure SessionFactory Bean

29 February 2016

Points To Remember Add the SessionFactory bean in the Application class. Add the Current Session Context class in application.properties. Use the SessionFactory using @Autowired annotation. How to Configure & Use SessionFactory Bean

read more

How to sort Array List based on Custom Order

Ekansh Rastogi | 23 February 2016

How to sort Array List using Custom Order On many occasions we need to sort an array list or linked list based on custom logic. Suppose you have a Quiz application and you want to return questions based on a custom question id.

read more

SpringBoot : How to do Exception Handling in Rest Application

Ekansh Rastogi | 18 February 2016

Points To Remember There are three ways to do exception handling in spring boot application. Global Level using -  @ControllerAdvice Controller Level using - @ExceptionHandler  Method Level using - try/catch   Difference between @ExceptionHandler and @ControllerAdvice How to do Exception Handling in Rest Application To demonstrate Exception Handling we will make three Exceptions. BaseException that will be parent of all the Custom Exceptions. CustomException1 that extends Base Exception. CustomException2 that extends Base Exception. We will create the following methods ex1() throws BaseException ex2() throws CustomException1 ex3() throws CustomException2 ex4() throws NullPointerException  ex5() throws NumberFormatException and now we will see how we can handle these exceptions using above...

read more

SpringBoot : How to disable the Application Banner

Ekansh Rastogi | 17 February 2016

How to disable the Application Banner You can disable the application banner using the following ways You can diable by adding following in application.properties file spring.main.web_environment=falsespring.main.banner_mode=off You can disable the same by adding the following code to your main Application class. public static void main(String[] args) { new SpringApplicationBuilder() .showBanner(false) .sources(Application.class) .run(args); } By following any of the above steps you can disable the banner in the spring boot application. Note :: How to add Custom Banner in Spring Boot Application.

read more

SpringBoot : Adding Custom Banner in Application

Ekansh Rastogi | 17 February 2016

Adding Custom Banner in Spring Boot ApplicationYou can replace the default spring boot banner for your application to give a more meaningful name to it. Steps to add Custom Banner in application. Go to the link ASCII art generator and generate an ascii art. Create a file named banner.txt under resources folder. That's it, rerun your application and you will be able to see your new banner. Note :: name of the file should be banner.txt and placed in folder resources Note :: How to disable the banner in Spring boot Application.

read more

Spring Boot : How to enable Hibernate SQL Logging using application.properties

Ekansh Rastogi | 06 February 2016

How to enable Hibernate SQL Logging in Spring Boot using application.propertiesYou can enable hibernate sql logging level to Debug. This will print the sql queries fired by hibernate. logging.level.org.hibernate.SQL=DEBUG Your complete SQL configuration may look like following spring.jpa.hibernate.ddl-auto=updatespring.datasource.url=jdbc:mysql://localhost/ekirasspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverlogging.level.org.hibernate.SQL=DEBUG

read more

SpringBoot : Internalization and i18n messages for Rest

Ekansh Rastogi | 19 January 2016

Points To RememberAccept the Locale from Headers e.g @RequestHeader("Accept-Language") Locale locale Step 1 : Define Beans for InternationalizationAdd the files in resources/i18n folder as shown in image Add the following to the Application class ( The main class) @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.US); // Set default Locale as US return slr; } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasenames("i18n/messages"); // name of the resource bundle source.setUseCodeAsDefaultMessage(true); return source; } Now inject the MessageSource Bean where you want to internationalize the message. We will be doing it in the Controller. Note...

read more

SpringBoot : How to read Header from Request and bind to variable

Ekansh Rastogi | 19 January 2016

How to read Headers in Spring Boot Controller How to Allow Custom Headers in Spring Boot  Suppose we have a controller and want to bind the Headers to a variable, then we can do the following @RequestHeader(value = "Accept-Language", defaultValue = "en") String locale This will bind the Header Accept-Language, to the variable locale. value="" It defines the name of the header to bind to the variable required= boolean It tells if this is mandatory header or not. default value is true defaultValue ="" It can be used to give a default value if the header is not present. Similarly...

read more

SpringBoot : How to bind data from url to a variable

Ekansh Rastogi | 19 January 2016

Binding data from URL to a variable Suppose you want to have bind some data from URL then you can do the following create the @RequestMapping annotation e.g /list/{id} /{version}/list/{id} bind the Url parameters using @PathVariable annotation e.g @PathVariable("id") Long id @PathVariable("version") int version,@PathVariable("id") Long id Complete code may look like this, @RequestMapping("list/{id}") public Object list(@PathVariable("id") Long id ){ // Logic goes here } @RequestMapping("/{version}/list/{id}") public Object list(@PathVariable("version") int version,@PathVariable("id") Long id ){ // Logic goes here }

read more

JPA : One to Many Mapping using Hibernate Spring Boot

Ekansh Rastogi | 19 January 2016

STEP 1 :: Add the dependenciesYou need to add the following dependencies in your build.gradle file. compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-jdbc') runtime('mysql:mysql-connector-java') STEP 2 :: Make Entity classesYou need to create two entity QUESTION and TOPIC.Here the Topic Entity will have an annotation @OneToMany , this indicates the following This one topic can have many questions. All the questions will be deleted or updated when topic is deleted/updated. Its mapping is defined by Entity Question by the mapping of topic variable. It will give a list of all question of a topic when it is fetched If you do not need questions when...

read more

Java : How to generate a random number between two given numbers

Ekansh Rastogi | 07 January 2016

How to find a Random Number Between two given Numbers Suppose we want to generate a number between two given numbers X and Y then we can use the following two approaches. Approach 1 Generate a random number between 0 to (Y - X ) just add this to X. i.e X+N For, example if we have to calculate a random number between 100 and 150, then in that case X = 100 , Y = 150,Then we calculate a number between 0 to (150-100)  i.e  0 to 50. Thus, we just need to add this to 100 to get...

read more

Android : How to send Object from One Activity to Another Activity

Ekansh Rastogi | 22 December 2015

Points To RememberYou can send an Object from one Activity to another using two ways Make a class extend Parcelable  Make class Serializable Parcelable is a faster way to send and receive data, but it needs a lot of code to be written and manage in a particular way, however Serializable is a Java technique and is much simpler than the former way. Send Object from one Activity to Another Activity using SerializableWe will make a POJO class Person that needs to be sent from ActivityOne to ActivityTwo. The Person class just needs to implement the serializable interface.The code may...

read more

Java : How to Make a Http GET request and read response

Ekansh Rastogi | 17 December 2015

How to Make a Http GET request and read responseSteps to make a HTTP GET request Make URL object. Make HttpURLConnection object from URL object and type cast it to HttpURLConnection Set Request method to GET. Add Headers using method setRequestProperty() if required. Use BufferedReader to read the input stream of the connection. Read the response from buffered reader object. The code to implement the above steps is shown below.

read more

Android : How to disable back button to Splash Screen Activity

Ekansh Rastogi | 12 December 2015

Points To Remember Ideally splash screen should be shown only at the start on the Android Application. Application should not go back to the Splash screen when back button is pressed How to disable back button to Splash Screen ActivityIn order to disable your application to go back to the your can do the following Disable the Back Button on the Activity called just after the Splash Screen. Remove the Splash Activity from Application life-cycle/history. You can disable the back button on any activity programmatically using the following   @Overridepublic void onBackPressed() {} You can also do the same by...

read more

Java : How to make enums inside java class

Ekansh Rastogi | 12 December 2015

How to make enums inside java classYou can use enums inside a class as shown in the code below. User.Gender.MALE or FEMALE is always associated with the user property. However if you need Gender to be generic and u want to use it with animals also, then you might want to keep this enum in a separate class. package com.ekiras.demo;public class User { public enum Gender{ MALE, FEMALE } private String name; private String address; private String email; private String password; private Gender gender = Gender.MALE; } You can also use the enums with parameters inside class as shown below. package...

read more

Android : How to implement Material Design Tab Layout

Ekansh Rastogi | 10 December 2015

How to implement Material Design Tab Layout Android Material Design Tab Layout with toolbar Android Material Design Tab Layout without toolbar looks like the following. You can implement the Tab Layout in android by using the following steps. Step 1 : Add the design dependency in the project dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.0' compile 'com.android.support:design:23.1.0'} After adding the dependency, synchronize your project so that gradle downloads and add the dependency. Step 2 : Layout Structure for the activityYour activity structure should be like following. --CoordinatorLayout----AppBarLayout------TabLayout----ViewPager Now let's understand why we need to follow this...

read more

Spring Security : Getting started with Spring Security and Spring Boot

Ekansh Rastogi | 18 November 2015

Points To Remember Add dependency of spring security Add custom username password in application.properties A unique password is generated each time application is started if no authentication process is specified. You can configure your own authentication  providers, managers, filters, entry points, tokens etc as required. Getting started with Spring Security and Spring BootIn order to apply Spring Security to a Spring Boot application, firstly you need to add the dependency in the application as follows In Maven you can do it as follows. <dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.3.RELEASE</version> </dependency></dependencies> In Gradle you can do it as follows. dependencies { compile...

read more

Java : How to write a File in Java using FileWriter

Ekansh Rastogi | 11 November 2015

Write a File in Java using FileWriterYou can write a file using FileWriter as shown in the code below. package com.ekiras.demo;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.util.Date;class FileDemo { public static void main(String args[]) { readFile(); } public static void readFile() { System.out.println(" Start :: writing file"); try { File file = new File("/home/ekansh/myFile.txt"); FileWriter fileWriter = new FileWriter(file); fileWriter.write("hello, this file is created at :: " + new Date()); fileWriter.flush(); fileWriter.close(); System.out.println(" End :: writing file"); } catch (IOException e) { e.printStackTrace(); } }} You can write the data using the write() method and then call the flush() method to force...

read more

JavaScript : What is Javascript Hoisting

Ekansh Rastogi | 04 November 2015

What is Hoisting in Javascript ??In Javascript the variable declaration can be done at any place inside the function or inside the script. Where a variable is declared makes no difference because the javascript interpreter always move the variable declarations silently to the top of the scope where the variable is used.For example, everyone will be fine the following javascript code. <script> var num; num = 5; function foo(){ alert(num); } foo(); </script> And, all will be able to guess that the function foo() will alert value 5. However, the following code will confuse a lot of the developers, since...

read more

SpringBoot : How to set active profile in spring boot application

Ekansh Rastogi | 03 November 2015

Points To RememberThere are two ways to set the spring profiles Using OS environment variables Using -D arguments Must Read :: What are profiles in Spring boot. How to set active profile in spring boot applicationIf you want to set Operating System Environment variables for your application the you can do as follows export SPRING_PROFILES_ACTIVE=developmentexport SERVER_PORT=8090gradle bootRunjava -jar build/libs/demo-1.0.0.jar If you want to specify it each time while running jar then you can do as follows java -jar -Dspring.profiles.active=development build/libs/dem-1.0.0.jarjava -jar -Dserver.port=8090 build/libs/demo-1.0.0.jar

read more

OOJS : Create an Object in Javascript

Ekansh Rastogi | 01 November 2015

Points To Remember You can create objects of a function in javascript. Function can have both private and public methods. Functions can inherit other functions Create an Object in JavascriptLet us create a User object in javascript. var User = function() { _self = this; var _name; _self.getName = function() { return _name; } _self.setName = function(name) { _name = name; } _self.toString = function() { return "Person{name::" + _name + "}"; }} Here User is a function name is a private variable and will not be accessible outside the User function. _self is used to save the this reference, this...

read more

Hazelcast : Auto Reconnect to Hazelcast Server

Ekansh Rastogi | 01 November 2015

Points To RememberYou can call the method getLifecycleService().isRunning() to check if the hazelcast clinet is up and running. Auto Reconnect to Hazelcast ServerYou can use the following code to reconnect to Hazelcast server, in case the hazelcast client looses the connection to the hazelcast server. if(!(hazelcastInstance!=null && hazelcastInstance.getLifecycleService().isRunning())){ // create a new hazelcast connection } return hazelcast instance

read more

Hazelcast : Setup Hazelcast Server in Spring Boot Application

Ekansh Rastogi | 31 October 2015

Following are the steps to setup to Hazelcast server Put data in hazelcast Retrieve data from hazelcast Step 1 : Add the Hazelcast dependency compile("com.hazelcast:hazelcast:3.3.5") compile("com.hazelcast:hazelcast-client:3.3.5") Step 2 : Initialize the Hazelcast Instance (Hazelcast Server) Config config = new XmlConfigBuilder().build();HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); The above code will start the Hazelcast server with default settings. For more settings you can refer this blog. Step 3 : Connect to Hazelcast server using a Hazelcast ClientNow to need to get a Hazelcast client to get and post data to the hazelcast server. Following is an example of how to get the hazelcast client....

read more

Spring Boot : How to create a Bootstrap class

Ekansh Rastogi | 30 October 2015

Points To RememberIn order to create a class that acts like a bootstrap for the application, that class needs to implement the InitializingBean of the package org.springframework.beans.factory.InitializingBeanHow to create a Bootstrap class in spring boot application Following is an example of a Bootstrap class. This class will be executed first when the application is coming up and is ready to server requests. Any class that implements InitializingBean will be executed before the application is up and its afterPropertiesSet method will be called. public class Bootstrap implements InitializingBean

read more

Spring Boot : How to register a Filter in the Application

Ekansh Rastogi | 27 October 2015

Steps : How to register a Filter in the Application Make a class. Make it a spring bean by using @Component annotation. Implement Filter interface to register it as a Filter in the Filter chain. Use @Order annotation to define the order of the filter in the filter chain. Following is the example of how you can implement the Filter using the above mentioned steps

read more

Spring : How to define Filter order in Filter Chain in Spring Boot

Ekansh Rastogi | 27 October 2015

Points To RememberFrom Spring boot version you can define the order of your filters by defining order for your filters using @Order annotation. You can use @Order annotation as follows to make a filter to be first in the filter chain. @Order(1) How to define Filter order in Filter Chain in Spring BootFollowing is the example where we have registered two filters Security Filter - To block unauthorized requests Tracking Filter - To log each request coming to the server ###### security filter###### tracking filter

read more

Java : How to check if the field of a class is STATIC by Reflection

Ekansh Rastogi | 26 October 2015

Points To Remember You can use Reflection to check if the field of a class is static or not. You need to get the modifiers of the field to check if the field is static. How to check if the field of a class is static by ReflectionThe following is the only way to check if the field is static or not field.getModifiers()& Modifier.STATIC) == Modifier.STATIC Following program shows how to get the static fields from a class. package com.ekiras.demo;import java.lang.reflect.Field;import java.lang.reflect.Modifier;public class Test { public static void main(String args[]){ Field[] fields = Person.class.getDeclaredFields(); for(Field field : fields){ if((field.getModifiers()& Modifier.STATIC) ==...

read more

Java : How to check if the field of a class is FINAL by Reflection

Ekansh Rastogi | 26 October 2015

Points To Remember You can use Reflection to check if the field of a class is final or not. You need to get the modifiers of the field to check if the field is final How to check if the field of a class is final by ReflectionThe following is the only way to check if the field is final or not field.getModifiers()& Modifier.FINAL) == Modifier.FINAL Following program shows how to get the final fields from a class. package com.ekiras.demo;import java.lang.reflect.Field;import java.lang.reflect.Modifier;public class Test { public static void main(String args[]){ Field[] fields = Person.class.getDeclaredFields(); for(Field field : fields){ if((field.getModifiers()& Modifier.FINAL) ==...

read more

Java : Exception in thread "main" java.util.ConcurrentModificationException

Ekansh Rastogi | 25 October 2015

When Exception in thread "main" java.util.ConcurrentModificationException occurs. package com.ekiras.demo;import java.util.ArrayList;import java.util.List;public class Test { public static void main(String args[]){ // create a new list List<String> list = new ArrayList<String>(); // add 50 items to the list for(int itr=0;itr<50;itr++) list.add("user-"+(itr+1)); // try to remove item from list while iterating the list for(String str : list){ if(str.equals("user-15")){ list.remove(str); } } } } The above code will give the following error. Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at testing.Test.main(Test.java:18) How to avoid ConcurrentModificationException Create the list of type CopyOnWriteArrayList, this will create a new copy of list for every operation performed...

read more

Android: Pagination in Custom List View

Ekansh Rastogi | 22 October 2015

Points To RememberYou can refer to blog - Create list view with custom list view adapter.Now we will implement pagination in this list view. Pagination in Custom List View Download Source from GitHub We will add 20 items each time to the list view. After 18th element is displayed on the screen we will call a method to load new items to the list view, so that user does not wait for new items to be loaded.(In real cases you might be loading from a server and this might take much time). We will restrict our pagination after 400 elements...

read more

SpringBoot : No 'Access-Control-Allow-Origin' Access-Control-Allow-Origin

Ekansh Rastogi | 22 October 2015

Points To Remember This error occurs when Server does not allow cross domain headers. Application does not allow cross domain headers. Custom headers provided by request is not accepted by the application. How to Solve : No 'Access-Control-Allow-Origin' Access-Control-Allow-Origin error In order to allow cross domain ajax calls to your Server you need to allow the Cross Domian Headers in your application. You can allow the cross domain requests from your application in Spring boot by adding a CORS Filter as shown below. response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header"); Here you need to specify the following Headers...

read more

Android : Create a List View with custom List View Adapter

Ekansh Rastogi | 19 October 2015

Points To Remember You need to create a custom List Adapter to show a model class in the list view. You need to create a xml file to display, how each item of the list will look on the UI. You need to set the Tag in the view, so that your data does not refresh due to scroll. Download from GitHub Create a List View with custom List View AdapterYou need to make Person Model class - show data on UI from this class Person Adapter - create the list view and inflate the view Main Activity - to...

read more

Android : Difference between gravity and layout_gravity

Ekansh Rastogi | 19 October 2015

Points To RememberThere are two attributes for a View in android to align its content gravity layout_gravity The basic difference between the two is that android:gravity is used for child elements of the view. android:gravity_layout is used for this element with respect to parent view. So, if you have a layout like <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" > <TextView android:layout_width="match_parent" android:layout_height="50dp" android:text="EkiRas" android:textSize="22dp" android:gravity="center" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" > // Other Elements </LinearLayout></LinearLayout> In the above code, outer LinearLayout will set its child elements in center. TextView gravity:center will set its ocntent in center. inner LinearLayout will be aligned in the center...

read more

Android : How to hide and show a view

Ekansh Rastogi | 15 October 2015

Points To RememberThere are three things yo can do to set the visibility of a VIEW in android VISIBLE - it makes the VIEW visible . INVISIBLE - it makes the VIEW invisible but it still takes the space occupied by the View element on the screen. GONE - it makes the VIEW invisible and also hides the space occupied by the view on the screen. How to make a TextView VisibleThe following code makes the TextView invisible to the user and also hides the space occupied by the TextView on screen <TextView android:id="@+id/text_view_name" android:visibility="gone" android:layout_height="30dp" android:textColor="@android:color/holo_blue_dark" android:paddingLeft="15dp" android:textStyle="bold" android:layout_centerVertical="true"...

read more

RestTemplate : How to get response from a server by HTTP GET call

Ekansh Rastogi | 12 October 2015

Points To RememberYou need to add the following dependency to your project to use Spring Rest Template. compile('org.springframework:spring-web:3.0.2.RELEASE') How to get response from a server by HTTP GET callFollowing are the methods that can be used to get the response from a url using HTTP GET method. getForObject() This method takes a URL, Response class (it tells that the response should be bound to this class). RestTemplate restTemplate = new RestTemplate();String response = restTemplate.getForObject("http://localhost:8080/someUrl",String.class); Following method will make a Http GET call with params. Map<String,String> params = new LinkedHashMap<String, String>();params.put("userId","1"); RestTemplate restTemplate = new RestTemplate();String response = restTemplate.getForObject("http://localhost:8080/someUrl",String.class,params); This method does...

read more

Android : How to change the Android Application Label in Action Bar

Ekansh Rastogi | 09 October 2015

Points To RememberAndroid saves the Application level Settings like App Icon, App Label etc in the AndroidManifest.xml file. How to change the Android Application Icon Go to the Application > manifests > AndroidManifests.xml file and look for the following lines. <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ekiras.activity" > <application android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/AppTheme" > // Your activities are declared here <activity></activity> </application></manifest> You can set the Application icon in strings.xml by name app_name in the values folder. <resources> <string name="app_name">Ekiras</string> <string name="action_settings">Settings</string></resources> If you do not want to keep them in strings.xml file then you can simple assign them in AndroidManifests.xml file , however it...

read more

Android : How to create a Basic List View

Ekansh Rastogi | 09 October 2015

Points To Remember You need to create a ListView in your activity. Then create a view for Item of the ListView. Create an Adapter and a list of objects to display. Pass the List of objects to the ListView. How to create a Basic List View Your Activity may look like the following activity_main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:text="Planet List" android:textAlignment="center" android:textSize="24dp" /> <ListView android:id="@+id/list_view_drawer" android:layout_marginTop="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" android:divider="@android:color/holo_blue_light" xmlns:android="http://schemas.android.com/apk/res/android" /></RelativeLayout> Your item may look like the following list_view_item.xml <?xml version="1.0" encoding="utf-8"?><TextView android:layout_height="50dp" android:textAlignment="gravity" android:textColor="@android:color/holo_blue_dark" android:paddingLeft="15dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:gravity="center_vertical" android:layout_width="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" /> Your...

read more

Android : How to change ActionBar/ ToolBar color

Ekansh Rastogi | 07 October 2015

Points To RememberYou can just override the primary_material_dark in the colorx.xml file in values folder. How to change ActionBar/ ToolBar color We will create a new file colors.xmlif it does not exist. Override the Primary color of the theme Theme.AppCompat.Light.DarkActionBar See the results <?xml version="1.0" encoding="utf-8"?><resources> <color name="primary_material_dark">#1B5891</color></resources> Your styles.xml file may look like the following <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> </style></resources> and the AndroidManifest.xml may look like following <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ekiras.demo" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"...

read more

Android : Add Action Icon / Action button on Action Bar

Ekansh Rastogi | 05 October 2015

Points To Remember You need to create a file in res > menu > menu.xml You can use showAsAction property to decide if to show the action icon on action bar or not.  Adding Action Icon Action button on Action BarYou can choose either of the following app:showAsAction="never" This will show the action in the list view when menu icon is pressed. app:showAsAction="ifRoom" This will show the action in the action bar if the amount of space required to show the action is available on the Action bar. <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".HomeActivity"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="#Settings" app:showAsAction="never" /> <item...

read more

Android : How to change application icon

Ekansh Rastogi | 30 September 2015

Points To RememberAndroid saves the Application level Settings like App Icon, App Label etc in the AndroidManifest.xml file. Add your icon image as icon.png in the drawable folder. How to change application icon Your Application structure looks like the following. Add the icon.png folder in the drawable folder Open the Application > manifests > AndroidManifests.xml file Add android:icon="@drawable/icon" in the application root. Your AndroidManifests.xml file should look like following <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.ekiras.activity" >     <application        android:allowBackup="true"        android:icon="@drawable/icon"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        // Your activities are declared here        <activity></activity>    </application> </manifest> After this you will be able to see the icon image as the application icon.

read more

Hibernate : Make a field Non Updatable in an Entity

Ekansh Rastogi | 29 September 2015

Points To RememberBy default all the fields in the Hibernate Entity are updatable and insertable. To make a field non updatable in hibernate you nee to add the annotation @Column(updatable = false) Make a field Non Updatable in an Hibernate EntitySuppose you have a User class and you want to make email as a non updatable field, all you need to do is add the @Column(updatable = false) annotation as shown in the example below. @Entitypublic class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "email",updatable = false, nullable = false, unique = true) private String email; // GETTERS and...

read more

How to Send Rest Response For Lazy fetched Hibernate Objects with Jackson

Ekansh Rastogi | 23 September 2015

How to Send Rest Response For Lazy fetched Hibernate Objects with JacksonJust add the following class to your application and your jackson will be configured to send the JSON response for the LAZY fetched domain objects. You need to add the dependency  compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.6.1") @Configuration@EnableWebMvcpublic class HibernateAwareObjectMapper extends WebMvcConfigurerAdapter { //More configuration.... /* Here we register the Hibernate4Module into an ObjectMapper, then set this custom-configured ObjectMapper * to the MessageConverter and return it to be added to the HttpMessageConverters of our application*/ public MappingJackson2HttpMessageConverter jacksonMessageConverter(){ MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); //Registering Hibernate4Module to support lazy objects...

read more

Spring : How to get Current Profiles in Spring Application

Ekansh Rastogi | 21 September 2015

Points To RememberYou can use the Environment interface in package org.springframework.core.env to get the current profiles in spring application.You can make use of the following methods to get the information about the profiles. acceptsProfiles(String ...profiles) - returns if the profiles given in input is active. getActiveProfiles() - Gives a list of profiles explicitly made active for this enviornment. getDefaultProfiles() - gives a set of profiles to be active by default if no active profile is set explicitly. See how to set and configure profiles in spring.Must Read :: What are profiles in Spring boot. How to get Active Profiles in an EnvironmentAll you need...

read more

SpringBoot : CORs Allow Custom Headers in Ajax calls

Ekansh Rastogi | 18 September 2015

Points To RememberAdd the comma separated Headers (standard and Custom headers) CORs Allow Custom Headers in Ajax calls $.ajax({ method : 'POST', url : 'url', headers: {'Custom-Header-1':'h1','Custom-Header-2':'h2'}, success: function(data){}, error : function(error){}}); @Componentpublic class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Custom-Header-1 , Custom-Header-2, X-Auth-Token"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {}} Add the above filter in your spring boot application. Add the comma separated headers at line 9 (highlighted)...

read more

SpringBoot : How to allow cross origin ajax calls to Spring application

Ekansh Rastogi | 15 September 2015

How to allow cross origin ajax calls to Spring application Add the following class to your Spring or Spring Boot application. After adding this class you will be able to make ajax calls to your application. package com.ekiras.filter;import org.springframework.stereotype.Component;import javax.servlet.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Componentpublic class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {}} Now you can hit the ajax calls like following $.ajax({ method:'GET', url:'http://someurl', success:function(data){...

read more

Gradle : Task to add selected files to jar

Ekansh Rastogi | 15 September 2015

Points To Remember You can create local variable in gradle with the type def, e.g def jarName = "ekiras" You can print variable with help of println e.g println "jar name is -> $jarName Gradle task declaration syntax is task taskName(type: taskType){} Task to add selected files to jarWe will be writing two tasks for this First task - compileFiles -> this will compile all the files in the project and then save them to the build/classes/ folder of the project Second Task - makeJar -> this will take all the compile files from the base folder and make a jar of these files in build/lib/ folder...

read more

Hibernate : How to get List of records of an Entity

Ekansh Rastogi | 09 September 2015

How to get List of records in Hibernate // List all records public List<User> list(){ return sessionFactory.getCurrentSession() .createCriteria(User.class).list(); // List all records } // List records based on MAX public List<User> list(Integer max){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max).list(); } // List records with MAX records and OFFSET public List<User> list(Integer max, Integer offset){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max) .setFirstResult(offset) .list(); } // List records with MAX records and OFFSET and ORDER by id field of User class public List<User> list(Integer max, Integer offset){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max) .setFirstResult(offset) .addOrder(Order.asc("id")) .list(); } this is body.

read more

Hibernate : How to use @Temporal annotation

Ekansh Rastogi | 04 September 2015

Points To Remember@Temporal annotation must be used with the persistent fields or properties of type java.util.Date  java.util.Calendar How to use @Temporal annotation@Temporal Annotation is defined as following @Target({ METHOD, FIELD })@Retention(RUNTIME)public @interface Temporal { /** * The type used in mapping <code>java.util.Date</code> or <code>java.util.Calendar</code>. */ TemporalType value();} So the TemporalType is an Enum and looks like following public enum TemporalType { DATE, TIME, TIMESTAMP} So @Temporal annotation can take three values DATE, TIME and TIMESTAMP. And it will create the following database ddl type. TemporalType Database DDL Type DATE date TIMESTAMP datetime TIME time If we the following class as...

read more

Hibernate : How to use @Column Annotation

Ekansh Rastogi | 03 September 2015

Points To Remember @Column annotation is used to define the column name, type, constraints. It should be used with the fields either above the getter or above field declaration. The @Column annotation can take the following configuration. Property Type Default Value Description name Optional "" The name of the column. Defaults to the property or field name unique Optional false Whether the column is a unique key. nullable Optional true Whether the database column is nullable. insertable Optional true Whether the column is included in SQL INSERT statements generated by the persistence provider. updatable Optional true Whether the column is included...

read more

Hibernate : How to use @Id annotation

Ekansh Rastogi | 02 September 2015

Points to remember There should be only one @Id annotation in a hibernate entity class. There should be at least one field specified as primary id. You can use different approaches for creating primary id using these Primary Key Generation Strategies. How to use @Id annotation in HibernateTaking the example in the previous example. @Id annotation tells the hibernate to @Id annotation tells the hibernate that this field will be the primary key of the table.@Id annotation class looks like the following @Target({METHOD, FIELD})@Retention(RUNTIME)public @interface Id {} If we do not add @Id annotation on any of the fields in Hibernate entity then you will...

read more

Hibernate : How to use @Entity annotation

Ekansh Rastogi | 02 September 2015

How to use @Entity annotation in HibernateSuppose we want to make a User domain with the following fields Id Name Age Address Gender Email Mobile We can create tell the hibernate to register this Domain class as a Hibernate Entity object by adding @Entity annotation at the class level. package com.ekiras.domian;import com.ekiras.enums.Gender;import javax.persistence.Entity;@Entitypublic class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private Integer age; private String address; private Gender gender; private String email; private Long mobile; // GETTERS and SETTERS} So what the above line means is that, hibernate treats the class User as a Hibernate Persistence Entity....

read more

How to run Spring boot Application

Ekansh Rastogi | 25 August 2015

How to run a Spring Boot Application using Maven/ Gradle If you are using Maven as a build tool you can the project as mvn spring:run If you are using Gradle as a build tool you can the project as gradle bootRun

read more

How to find all Permutations and Combinations of a String

Ekansh Rastogi | 20 August 2015

Algorithm UsedWe will be using the following algorithm to find all the permutations of a string Take the first letter as a prefix and find all the permutations of the remaining string. Each of the prefix will also be a permutation itself. If you want to find all the permutations of string with same length as the original string then skip the prefix's as the combination. public class Permute { static String codes = "eki"; static int count; public static void main(String args[]) { permute("", codes); System.out.println(">>>>>>>" + count); } public static void permute(String prefix, String str) { System.out.println(prefix); count++;...

read more

Spring Boot Maven Dependencies to create basic CRUD application

Ekansh Rastogi | 18 August 2015

Spring Boot Maven to create basic CRUD application.You need to add the following dependencies to the pom.xml to make the basic CRUD application spring-boot-starter-data-jpa spring-boot-starter-jdbc spring-boot-starter-web jstl mysql-connector-java spring-boot-starter-tomcat tomcat-embed-jasper So your pom.xml may look like the following pom.xml <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ekiras</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>springboot</name> <description>Basic Springboot CRUD application</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>...

read more

Spring Boot Gradle MVC sample CRUD project

Ekansh Rastogi | 17 August 2015

This is a sample Spring Boot Application that uses  JDBC Mysql JPA MVC Gradle Create Basic CRUD for Person Entity with JPA and Mysql Download from GitHub Project Structure  build.gradleView Maven Dependencies (pom.xml) here. buildscript { ext { springBootVersion = '1.2.5.RELEASE' } repositories { maven { url "http://repo.spring.io/libs-milestone" } mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE") }}apply plugin: 'java'apply plugin: 'eclipse-wtp'apply plugin: 'idea'apply plugin: 'spring-boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'war'war { baseName = 'springboot' version = '0.0.1-SNAPSHOT'}sourceCompatibility = 1.7targetCompatibility = 1.7repositories { mavenCentral() maven { url "http://repo.spring.io/libs-milestone" }}configurations { providedRuntime}dependencies { compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("javax.servlet:jstl:1.2") runtime("mysql:mysql-connector-java") compile("org.springframework.boot:spring-boot-starter-jdbc") compile ("org.springframework.boot:spring-boot-starter-web") providedRuntime("org.springframework.boot:spring-boot-starter-tomcat") providedRuntime 'org.apache.tomcat.embed:tomcat-embed-jasper'}eclipse...

read more

Get free Airtel 4G sim by tweeting #GetAirtel4G

Ekansh Rastogi | 10 August 2015

Wow! you can get an Airtel 4G Sim totally free. Here is how?If you are an Airtel user and you have the required 4G handset with you, you just have to tweet #GetAirtel4G to get a 4G sim delivered to your home for TOTALLY FREE.    Steps to get your Airtel 4g SIM Tweet with #GetAirtel4G on twitter,  Get the reply from Official Airtel India handle @AirtelIndia to fill details Fill your details and address where you want your sim to be delivered. You are done. You will get your Airtel 4g Sim within hours to a day or two at max....

read more

Spring Boot Making CLI Application using Java

Ekansh Rastogi | 07 August 2015

Points To RememberYou can make the cli application without writing any configurations or xml's that you needed to do in traditional spring framework.Spring boot automatically adds the boiler plate code to the application that may look like this // import org.springframework.web.bind.annotation.Controller// other imports ...// @Grab("org.springframework.boot:spring-boot-web-starter:0.5.0")// @EnableAutoConfiguration@RestController@RequestMapping("/")class Hello { @RequestMapping(value="/hello") public String index(){ return "<h1>Hello World !! Today's date is " + new Date() + "</h1>"; }// public static void main(String[] args) {// SpringApplication.run(Example.class, args);// }} The following code is a self sufficient code to run in a servlet container. Hello.java import java.util.Date;@RestController@RequestMapping(value="/")class Hello{ @RequestMapping(value="/hello") public String index(){ return "<h1>Hello World...

read more

Spring Boot Making CLI Application using Groovy

Ekansh Rastogi | 07 August 2015

Points To RememberYou can make the cli application without writing any configurations or xml's that you needed to do in traditional spring framework.Spring boot automatically adds the boiler plate code to the application that may look like this // import org.springframework.web.bind.annotation.Controller// other imports ...// @Grab("org.springframework.boot:spring-boot-web-starter:0.5.0")// @EnableAutoConfiguration@RestController@RequestMapping("/")class Hello { @RequestMapping(value="/hello") public String index(){ return "<h1>Hello World !! Today's date is " + new Date() + "</h1>"; }// public static void main(String[] args) {// SpringApplication.run(Example.class, args);// }} The following code is a self sufficient code to run in a servlet container. Hello.groovy import java.util.Date;@RestController@RequestMapping(value="/")class Hello{ @RequestMapping(value="/hello") public String index(){ return "<h1>Hello World...

read more

Hibernate : @Table Annotation

Ekansh Rastogi | 06 August 2015

Points To Remember@Table Annotation is an annotation that is used to give the table level information. It can be uesd to specify the following Table name (optional,default ="")- to set the name of the table in database Table schema (optional,default ="")- to set the schema of the table in database Table catalog (optional,default ="") -to set the catalog of the table Table Constraints (optional,default = []) to set the constraints on the table. It belongs to the package javax.persistence.Table @Table(name="person",schema="ekiras",uniqueConstraints = {@UniqueConstraint(columnNames = {"id","email"})})public class Person { private Long id; private String name; private String email; // code} If you do not define the name property of...

read more

Exception in thread java.util.ConcurrentModificationException

Ekansh Rastogi | 03 August 2015

Points To Remember ConcurrentModificationException occurs when the you you try to modify the collection you are using or iterating. It can be prevented if you create a new object of that collection and do operations on that and then assign it back to the original object. java.util.ConcurrentModificationExceptionIn the following code we will be iterating on the list and trying to remove the null objects from the list. import java.util.*;public class Demo { public static void main(String args[]) { // create an array of string objs String init[] = { "One", "Two", null, null, "One", "Two", null, "Three", "Four", "Two", null };...

read more

How to remove all nulls from a Collection in Java

Ekansh Rastogi | 03 August 2015

How to remove nulls from a List in Java One way is to iterate the objects from the Collection ( like List, Array, Map etc) and remove null objects. Remove a particular object from List, Array or Map by searching the object and then removing it. Using the Collections.singleton(T o) method from the java.util package and then it will remove all the objects from the collection. Removing Objects in Traditional Way.We will be taking the following list of String for all our Examples String init[] = { "One", "Two", "One", "Three", "One", "Two", "Three","Four", "Two" }; Here we will remove the objects...

read more

Spring Boot Reading Properties File

Ekansh Rastogi | 29 July 2015

Points To Remember You can use  @PropertySource annotation to load the properties file from classpath. Keep your properties file under the resources folder. Use @Value annotation to load the values from property file with "${key}" as key. Load Properties file from classpath in Spring boot.Your properties file look like following. spring.data1=sampleData1spring.data2=sampleData2spring.data3=sampleData3 You can load the properties using the following two approaches In this approach you can specify a prefix with which your config starts in the properties file @Component@PropertySource("sample.properties")@ConfigurationProperties(prefix = "spring")public class SampleConfig { private String data1; private String data2; private String data3; // GETTERS and SETTERS} In this approach you need to specify...

read more

Angularjs RouteParams with ngRoute

Ekansh Rastogi | 28 July 2015

Points To Remember You should pass the params separated by "/". You can pass the params to the controller and pass them to the templates or apply logic. You need to add $routeParams input to your controller function to get these params. How to pass Params from one state to another in AngularJs using ngRoute.You need to add the route params along with the url e.g you can send the params as follows #url/param1/param2 This is how you can update your $routeProvider to use these route params. Finally, access the params in the controller and pass them to the template....

read more

Get Current Environment in Grails

Ekansh Rastogi | 28 July 2015

How to create custom Environments in GRAILS.This is how you can specify the environments in your grails application. Below we have made five environments. production uat (custom) qa (custom) development test environments { production { grails.serverURL = "http://www.ekiras.com/" } uat { grails.serverURL = "http://uat.ekiras.com:8080/" } qa { grails.serverURL = "http://qa.ekiras.com:8080/" } development { grails.serverURL = "http://localhost:8080/${appName}" } test { grails.serverURL = "http://localhost:8080/${appName}" }} There are Five predefined environments in grails. APPLICATION CUSTOM DEVELOPMENT PRODUCTION TEST How to get Execute a particular Environment in GRAILS To run a particular environment in grails you can do the following grails -Denv=qa -Dserver.port=8080 run-app...

read more

Spring MVC handle Exceptions in Controller using @ExceptionHandler

Ekansh Rastogi | 21 July 2015

Points To Remember You can handle all types of runtime exceptions and custom exceptions using @ExceptionHandler annotation.  You just need to define the class to the annotation to handle exceptions of that class. Spring MVC handle Exceptions in ControllerHere we have a simple Spring MVC application with the following. HomeController wih three actions  throw1 - throws Custom exception throw2 - throws Custom exception throw3 - throws Runtime exception Home Controller package com.ekiras.controller;import java.text.DateFormat;import java.util.Date;import java.util.Locale;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.ekiras.exception.MyException;import com.ekiras.exception.MyGlobalException;@Controllerpublic class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(value = "/", method = RequestMethod.GET) public...

read more

Send JSON object as data in Ajax POST/ GET call

Ekansh Rastogi | 02 July 2015

Send JSON object as data in Ajax call.Suppose you have  a JSON object associated with a variable say json  in our case, you can send this json value as data in the ajax call as follows. var json = [{'id':1,'name':'user1'},{'id':2,'name':'user2'},{'id':3,'name':'user3'},{'id':4,'name':'user4'}]function demo(url){ $.ajax({ method : 'POST', url : url, dataType: 'json', data : { objects :JSON.stringify(json)}, success : function(data){ console.log(data); }, error : function(error){ alert('OOps Something went wrong, please contact admin'); } });} JSON.stringify() method will parse the json object and convert it to a string format that can be sent as data in the Ajax call.you can also send other data...

read more

Why ASUS ZENPHONE 2 should be in everyone's pocket

Ekansh Rastogi | 30 June 2015

When I was looking for a cheap and best smartphone, then Asus Zenphone 2 is the one that comes in choice which comes in half the price of all top-tier smart phones and luckily nowhere near half the quality.  There are many features that makes this phone desirable like: 1) Design: The luxurious ultra thin lollipop based Asus phone featured a hard plastic chassis available in multiple colors that make the phone even more desirable for me. the 72 % screen to body ratio and 1920 x 1080 full HD IPS display maximises the viewing experience. The removable back-panel gives access to...

read more

How to delete a Folder in Java

Ekansh Rastogi | 02 June 2015

Points To RememberBefore deleting the file you need to check if you have permission to delete file using method canWrite() file specified exists exists() Deleting the file in Java Test.java import java.io.*;class Test{ public static void main(String args[]){ File file = new File("/home/ekansh/test"); if(file.isDirectory()){ if(file.delete()) System.out.println("Success ! Folder deleted."); else System.out.println("Failure ! Folder not deleted."); }else System.out.println("FOLDER DOES NOT EXIST"); }} Success ! Folder deleted.

read more

How to create Nested folders in Java

Ekansh Rastogi | 02 June 2015

Points To RememberYou need to check the following things fro creating the nested folders If it is a directory by method isDirectory() If it exists by method exists() You might need to check if you have write permissions to create folder by method canWrite() How to create Nested Folders/Directories in JavaThis is how yo can create the nested folders in java. CreateNestedFolders.java import java.io.*;class CreateNestedFolders{ public static void main(String args[]){ File file = new File("/home/ekansh/test/1/2/3/abc"); if(!file.canWrite()){ // check if user have write permissions if(!(file.exists() && file.isDirectory())){ if(file.mkdirs()) System.out.println("Success ! Folders created."); else System.out.println("Failure ! Folders not created."); } }else{ System.out.println("PERMISSION DENIED");...

read more

Getting started with Nginx

Ekansh Rastogi | 31 May 2015

Points To Remember Nginx is pronounced as Engine-x It is open source It is a High performance HTTP server and Reverse proxy It does not rely on thread to handle requests. Thus it can serve thousands of concurrent requests. It works on scalable event driven (asynchronous) architecture.  Getting started with NGINX Install nginx sudo apt-get install nginx Check the status of the server sudo service nginx status Start the nginx server sudo service nginx start Go to the browser and enter the url http://localhost you will see the following screen. Our nginx server is up and running. Viewing the NGINX configuration files....

read more

How to create/ schedule a Job or Thread to run at fixed intervals

Ekansh Rastogi | 21 May 2015

Points To Remember TimerTask is a class that can run a Thread repeatedly after a specific period. You can either implement your own class also by implementing Runnable Interface. Then you may need to put your thread to sleep and then resume the thread after a desired interval. The TimerTask will do this more efficiently for you then implementing your own code. How to schedule a Thread to run after fixed intervalWe will be using TimerTask to schedule the Thread after every 1 sec. TimerTask class in Java implements Runnable interface and has the following methods. cancel - to cancel the...

read more

How to use AngularJs Expressions

Ekansh Rastogi | 19 May 2015

Points To Remember You can evaluate angular expressions by the following ways using interpolation {{ }} using ng-bind Examples of AngularJs ExpressionsFollowing are the ways you can use the angular expressions. Mathematical calculations  String operations Json operation Array operations You may want to see ng-init. <!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body ng-app="" ng-init="firstName='Ekansh';lastName='Rastogi';json=[{'name':'user1','age':'18'},{'name':'user2','age':'24'}];array=[0,1,2,3,8]"> <div ng-bind="firstName + ' ' + lastName"></div><hr/> String operation ->{{"Hello" +" " + "World!" }}<hr/> Math operation -> {{2 * 5 }}<hr/> String &amp; Math operation ->{{"10 * 15 * 84 = " + (10 * 15 * 84)}}<hr/> Json Operation ->{{'name...

read more

Introduction to AngularJS

Ekansh Rastogi | 19 May 2015

Setting up AngularJS.All you need to do is Download the AngularJs script from https://angularjs.org/. You can use the AngularJs cdn   http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js Add the Angular Js ng-app="" tag to initialize the angukar application. Add the angularjs script to the Html page and you are good to go <!DOCTYPE html><html>  <head>    <link rel="stylesheet" href="style.css">    <script src="script.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>  </head>  <body ng-app="">    <h1>{{"Hello" +" " + "World!" }}</h1>  </body></html> The above code will give you the following output. Loading plunk...

read more

Best HTC Mobiles under INR 15000

Ekansh Rastogi | 06 May 2015

Lets have a look at the top HTC mobile phones under Rs 15000. HTC Desire 816G Plus  This is one of the most wanna be mobile that the company has produced and is available in the range 15000 INR. Lets see what makes this phone a great choice to buy. Octacore  1.7 Ghz processor that is fast enough to run all your games and applications simultaneously. 5.5 inch screen multi touch screen High resolution 720 x 1280 that will give you a great experience of viewing your videos and movies. 1 GB RAM and 16 GB internal memory. So store all your...

read more

Different ways to bind Elements to Model in AngularJs

Ekansh Rastogi | 03 May 2015

Different ways to Bind Elements to Model/ DirectivesYou can bind the Angular Elements to the Model in the following ways. <span ng-bind="name"></span> <br/> <span ng:bind="name"></span> <br/> <span ng_bind="name"></span> <br/> <span data-ng-bind="name"></span> <br/> <span x-ng-bind="name"></span> <br/> Remove the x- or data- from the start of the element attributes. e.g data-ng-bind and x-ng-bind can be written as ng-bind Convert the delimiters like :, -, _ to camelCase. Since the Html is case insensitive you can not use camelCase and you can use delimiters like :, -, _ to write your directives/angular . So the above ways areFollowing example in the Plunk shows the various...

read more

Best Acer Laptops

Ekansh Rastogi | 01 May 2015

Acer Laptops When we talk about the Laptops for beginners or entry level laptops some of the best brands that offer these are ACER, HP, Lenovo, Samsung. Laptops are meant to give you a multifunctional computer. They have built-in Wi-Fi1 to give you the freedom to work and play wirelessly. Depending on the model, larger screen sizes, bigger hard drives and built-in DVD drives increase laptops' weight, which makes them less portable than netbooks but an excellent choice for your everyday computing needs.   And thankfully if you know where to look, it's possible to get a sleek and impressive...

read more

Test : Java_19

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these packages contains abstract keyword? java.util java.io java.system java.lang D A subclass of an abstract class can also be abstract if It is instantiated The static class is declared in the parent class It does not define all the abstract...

read more

Test : Java_18

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these method of Thread class is used to find out the priority given to a thread? get() ThreadPriority() getPriority() getThreadPriority() C In the following example, which class must be abstract: abstract class X implements Y { // implements all but...

read more

Test : Java_16

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class box { int width; int height; int length; int volume; box() { width = 5; height = 5; length = 6; } void volume() { volume = width*height*length; } } class constructor_output { public...

read more

Test : Java_17

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class exception_handling { public static void main(String args[]) { try { int i, sum; sum = 10; for (i = -1; i sum = (sum / i); } catch(ArithmeticException e) { System.out.print("0"); } System.out.print(sum); }...

read more

Test : Java_15

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these method is used to avoid polling in Java? wait() notify() notifyAll() All of the mentioned D What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a, b; b =...

read more

Test : Java_14

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these interface is implemented by Thread class? Runnable Connections Set MapConnections A What is the output of this program? class area { int width; int length; int area; void area(int width, int length) { this.width = width; this.length = length;...

read more

Test : Java_13

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of the folowing stements are incorrect? Default constructor is called at the time of declaration of the object if a constructor has not been defined. Constructor can be parameterized. finalize() method is called when a object goes out of scope and...

read more

Test : Java_12

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of the following statements are incorrect? public members of class can be accessed by any code in the program. private members of class can only be accessed by other members of the class. protected members of a class can be inherited...

read more

Test : Java 11

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which keyword is used by method to refer to the object that invoked it? import catch abstract this D The methods wait() and notify() are defined in java.lang.String java.lang.Runnable java.lang.Thread java.lang.Object D Which of these keywords is used to refer to member...

read more

Test : Java_10

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of the following statements are false in the concept of abstract classes: Can b instantiated It may or may not include abstract methods It can be subclassed None of the above A Which of these is static variable defined in Collections?...

read more

Test : Java_9

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class access{ public int x; private int y; void cal(int a, int b){ x = a + 1; y = b; } void print() { system.out.println(" " + y); } } class access_specifier { public...

read more

Test : Java_8

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class newthread extends Thread { Thread t; newthread() { t1 = new Thread(this,"Thread_1"); t2 = new Thread(this,"Thread_2"); t1.start(); t2.start(); } public void run() { t2.setPriority(Thread.MAX_PRIORITY); System.out.print(t1.equals(t2)); } } class multithreaded_programing { public static void main(String...

read more

Test : Java_7

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What will be the output of the program? public class Test { public static void main(String[] args) { int x = 0; assert (x > 0) ? "assertion failed" : "assertion passed" ; System.out.println("finished"); } } finished Compiliation fails. An AssertionError is...

read more

Test : Java_6

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Given the class definitions System.out.print(b.display() + " ");System.out.print(d.display() + " ");System.out.print(bd.display() + " ");System.out.println(); will display: Base Derived Derived Base Base Derived Base Derived Base Derived Derived Derived A Which of the following keywords are used to control access to a class...

read more

Test : Java_5

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class box { int width; int height; int length; } class mainclass { public static void main(String args[]) { box obj = new box(); obj.widht = 10; obj.height = 2; obj.length = 10; int y...

read more

Test : Java_4

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Class A      {       public static void main(String a1[])       {         String s1= ?Hello?;         StringBuffer s2= new StringBuffer(?Hello?);         s1 = s1 + ?World?;         s2.append(?World?);       }      }   In the above code how many String and StringBuffer objects are created? 1 & 1 2 & 1 2 & 2 1 & 2 B Difference between String and StringBuffer object is...

read more

Test : Java_3

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these lines will give an error line 1 :int a=1; line 2 :char c=25; line 3 :double d=2.9; line 1 line 2 line 3 none of these D no error since character can take integer value Following code prints ?...

read more

Test : Java_2

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the output of this program? class box { int width; int height; int length; } class mainclass { public static void main(String args[]) { box obj1 = new box(); box obj2 = new box(); obj1.height = 1; obj1.length = 2;...

read more

Test : Java_1

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What was the original name of Java Oak Pok James Coffee A Java was initially named as Oak Who is know as the father of Java Ken Arnold David Holmes James Gosling Peter Dibble C James Arthur Gosling, OC (born May 19,...

read more

Test : Java_20

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of the following is incorrect statement about packages? Interfaces specifies what class must do but not how it does. Interfaces are specified public if they are to be accessed by any code in the program. All variables in interface are implicitly...

read more

Test : Java_21

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which keyword can be used to prevent a class from being subclassed init equals final clone C What is the output of this program? import java.util.*; class Array { public static void main(String args[]) { int array[] = new int [5]; for...

read more

Test : Java_22

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these keywords is used to manually throw an exception? catch finally throw try C What is the output of this program? class access{ public int x; private int y; void cal(int a, int b){ x = a + 1; y...

read more

Test : Java_23

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of these lines of code will give better performance? 1. a | 4 + c >> b & 7; 2. (a | ((( 4 * c ) >> b ) & 7 )) 1 will give better performance as it has...

read more

Test : Java_24

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds What is the order of precedence (highest to lowest) of following operators? 1. & 2. ^ 3. ?: 1 -> 2 -> 3 2 -> 1 -> 3 3 -> 2 -> 1 2 -> 3 -> 1 A What is the...

read more

Test : Java_25

Ekansh Rastogi | 22 April 2015

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes :seconds Which of the following methods belong to the String class? 1. length() 2. compareTo() 3. equals() 4. substring() Length(), & compareTo() Equals() All of these None of these C What is the length of the application box made by this program? import...

read more

How to restore dump of single database from Dump in MYSQL

Ekansh Rastogi | 14 April 2015

Suppose you have a dump of more than one databases in a single dump file, then you can restore one or all the databases. mysql -u root -p --one-database DBNAME < DUMPFILE.SQL You should take care of a few things when you take the dump. Create a database by that name in mysql if it does not exist. Switch to the database you want to restore, this will help restore the database properly. You need to be outside mysql environment to run this command. For more specific restoration of databases from a dump file you can try mydumpsplitter. 

read more

How to execute a SQL query in grails

Ekansh Rastogi | 07 April 2015

Points To Remember You need to inject the SessionFactory object in the service or the controller, where you want to use it. Get the current session from the session factory and execute the query in this session using sessionFactory.getCurrentSession(). You can also execute the query in a new session by using sessionFactory.openSession(). Executing SQL query in grails Person.groovy package com.ekiras.grails;class Person{ String username String email String password static mapping = { } static constraints = { username nullable: true password nullable: false, blank: false email nullable: false, blank: false }} PersonService.groovy package com.ekiras.grails;import org.hibernate.SessionFactory;import grails.transaction.Transactionalimport com.ekiras.grails.Person;@Transactionalclass PersonService{ SessionFactory sessionFactory; def listPersons(){ String query =...

read more

How to escape Html in Angular js

Ekansh Rastogi | 25 March 2015

Points To Remember You need to use SCE to render html as it is on the page. There are two ways to use sce either you use it in the angular controller to prevent escape html or you can create a filter to do this where ever you need it. Using it with a filter is a much better way to do so, if you need to do it at multiple places. Following Plunker example shows how you can prevent escaping of Html Loading plunk... Prevent Escape Html from angularjs Controllers <html><head><script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script></head><body ng-app="demo"><div ng-controller="home"> Original Text : {{text}}<br/><br /><br /> EscapedText...

read more

Hibernate : fetch results using Orderby in Criteria Query

Ekansh Rastogi | 23 March 2015

Syntax to use OrderBy in Hibernate Criteria QueryThe order can be specified using addOrder on a Criteria Object criteria.addOrder(Order.asc("propertyName"))criteria.addOrder(Order.desc("propertyName")) Order results according to an order in Hibernate Suppose we have a class Category.java package com.ekiras.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="category")public class Category { public Category(){} public Category(Long id){ this.id = id; } public Category(Long id, String name){ this.id = id; this.name = name; } @Id @Column(nullable=false, name="id") @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable=false, name="name") private String name; // Getters and Setters } So if we need to order the results of this class according to a given order we can...

read more

Hibernate Criteria Query to find List of Domain class.

Ekansh Rastogi | 20 March 2015

Syntax to get List of domain Object list can be used on the Criteria object as shown below. criteria.list() How to get a List of a Domain class using Hibernate's Criteria Query.If we have a domain class Category as shown below. Catgeory.class package com.ekiras.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="category")public class Category { public Category(){} public Category(Long id){ this.id = id; } public Category(Long id, String name){ this.id = id; this.name = name; } @Id @Column(nullable=false, name="id") @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable=false, name="name") private String name; // Getters and Setters } We can get the list of all the categories...

read more

How to Upload and Read a Csv in Grails

Ekansh Rastogi | 12 March 2015

Points To Remember Add the plugin Csv Grails plugin . You can do it manually without the plugin if the you have a uniform structure of the csv file. Upload a Csv You need to add the dependency for the csv file reader in BUildConfig.groovy as shown below BuildConfig.groovy compile ":csv:0.3.1" And you have a csv file like the following. upload.jsp <g:uploadForm action="upload"> <input type="file" name="file"> <g:submitButton name="file" value="Upload"/></g:uploadForm> When the above form is submitted then the request will be handled by the controller action as shown below UploadController.groovy def upload() { MultipartFile file = request.getFile( 'file' ) file.inputStream.eachCsvLine { row...

read more

Pagination in Spring Hibernate Mvc application

Ekansh Rastogi | 08 March 2015

Points To Remember Create a Pagination Taglib using this example. Add Bootstrap css and js in the jsp you want to do pagination and include the taglib in the jsp. Pagination in Spring Hibernate Application using Bootstrap Create a Domain Person. Create a Service PersonService Create a Dao PersonDao. Create a Controller PersonController. Create a Taglib PaginationTaglib. Person.java package com.ekiras.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="person")public class Person { public Person(){}; public Person(String name,Integer age){ this.name = name; this.age = age; } @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="name") private String name; @Column(name="age") private Integer age; // GETTERS and SETTERS...

read more

How to get results from a fixed position in Hibernate Criteria Query

Ekansh Rastogi | 04 March 2015

Points To Remember Offset may be required to do pagination or get the results after a particular result from the database. Using offset you can define the first result to be included in the result set from the database.  You can use setFirstResult on the CriteriaQuery to set the first result that you want. Using offset to get the results SampleDAO.java @SuppressWarnings("unchecked")public List<Person> getCategories(Integer offset){ return getSession() .createCriteria(Person.class) .setFirstResult(offset!=null?offset:0) .setMaxResults(10) .list(); } This is how you can set the first result you want to fetch from the database. In this example we have set the first result and the maximum number of...

read more

How to create Pagination Taglib in Java, Spring

Ekansh Rastogi | 03 March 2015

Points To RememberBootstrap is one of the major UI componnet used worldwide, So you may want to implemnt pagination using bootstrap in java , j2ee or spring application. So all you need to do is Create a Class that will behave like a taglib. Create a Tld file that will map the tablib class with the jsp's. Use the taglib on jsp using the tld file. Create Pagination Taglib for Jsp with Bootstrap.Following is an example of the a custom taglib built for Bootstrap. This taglib takes in uri -> action to be hit when clicked. offset -> the offset...

read more

How to do Versioning Controllers in Grails Example

Ekansh Rastogi | 21 February 2015

Points To Remember Versioning  of Controllers can be done in grails with the help of UrlMappings and Namespaces. We can have two or more controllers with the same name as long as they are in different packages and different namespaces. You can map these controllers in UrlMappings like /$namespace/$controller/$action Versioning of Grails Controllers The easiest way of versioning the grails controllers is to do it with the help of namespaces. So in this example we will try to do versioning of the controllers on the basis of namespaces. Test.groovy package com.ekiras.versioning.v1class TestController { static namespace = "v1" def index() { render "Hi, This is...

read more

What is NoClassDefFoundException in Java

Ekansh Rastogi | 15 February 2015

Points To Remember NoClassDefFoundException is an Exception that occurs when a class is not found at runtime but was available at compile time. This exception is different from ClassNotFoundException. See the differences here. Example : Creating a NoClassDefFoundExceptionSuppose we have two classes A and Test. We just make an object of class A in Test class. A.java class A{ public A(){ System.out.println("This is class A"); }} Test.java class Test{ public static void main(String args[]){ System.out.println("This is Test Class"); A obj = new A(); }} The output of the program will be as follows This is Test ClassThis is class A...

read more

How to create a Custom Exception in Java

Ekansh Rastogi | 15 February 2015

Points To Remember All the custom Exceptions must implement the Exception class or any of its subclass. There are four types of Constructors that you can use while defining your Custom Exception. Ex 1 : Basic Custom ExceptionIn this case we will just created a Custom Exception where we define a Custom Exception and throw it with a message. This message is visible in the stacktrace. class CustomException extends Exception { public CustomException(String message) { super(message); }}public class Test { public static void main(String args[]) { try { throw new CustomException("Throwing Custom Exception"); } catch (CustomException e) { e.printStackTrace(); }...

read more

How to create Nested Custom Exceptions in Java

Ekansh Rastogi | 15 February 2015

Points To Remember

read more

Youtube Data Api v3 : Authenticate User

Ekansh Rastogi | 10 February 2015

Points To Remember You must have a project created in Developers console to use Youtube data api and other api's. You should save the youtube refresh token in a database or file where you can save it for a long time and use it. Youtube refresh token is generated only once, so if you want to regenerate it go to google accounts page and revoke access to your project and then re authenticate. To revoke access, go to Connected Apps and Sites in the above mentioned url and click on your project and then click revoke access to revoke access to the...

read more

How to use Enums in Hibernate Persistence

Ekansh Rastogi | 08 February 2015

Points To Remember Enums are special java classes that are used to declare constants and methods. Enums have all the variables declared as public static final. Enums variables can be compared using == operator. End of a enum can be declared by a semi colon, but this is optional. There are two ways to use Enums  ORDINAL (saves the enum values in integer format starting from 0.) STRING (saves the enum value in String, takes the value of the field itself. ) Use Enums in HibernateIn this example we will be using Enums to save a value in database using hibernate.Suppose...

read more

Maven Spring MVC Hibernate Sitemesh Project Setup

Ekansh Rastogi | 07 February 2015

Points To RememberYou need to add the following dependencies to pom.xml spring-core spring-context spring-web spring-webmvc spring-tx spring-orm mysql-connector-java jstl hibernate  Create  Maven Spring Hibernate Sitemesh Annotation based Hello World project pom.xml pom.xml should contain the following dependencies <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples.service.service</groupId> <artifactId>ekiras</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <java.version>1.7</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring.version>3.2.8.RELEASE</spring.version> <junit.version>4.11</junit.version> <sitemesh.version>3.0.0</sitemesh.version> <hibernate.version>4.2.1.Final</hibernate.version> <logback.version>1.0.13</logback.version> <slf4j.version>1.7.5</slf4j.version> <jsp.version>2.2</jsp.version> <jstl.version>1.2</jstl.version> <servlet.version>2.5</servlet.version> </properties> <dependencies> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId>...

read more

Hibernate Many to Many relational Mapping

Ekansh Rastogi | 07 February 2015

Points To RememberSuppose we have two domains/ entities User and Role and we want to create a many to many relationship between them them, then we can do it like following in hibernate. Many to Many relationship between two Entities. User.java Create a User class as following package com.ekiras.domain;import java.util.ArrayList;import java.util.Collection;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.ManyToMany;import javax.persistence.Table;@Entity@Table(name = "user")public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="email") private String email; @Column(name="password") private String password; @Column(name="enabled") private boolean enabled; @ManyToMany(cascade=CascadeType.ALL) private Collection<Role> roles = new ArrayList<Role>(); // GETTERS and SETTERS Role.java Create the Role class as follows package com.ekiras.domain;import java.util.ArrayList;import java.util.Collection;import...

read more

How to create a database dump in Mysql

Ekansh Rastogi | 06 February 2015

Points To Remember You can take dump of Mysql using mysqldump in windows, linux or ubuntu operating systems. You should reach to the location of mysql/bin in a windows platform to use mysqldump, you can use from any location in ubuntu and linux. Taking dump of whole databaseWhen you want to take the dump of the whole file, you can simply do it with the following command mysqldump -u db_username -p database_name > path/dump.sql Here the database_name is your database name and path is absolute path where you want to create dump. Taking dump of a tableWhen you want to take the...

read more

Many To Many Mapping in Hibernate Annotation

Ekansh Rastogi | 05 February 2015

Points To RememberThere are two ways to create hibernate many to many relational mappings in Hibernate. We will discuss both of them in detail here. First one is to use default hibernate mapping to create and manage these relations. By creating a new domain that will manage these relations for us. Suppose we want to have a simple User and Role mapping where a user can have multiple roles and a role can be assigned to multiple users. Then we can create and manage these relations in the following ways. Strategy 1 : Default Hibernate MappingsYou can use this strategy...

read more

Custom 404 Error Page in Spring MVC

Ekansh Rastogi | 04 February 2015

Points To Remember You need to first add the errors in the web.xml and redirect them to a url. Then you need to map these url to controller to handle them and take necessary actions.  You can either handle exceptions in your controllers as explained in the link. Custom Error PagesHere in this example we are going to create custom error pages in our spring mvc application. So will first of all configure the error codes in web.xml like the following. web.xml <error-page> <error-code>400</error-code> <location>/400</location> </error-page> <error-page> <error-code>404</error-code> <location>/404</location> </error-page> <error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page> Now when we have configured the error...

read more

How to create Custom 404 page in Web Application

Ekansh Rastogi | 04 February 2015

Points To RememberYou can define your custom error pages in web.xml. This is the best way to define custom 404 and other error pages. Configure Custom error pagesMany times we want to create custom error pages in our web applications like for a 404 error, resource not found, 500 internal server error and other errors that we see commonly. So we may want to redirect such errors to a better looking custom error page.If you want to redirect to custom error pages in a web application you can add these custom error pages in web.xml like following. web.xml <error-page> <error-code>400</error-code> <location>/error/400.html</location>...

read more

How to create a Composite Key in Hibernate

Ekansh Rastogi | 04 February 2015

Points To Remember You need to create an Embedded Object to create a composite key in Hibernate. You can create use an Embeddable Object as an EmbeddedId in class to make it a composite key. Create a Composite Key in HibernateSuppose we have three classes User, Role and UserRole. In class UserRole we want to have a composite id that will include userId and roleId. Then we will first create an embedded object and then using this we will create a composite key.Let us first create an Embeddable object and User.java package com.ekiras.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name =...

read more

How to convert the Base of a Decimal Number in Java

Ekansh Rastogi | 30 January 2015

Points To RememberYou can convert the number from decimal to any base by dividing the number by the base till the number is either 0 or less than the base it self and counting the remainders in a reverse order. Program : Convert the base of a Decimal Number import java.util.Scanner;class ConvertBase{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the Original NUmber"); int originalNumber = sc.nextInt(); System.out.println("Enter the base for conversion"); int base = sc.nextInt(); String convertedNumber = new ConvertBase().convert(originalNumber,base); System.out.println("Original Number = "+originalNumber); System.out.println("Converted NUmber = "+convertedNumber); } public String convert(int original, int base){ String...

read more

Spring Security : Custom UserDetailsService and Custom UserDetails

Ekansh Rastogi | 27 January 2015

Points To RememberYou need to change the UserDetailsService, User Object of the spring security to achieve this. Add Custom User Details to Spring Security Authentication ObjectFirst of all we nee to create a new User Object that will override the User class of the spring security in package org.springframework.security.core.userdetails.User After this, you need to tell  UserDetailsService to use this object as the principal for the authentication token. For this you will have to override the UserDetailsService of the spring security.You can have the custom User object like. Custom User Class -> MyUser.groovy package com.ekirasimport org.springframework.security.core.GrantedAuthority/** * Created by ekansh on 24/1/15. */class...

read more

Allegations and Mixtures

Ekansh Rastogi | 26 January 2015

Concepts Examples How To Solve Allegations Suppose the average weight of a group of objects O1 is A1 and average weight of group of objects O2 is A2 and A1 2, then we can write the data in the manner as shown in the figure. (Aw−A2) : (Aw−A1) gives the ratio of O1 : O2. Allegations does not give the actual volume to be mixed but only the ratio in which volumes are to be mixed. Question 1 A shopkeeper sells two types of rice A and B. If he sold 30% of type A rice at a profit of...

read more

Weighted Averages

Ekansh Rastogi | 26 January 2015

Concepts Examples When we have to calculate the average of some groups of different things, having different number of elements is being calculated, then it is called the weighted average. If the number of elements in n different groups be N1,N2,N3 .. Nn and their respective averages be A1,A2,A3...An , then Weighted average = $\frac{\mathbb{N}_1\cdot A_1+\mathbb{N}_2\cdot A_2+\mathbb{N}_3\cdot A_3...\mathbb{N}_n\cdot A_n}{\mathbb{N}_1+\mathbb{N}_2+\mathbb{N}_3...\mathbb{N}_n}$N1·A1+N2·A2+N3·A3...Nn·AnN1+N2+N3...Nn  Question 1 Average cost of buying 5 quality A crackers is 60 and cost of buying 10 quality B crackers is 80. WHhat will be average cost of buying all the crackers. 71.33 72.33 73.33 74.33 C Total number of employees...

read more

Spring Security : Create a Custom Authentication Filter

Ekansh Rastogi | 23 January 2015

Points To RememberYou may need to create an AuthenticatioFilter when you want to create a custom logic for handling the authentication filter. You may also want to create your own Authentication Provider, Entry Point, Authentication Token etc to customize the authentication process to a new level. Step 1 : Create a FilterLet us first create a class named MyAuthenticationFilter and then register it as a bean in resources.groovy. After we have created the class and registered the it as a bean, we can use this class as a filter for our custom spring security authentication.Class : MyAuthenticationFilter.groovy package com.ekirasimport org.springframework.context.ApplicationEventPublisherimport org.springframework.security.authentication.UsernamePasswordAuthenticationTokenimport...

read more

How to integrate Spring Security in Grails

Ekansh Rastogi | 19 January 2015

Points To RememberGo to the Grails Spring Security Plugin and add the dependency in the BuildConfig. Integrate Spring Security in GrailsAdd the latest grails spring security plugin in the build config of the project. This will add spring security jars and classes that will be used to configure spring security in the project. http://grails.org/plugin/spring-security-core Now run the following command from the terminal. grails s2-quickstart com.ekiras User Role Here the syntax of the above command isgrails s2-quickstart {package} {user domain} {authority domain}The above command will create three Domains in the project User, Role and UserRole. user domain will contain the user info,...

read more

What is ServletConfig in Java J2EE application

Ekansh Rastogi | 18 January 2015

Points To Remember Each Servlet has its own ServletConfig object. ServletConfig is defined in web.xml ServletConfig is a way of giving init parameters to a servlet during initialization.  ServletConfig is a predefined interface. ServeltConfig object is created by the container when a servlet is initialized and this object remains with the servlet throughout the life cycle of the servlet. Example : How to get ServletConfig Object in a Servlet. Lets take an example where we will add a few init params in the servlet config and get the config object from the servlet config object within the servlet. package com.ekiras;import...

read more

How to create a Custom Annotation in Java

Ekansh Rastogi | 15 January 2015

Points To Remember An annotation can be used as a replacement of interfaces. You can make both empty/marker annotations and annotations with methods. You can define the retention policy for the annotation and where the annotation can be used. Program : Create A Custom AnnotationThe following program creates a custom empty annotation. import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.annotation.ElementType;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface Table { public String name() default "table";} The above class can be used as a custom annotation with only one method name with a default value. This annotation can be applied only to the class i.e it is class level annotation and...

read more

How to find all the packages in a Project with a Prefix

Ekansh Rastogi | 14 January 2015

Points To Remember You to need to add the Reflections jar in the class path.  You will not be able to load the packages other than the current package using Package.getPackages() since current class loader will not be able to reach them. Program : Scan all packages with a PrefixYou can use Package.getPackages() approach to find all the packages that are in the current class loader. But you will not be able to get the packages that are not in the class path of the current class loader. So you need to include the jar "Reflections" to do this for you.All the dependency to the...

read more

How to apply Constraints in Command Objects

Ekansh Rastogi | 30 December 2014

Points To Remember You need to add the @Validateable annotation to the command class. Use importFrom in the constraints block with the domain name to import the constraints from domain. How to add Constraints to the Command Object.Lets us look at the example below. We have created a Domain by name User and a Command object by name UserCommand. We have created the constraints for email, password, first name and last name in User domain. We will import these constraints from domain to the command object and add some more constraints like verify password( if password and confirm password match).User.groovy package com.ekiras.domainclass User {...

read more

How to create SSL Certificate and add it to Keystore

Ekansh Rastogi | 25 December 2014

Points To Remember You need to have a SSL certificate o run an application/ server on https. You can create a SSL certificate using keytool. The keystore file for Java is available in Java/jre/lib/security/cacerts. Default password of the keystore is "changeit". Create a KeystoreYou can make a SSL certificate by following the steps below. Open a Command-line or Terminal window and make sure you're in your home directory. Execute the following command in the terminal keytool -genkey -alias tomcat -keyalg RSA -validity 365 NOTE, the validity parameter allows you to specify, in the number of days, how long the certificate...

read more

Struts : Setup Hello World Example

Ekansh Rastogi | 23 December 2014

Points To RememberDownload the struts required jars and add to the lib folder. Setup :  Struts Hello World Exampleweb.xml File <?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app> Struts Filter- This filter routes all incoming requests to struts.xml. struts.xml matches the actions and provides response accordingly. Welcome File List- this defines which file will be loaded on starting the application. We can have multiple welcome-file one followed by another. struts.xml <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"><struts><!-- ********************* START STRUTS FILE ********************************* --> <package name="HelloWorld" extends="struts-default">...

read more

How to make a Class Singleton

Ekansh Rastogi | 20 December 2014

Points To Remember To make a class Singleton the class must satisfy the following points No class should be able to make the object of this class. Only one object of this class must me there that is used by all the other classes. The class must have a private constructor so that no class should be able to make object of this class. Class should make a final object of the class itself and return it whenever asked for. Class should have a static method that returns the object of this class. Demo : Create a Singleton ClassClass :...

read more

How to flatten a Nested List in Java

Ekansh Rastogi | 18 December 2014

Points To Remember See How to create a Nested List from a String input. We use this class to create a nested list and then we try to flatten this list. Program : Flatten a Nested List Here we write a Java function that will accept a nested ist upto any level of nesting and flatten this list. import java.util.List;import java.util.LinkedList;import java.util.Scanner;class FlattenList{ public static void main(String args[]){ CreateList obj = new CreateList(); // Get the nested list sample List<Object> nestedList = obj.createNestedList(); System.out.println("-----------------------------------"); // Print the nested list System.out.println("Nested List = " + nestedList); // Print the sample nested list after flattening...

read more

How to create a Nested List upto any level of nesting

Ekansh Rastogi | 18 December 2014

Points To Remember The Correct Datatype for creating a Nested List will be List<Object>, because we have to store either a integer number or a list inside the list. We can not have a nested list like List<List<Integer>> because it will not be able to hold the integer values. It can only hold a list. The List we create can be nested to any level. Program : Create A nested list upto any levelHere we suppose that we get a String input of the list that we have to create. The following program accepts the list as a String and returns after converting...

read more

Test CAS Rest API from Java Code

Ekansh Rastogi | 16 December 2014

Points To Remember Make sure that your CAS Server is up and running. How to set up CAS Rest api with JDBC Authentication. You have created a database and have dummy data in it. Program : Test CAS Rest Api from a Java CodeYou can use the following piece of code to test the CAS Rest API. You need to follow the following points for Authentication a user on CAS You need to make a GET or POST call depending on your CAS server setup. If the Username and Password are correct then you will get a TGT (Ticket Granting...

read more

Finding number of factors of a number

Ekansh Rastogi | 14 December 2014

Concepts Examples If a number x divides another number y completely then x is a divisor of y. If x is a prime number then x is called the prime factor of number x. e.g 1,2,3,6 are the factors of 6 and 2,3 are the prime factors of 6. If any composite number N which can be expressed as N=$a^x\cdot b^y\cdot c^z...$ax·by·cz... , where a,b,c are the prime numbers and x,y,z are the powers of a,b,c respectively and so on. then the number of factors of N =(x+1)×(y+1)×(z+1)... e.g Find the number of factors of 24 24=22×31 ∴ number of...

read more

CAS Rest API Integration and Testing

Ekansh Rastogi | 10 December 2014

Points To Remember Please refer to blog How to set up CAS server with database. Now we are going to use the same authentication process through rest api and test it. Step 1: Adding dependency in pom.xmlFirst thing that we need to do here is to add the CAS Rest Api dependencies to pom.xml so that we can get the related jars in the class path. <dependency> <groupId>org.jasig.cas</groupId> <artifactId>cas-server-integration-restlet</artifactId> <version>${cas.version}</version> <type>jar</type> </dependency> Note : Here we are using CAS v4.0.0 Step 2: Mapping Servlet in web.xmlNow, we need to map the restlet servlet in the web.xml. For this copy the previously...

read more

How to setup & configure CAS with Database

Ekansh Rastogi | 08 December 2014

Points To Remember You can user MYSQL, Oracle or PostgreSQL connectors as the database. Make sure you have created a SSL certificate to run the CAS server on browser. Step 1: Adding Dependencies in pom.xmlAdd the following dependencies to the pom.xml that we created in this tutorial. These are the dependencies that are required to authenticate the user using the database. <dependency> <groupId>org.jasig.cas</groupId> <artifactId>cas-server-support-generic</artifactId> <version>${cas.version}</version> <type>jar</type> <scope>runtime</scope> </dependency> <dependency> <groupId>org.jasig.cas</groupId> <artifactId>cas-server-support-jdbc</artifactId> <version>${cas.version}</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.jasig.cas</groupId> <artifactId>cas-server-integration-restlet</artifactId> <version>${cas.version}</version> <type>jar</type> </dependency> So now the pom.xml will look like the following <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">...

read more

How to setup and configure CAS - Central Authentication Service

Ekansh Rastogi | 08 December 2014

Points To Remember CAS works on Maven WAR overlay technique. You need to create a SSL certificate to use CAS and run it over https to enable SSO(single sign on). How to create a SSL certificate and add it to keystore. You can use LDAP, Database and Active Directory techniques to authenticate the user. Requirements You need to have Java SDK v1.6 or greater. Servlet Containers like Tomcat , Websphere, JBoss etc.  Apache Maven v3.0 or greater. Authentication technique related dependencies. For the sake of simplicity let us assume that out application path is PROJECT = /home/ekiras/cas and our tomcat path...

read more

How to Deploy a war on Tomcat

Ekansh Rastogi | 03 December 2014

Points To Remember You should have a war file that can be deployed to the tomcat. You should have tomcat installed on your machine. Deploying a war file on Tomcat. We hope you have a installed the tomcat or have the tomcat bundle extracted on your system. In your case we just downloaded the tomcat zip and unzipped at home location. Step 1 : Change Tomcat User Name Password and Roles This is done so that you can login to the Tomcat Application Manager. All you need to do is find the file tomcat-user.xml at location path-to-tomcat/conf. Replace the following...

read more

Simple Averages

Ekansh Rastogi | 28 November 2014

Concepts Examples Properties of Averages Average of N things/quantities is equal to the sum of all the things/quantities divided by number of things/quantities. Average of N number of things/quantities always lies between the lowest and the highest quantities. If each quantity is increased by a certain value K, then the new average is increased by K. If each quantity is decreased by a certain value K, then the new average is decreased by K. If each quantity is multiplied by a certain value K, then the new average becomes K times the the original average. If each quantity is divided...

read more

LCM with Remainders

Ekansh Rastogi | 28 November 2014

Concepts Examples There are three types of questions that are based on LCM with remainders. They are as follows. When the remainders are same for all the divisors In this case the required number will be the LCM × N + remainder, where N is any natural number N=1, will give smallest such number N=2, will give second smallest such number and so on When the remainders are different for different divisors but the respective difference between the divisors and the remainders remain constant. In this case the required number will be LCM × N +difference of any (divisor -...

read more

Finding Last Two digits

Ekansh Rastogi | 28 November 2014

Concepts Examples There can be direct questions on finding last two digits of any power of a natural number and this is very important for eliminating options in questions. Following are the four simple cases with which we will be able to solve almost every problem. Rules for Finding Last Two Digits of square of a number In order to find the last two digits of square of any two digit number number, we can write it as difference or sum from 50 or 100, whichever is closer. In general the last two digits of a number (50±k)2 or (100-k)2...

read more

Finding Last Digit of a Number

Ekansh Rastogi | 28 November 2014

Concepts Examples To find the last digit i.e the unit digit you need to be aware of the cyclicity of the numbers and their powers 21=2 31=3 41=4 22=4 32=9 42=16 23=8 33=27 43=64 24=16 34=81 44=256 25=32 35=243 45=1024 26=64 36=729 46=4096 27=128 37=2187   28=256 38=6561   We can see that unit's digit of 21,25,29 is 2 and so on. Therefore, after every four powers of 2, the units digit of the number starts repeating.Thus we can say that cyclicity of unit's digit of higher powers of 2 is 4. Similarily unit digit of power of 4 starts...

read more

Finding Remainders

Ekansh Rastogi | 27 November 2014

Concepts Examples We can use the following rules to find the remainder when a number is divided by another. Rules for Finding Remainders Rule 1 : x is divided by y When we have to divide a number by another number, then we can write x in terms of y, i.e. (y×a)+b. This means that the remainder is b. e.g.When 66 is divided by 10, we can write 66 as 10×6+6, thus the remainder is 6. Rule 2 : x ± y is divided by z When we have to divide the sum or difference of two number by another...

read more

Finding Number of Zeros in a Number

Ekansh Rastogi | 27 November 2014

Concepts Examples To find the number of zeros at the end of a factorial or a product, find the highest power of 2 and 5 in the factorial or the product, number of zeros will be decided by the limiting factor. ( one who's power is smaller will be the limiting factor) Limiting factor is the one who's power is less among 2 and 5 e.g. Finding number of Zeros in 150 150 = 2 × 3 × 5 × 5, ∴ Highest power of 2 = 1 ∴ Highest power of 5 = 2 ∴ Limiting factor = 1...

read more

Finding Highest Power of Number

Ekansh Rastogi | 27 November 2014

Concepts Examples Finding highest power of a number can be used to find the Highest power of a number that divide the factorial Highest power of a product of numbers that divide the factorial Number of 0's at the end of the factorial To find the highest power of a number 'x' in the factorial of number N, Step 1 : Divide the number N successively till we get 0 as the last quotient. Step 2 : Add all the quotients to get the highest power that divides the factorial of N e.g Find the highest power of a 2...

read more

Render HTML String in a GSP in Grails

Ekansh Rastogi | 24 November 2014

Points To Remember By default, in grails all the html code and script code is escaped. You can render your html string as html in three ways, change in config, change at page level and change at field level.  Rendering HTML String in a GSP in Grails. Suppose we have a String like the following and we want it to get rendered as HTML in our gsp. By default out code will get rendered like this. Hi < br />My name is Ekansh Rastogi < br />I want this in three lines. But we wanted out output as Hi My...

read more

How does equals() method work in Java

Ekansh Rastogi | 11 November 2014

Points To Remember equals(), method is a method of the Object class, hence is available in all classes. Syntax of equals in Object class is public boolean equals(Object obj). It return true if two objects are same, in object class it just checks if the two references points to the same class.  We can override the equals method to provide custom logic to say the two objects are same. See How to override equals method,  Concept: Making two objects same. Suppose we have a Book class and each object represents a book. We create three objects book1, book2 and book3 (new...

read more

Contract between equals() and hashCode()

Ekansh Rastogi | 11 November 2014

Points To Remember Both the method equals() and hashCode() are the methods of Object class, hence available in all the classes. Syntax for equals() method in Object class is public boolean equals(Object obj) Syntax for hashCode() method in Object class is public int hashCode() The equals() method of Object class checks if the two references compared point to same object, returns true if they are same and false if two objects are different. We can override this functionality by our own custom way of comparing objects. If the equals() method returns true, then the hashcode() of the two object must be same....

read more

How to insert values in table from another table

Ekansh Rastogi | 07 November 2014

Points To Remember We can use subqueries in databases like Mysql and avoid multiple queries. Syntax - INSERT INTO table1 SELECT * FROM table2; We do not write VALUES in the query.  Example : Insert Values from one table to another. Suppose we have two table person and person_old with columns id int primary key name varchar age number contact varchar description text And we want to copy all the details of the table person_old to table person. Then we must write our query as. This will insert all the rows of the person_old table to the new table person. insert...

read more

How to ignore Foreign Key Constraint in Database

Ekansh Rastogi | 04 November 2014

Points To Remember A foreign key is a key that is a primary key in some another and is used to maintain a relationship with this table. Foreign key constraint failure occurs when we are trying to assign a value to a foreign key, that does not exist in the other table of which it is primary key. Solution : How to ignore Foreign key constraint failure When you need to avoid foreign key constraints, you can do SET FOREIGN_KEY_CHECKS=0; When you again need to set foreign key constraints on you can, SET FOREIGN_KEY_CHECKS=1; Note : This is not recommended...

read more

How to make Thread by extending Thread class

Ekansh Rastogi | 30 October 2014

Points To Remember We can implement Runnable interface or extend Thread class to create threads. We have to override the run() method to define the functionality of thread. We should call start() method to start execution of a thread as a new entity, if we call run() method on a thread then it will not start a new thread. We cannot guarantee which thread will execute first even if we prioritize the threads. A thread whose run() method is executed completely reaches the dead state and cannot be invoked again. Program : Making 3 Threads using Thread Class In the following example we...

read more

Find the word with maximum occurrences in a line

Ekansh Rastogi | 29 October 2014

Question : Count the number of occurrences of each word in a String Write a program to accept a string from the user and print the number of times each word of the string occurs in the input string.e.gIf the input is "Tinkle Twinkle little star" then the output should beTwinkle  - 2little        -1star         -1 Program  import java.util.HashMap;import java.util.Scanner;class CountOccurances{ public static void main(String args[]){ CountOccurances obj = new CountOccurances(); System.out.println("Enter the line of String"); String max = obj.maxOccurances(new Scanner(System.in).nextLine().split(" ")); System.out.println("Word with maximum occurances = " + max); } public String maxOccurances(String[] str){ HashMap<String,Integer> map...

read more

Java MCQ's on Random Java

Ekansh Rastogi | 29 October 2014

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Which of these is not supported by Java ? Multilevel Inheritence Multiple Inheritence Garbage Collection Data Hiding B Java does not support Multiple inheritence. It can be only achieved by making use of the Interfaces. Which of the following exceptions needs...

read more

Java MCQ's on Java

Ekansh Rastogi | 28 October 2014

This test contains 10 questions based on Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Weakest access specifier among the following is public private default protected B private has the weakest access among all. Private members of a class can be accessed only within the same class. Which access specifier should be used with a class...

read more

Program to print Numbers in Words

Ekansh Rastogi | 28 October 2014

Question : Print a given number in Words Write a program to print a number and convert it into words. Suppose we enter a number 132 the output should be "one hundred thirty two" 5234 the output should be "five thousand two hundred thirty four" 90 the output should be "ninety" Program : Print Numbers in Words import java.util.Scanner;class NumberInWords{ String once[] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; String tens[] = {"ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"}; public static void main(String args[]){ NumberInWords obj = new NumberInWords(); System.out.println("Enter the number to be converted to words"); Scanner sc = new Scanner(System.in); System.out.println(obj.getNumber(sc.next())); } public String getNumber(String num){ String words=""; int...

read more

How to add objects in a HashMap

Ekansh Rastogi | 25 October 2014

Points To Remember HashMap saves objects in form of key-value pair in form of Entry object (Map.Entry). We can use any object as a key on which hashCode() and equals() can be applied. We cannot use primitive datatypes as keys or values. We can have only one value corresponding to a key, other values will get overridden. A hashMap can contain a single null key. Initial size of a HashMap is 16 and its load factor is 0.75 after this HashMap gets rehashed. Program : Adding Objects to HashMap Below program shows how to save key-value pairs as entry objects...

read more

How to Iterate over HashMap Collection in Java

Ekansh Rastogi | 25 October 2014

Points To Remember A HashMap contains objects in key-value pair. We can use enumeration, iterator , for loop(jdk v1.5 onwards) and lamda expression( jdk v1.8) We can add values to HashMap using put(key,value). We can get all keys by .keySet() and value of a key using .get(key) Method 1: Traverse A HashMap using "for" loop The below example shows how we can traverse a HashMap in java using advanced for loop. import java.util.HashMap;class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5");...

read more

Java MCQ's on Fundamentals Of Java

Ekansh Rastogi | 24 October 2014

This test contains 10 questions based on Fundamentals Of Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Which of the following is not a conditional statement. while if for do while B if is the conditional statement out of these all the others are the loops. Which of the following is not a keyword in java....

read more

How to make threads using Runnable Interface.

Ekansh Rastogi | 21 October 2014

Points To Remember We can make threads in java by implementing Runnable Interface. Any class that implements this interface must override its run() method. The call to start() method internally calls the run() method of the thread. We can not guarantee which thread would be executed first. Thread Priority only promises the cpu time and not that it will be run first.  Program : How to make threads by implementing Runnable Interface In the below example we are implementing the Runnable interface and creating two threads "t1" and "t2" and calling the run() method using thread.start(). We run the same program twice and...

read more

How to get all Declared Fields in a Class

Ekansh Rastogi | 20 October 2014

Points To Remember We can use reflection to find all the fields available within a class. We can get all the declared fields in a class by getDeclaredFields(). We can search for any field in a class by using getField(). It throws NoSuchFieldException if the field does not exist in the class. Program : Get all the declared fields in a class import java.lang.reflect.Field;class SampleClass{ String s1 = "Class variable"; int a = 123;}class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Field feilds[] = obj.getDeclaredFields(clazz); for(Field feild : feilds){ System.out.println(feild); } }catch(Exception e){ e.printStackTrace();...

read more

How to get all Methods available in a Class

Ekansh Rastogi | 20 October 2014

Points To Remember We can use Reflection API to get all methods available in a class. Method class is present in java.land.reflect.Method class. We can use getDeclaredMethods() to get all the declared Methods in a class. We can use getMethods() to get all the methods available in a class. It also includes methods from its super classes. Program : Get All Methods Declared in a Class import java.lang.reflect.Method;class SampleClass{ String s1 = "Class variable"; int a = 123; public SampleClass(){ System.out.println("SampleClass Default Constructor"); } public SampleClass(String str){ System.out.println("SampleClass Overloaded Constructor"); } public void show(){ System.out.println("SampleClass Show Method"); } public void print(){...

read more

How to get all Constructors declared in a Class

Ekansh Rastogi | 20 October 2014

Points To Remember We can get the constructors declared in a class using Reflection API. Constructor class is present in java.lang.reflect.Constructor class. The getDeclaredConstructors() method will return an array of Constructors in a class. Program : Get all constructors declared in a class import java.lang.reflect.Constructor;class SampleClass{ String s1 = "Class variable"; int a = 123; public SampleClass(){ System.out.println("SampleClass Default Constructor"); } public SampleClass(String str){ System.out.println("SampleClass Overloaded Constructor"); } public void show(){ System.out.println("SampleClass Show Method"); } public void print(){ System.out.println("SampleClass Print Method"); }}class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Constructor cc[] = obj.getConstructors(clazz); for(Constructor...

read more

Program to convert String to Integer without using Integer.parseInt()

Ekansh Rastogi | 19 October 2014

Program : Convert a String to an Integer without using parseInt() method. We have to convert a String suppose "12345" to its equivalent integer value that is 13245 without using the parseInt() method. We need to check if the number is positive or negative and convert accordingly. import java.util.Scanner;import java.util.Scanner;class Test{ public static void main(String args[]){ System.out.println("Enter the string to be converted to integer number "); System.out.println(new Test().stringToInteger(new Scanner(System.in).next())); } public int stringToInteger(String str){ int number = 0,itr=0; boolean flag = false; if(str.charAt(0) == '-'){ flag = true; itr = 1; } for(; itr <=str.length()-1 ; itr++){ char digit =...

read more

Program to check if the given number is Armstrong

Ekansh Rastogi | 18 October 2014

Program : Find if the given number is Armstrong A number is said to be armstrong if the sum of cube of its digits is equal to the number itself.e.g.371 is an Armstrong number, since   3^3 + 7^3 + 1^3 = 371 341 is not Armstrong number, since  3^3 + 4^3 + 1^3 = 92 import java.util.Scanner;class Armstrong{ public static void main(String args[]){ Armstrong obj = new Armstrong(); System.out.println("Enter a number to check Armstrong"); Scanner sc = new Scanner(System.in); obj.isArmstrong(sc.nextInt()); } public void isArmstrong(int n){ int sum = 0,number = n; while(n!=0){ sum += Math.pow(n%10,3); n = n/10; }...

read more

How to make Object of a class By Reflection API

Ekansh Rastogi | 17 October 2014

Points To Remember Reflection API is a powerful technique to find out environment of a class as well as to inspect the class itself. Reflection API was introduced in Java v1.1 It allows user to get full information about the classes, interfaces, constructors, methods, variables etc. It is available in java.lang.reflect package. Example : Creating Object Using Reflection API In the example below we are trying to create the object of class "A" in class "Test" using reflection api. We will first get the class of "A" by using .class and then call the newInstance() method to get the object of...

read more

Java MCQ's on Method Overloading

Ekansh Rastogi | 12 October 2014

This test contains 10 questions based on Method Overloading. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Compile time polymorphism is also known as Method Overriding Method Overloading Method Rewriting None of these B Comiple Time polymorphism means that methods with same names gets resolved at the compile time only. JVM does not have to resolve these...

read more

Java MCQ's on Method Overriding

Ekansh Rastogi | 11 October 2014

This test contains 10 questions based on Method Overriding. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds Compile time polymorphism is also known as Method Overriding Method Overloading Method Rewriting None of these B Comiple Time polymorphism means that methods with same names gets resolved at the compile time only. JVM does not have to resolve these...

read more

Find the Sum of Even Digits of a Number

Ekansh Rastogi | 10 October 2014

Question : Find sum of digits of number that are even. Suppose we have a number 456789 and we need to find the sum of all the digits in the number that are even or divisible by 2.e.g In number  456789 sum of even digits is 4 + 6 + 8 = 18. import java.util.Scanner;class FindSum{ public static void main(String args[]){ System.out.println("Enter the number"); Scanner sc = new Scanner(System.in); FindSum object = new FindSum(); int number = sc.nextInt(); int sum = object.findSumOfDigits(number); System.out.println("Sum of digits of "+number+" = "+ sum); } public int findSumOfDigits(int num){ int sum = 0; while(num...

read more

Find the Sum of Digits of a number.

Ekansh Rastogi | 10 October 2014

Question : Find the sum of digits of a number Suppose we have a number and we need to find the sum of digits of the number. e.g let the number be 456789, then the sum of digits will be 4 + 5 + 6 + 7 + 8 + 9 = 39 import java.util.Scanner;class FindSum{ public static void main(String args[]){ System.out.println("Enter the number"); Scanner sc = new Scanner(System.in); FindSum object = new FindSum(); int number = sc.nextInt(); int sum = object.findSumOfDigits(number); System.out.println("Sum of digits of "+number+" = "+ sum); } public int findSumOfDigits(int num){ int sum = 0; while(num...

read more

Can We have a Private Constructor in Class

Ekansh Rastogi | 08 October 2014

Points To Remember A constructor have the same name as that of a class. A constructor does not have any return type, not even void. Constructor of a class is called first, before any other method is called. Constructor of a super class is called before the base class constructor.  We can have a private constructor in a java class. A class with a private constructor can not be inherited. We cannot create object of a class with a private constructor. What happens if we have a Private Constructor in a class. Suppose if we make a private constructor of...

read more

Program to Find All paths in a Matrix of 2D array.

Ekansh Rastogi | 07 October 2014

Problem : Find all possible paths through the array. It is only allowed to go diagonally up or down, or go to the right. An example 4x4 matrix 3 5 7 92 4 6 89 3 7 56 8 2 4 The numbers in the matrix can be any arbitrary value. I would like to generate all possible routes through the matrix, starting in one of the four numbers in the first column. It is only allowed to move Northeast, East, and Southeast. An example route: 3-5 7 9 \2 4 6-89 3 7 56 8 2 4 Solution import...

read more

Java MCQ's on Fundamentals Of Java

Ekansh Rastogi | 06 October 2014

This test contains 10 questions based on Fundamentals Of Java. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds What was the original name of Java ? Oak Pok James Coffee A Java was initially named as Oak by its founders. Who is know as the father of Java ? Ken Arnold David Holmes James Gosling Peter Dibble...

read more

Java MCQ's on Constructors

Ekansh Rastogi | 06 October 2014

This test contains 10 questions based on Constructors. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds What is the return type of Constructors? int float void None of these D Constructors does not have any return type, not even void. Which keyword is used by method to refer to the object that invoked it? import catch this...

read more

Can a Servlet have a Constructor

Ekansh Rastogi | 03 October 2014

Points To Remember Servlet is a java class that implements javax.servlet.Servlet interface. Servlets are initialized by the servlet containers using init() method. Servlets like any other java class can have constructors. Servlet must have a no argument constructor in case it have a non zero arguments constructor. Servlet needs an object of ServletConfig for initialization. Interfaces cannot have constructors. Can we have Constructors in a Servlet ? Yes we can, please read How a servlet is initialized by the servlet container. So this article will make clear, why we cannot use a constructor for initializing a servlet.However there is no problem...

read more

How a Servlet is initialized by Servlet Container

Ekansh Rastogi | 03 October 2014

Points To Remember Servlets are initialized by the servlet containers. Servlets like any other java class can have constructors. Servlet needs an object of ServletConfig for initialization. Interfaces cannot have constructors. Why a Servlet is initialized using init() method ? A servlet is a java class that implements javax.servlet.Servlet interface.A servlet can be given some init parameters in web.xml, called the ServelConfig and some global init parameters called the ServletContext. Thus they both are required at the initialization time of a servlet.Also Servlet is an interface so it cannot have a constructor, so how will we pass the ServletConfig  object to the servlet for...

read more

Difference Between HashMap and HashTable

Ekansh Rastogi | 03 October 2014

Points To Remember HashTable have the legacy code and were introduced before HashMaps. There is nothing in a HashTable that a HashMap cannot do except multithreading. ConcurrentHashMap is a replacement for HashTable, it a synchronized HashMap. Differences : HashMap and HashTable  HashMap HashTable They implement Map Interface. It extends Dictionary(obsolete from jdk 1.7) class and implements Map interface They are a part of Collections API They are not a part of Collections API They allow a single null key and any number of null values. They do not allow null values to be added. They are not synchronized or thread-safe...

read more

Find Factorial of a number using Recursion

Ekansh Rastogi | 02 October 2014

Program : Factorial Using Recursion class Factorial{public static void main(String args[]){ int number = Integer.parseInt(args[0]); System.out.println("Factorial of " + number + " = " + factorial(number));}public static int factorial(int n){ // Check if the number is greater than equal to 0. // because factorial of a number < 0 is undefined. if(n == 1) return 1; return n * factorial(n-1);}} Factorial of 5 = 120 Here the function factorial for number =1 will return  1 number =2 will return  2 * factorial(1)  = 2 * 1 = 2 number =3 will return  3 * factorial(2)  = 3 * 2 * factorial(1) =...

read more

ClassNotFoundException and NoClassDefFoundError

Ekansh Rastogi | 02 October 2014

Points To Remember ClassNotFoundException is an Exception. NoClassDefFoundError is an Error. ClassNotFoundException This is a type of error when we are trying to access a class but that class is not available at the classpath or at the path specified by us. This type of error is thrown when an application tries to load in a class through its string name using: The forName method in class Class. The findSystemClass method in class ClassLoader. The loadClass method in class ClassLoader. Example : When ClassNotFoundException occurs class A{}class Test{ public static void main(String args[]){ try{ System.out.println("classA = "+Class.forName("A").getClass()); System.out.println("classB = "+Class.forName("B").getClass());...

read more

Java MCQ's on Internal Working of HashMaps

Ekansh Rastogi | 30 September 2014

This test contains 10 questions based on Internal Working of the HashMap. Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds How are key values stored in a hashmap ? as Entry object as a LinkedList as an ArrayList None of these A All the objects in the form of a key-value pair are stored as an Entry...

read more

What are static variables in Java ?

Ekansh Rastogi | 30 September 2014

Points To Remember Static variable are the variables at the class level. Static variables are not attached to the objects. Static variable cannot be declared inside any method of a class. Static variables are assigned the memory only once during the execution of the class. Static variables can be called directly from static context or by class reference. Definition Static variables are the class level variable that are allocated the memory only once and they cannot be declared inside any method of a class or inside a static block or static method but can be declared only  outside all methods...

read more

Can we override a static method in Java ?

Ekansh Rastogi | 29 September 2014

Points To Remember Static methods can not be overriden. Static methods are at class level and not at object level. Static methods take lock on a class and non static methods takes lock on an object. Example : Trying to override a static method Suppose we have a class A and another class B that extends this class. Both the classes have same static method test() with same return type and same parameters. So this satisfies this the conditions for overriding a function. So what will be the output of the following program ? class A{ public static void test(){...

read more

What is a TreeSet in Java ?

Ekansh Rastogi | 26 September 2014

Points To Remember TreeSet is ordered and sorted Set. TreeSet extends AbstractSet and implements NavigableSet. Objects are stored in ascending order based on natural ordering. You can even define your sorting rules for sorting a TreeSet using constructors with Comparable or Comparator. It is fast for Accessing/Retrieving objects but slow for Adding/Removing objects.  Constructor : TreeSet TreeSet(); // Default ConstructorTreeSet(Collection<? extends E> c); //TreeSet from Collection CTreeSet(Comparator<? super E> comp); // TreeSet with custom ordering as per ComparatorTreeSet(SortedSet<E>ss); //TreeSet that contains the elements of ss. Example : TreeSet Implementation Suppose we have a Set of Tourists from different countries and...

read more

How HashSet works internally in Java ??

Ekansh Rastogi | 26 September 2014

Points To Remember HashSet returns unordered and unsorted values. HashSet contains only the unique values. HashSet maintains an internal HashMap to provide uniqueness.  How Set maintains Uniqueness ?? The following program shows how we add new values to a set. import java.util.Set;import java.util.HashSet;class SetImpl{ public static void main(String args[]){ Set<object> set = new HashSet<object>(); set.add(100); set.add("Java"); set.add("String"); set.add("Java"); set.add("Java"); System.out.println(set); }} Output of the program is [100, String, Java]Now, the question is how does Set maintains  uniqueness. The answer is that Set internally maintains a HashMap. Surprised ?? If you open the implementation of HashSet in the java api you will get...

read more

What is a JSP in Java J2EE.

Ekansh Rastogi | 21 September 2014

Points To Remember JSP stands for Java Server Pages. Jsp at compilation time is a servlet and also behaves like a servlet. Jsp serves as views in MVC architecture. Jsp can contain HTML code inside them. They are compiled everytime they are requested. What is a JSP ? JavaServer Pages (JSP) is a technology for developing dynamic web pages with dynamic data. You can write java code within a jsp along with the Html using special Jsp tags most of which start with <% and end with %>.A JavaServerPage component is a type of Java servlet that is designed to fulfill...

read more

Difference between ServletConfig and ServletContext

Ekansh Rastogi | 19 September 2014

Difference : ServletContext vs ServletConfig ServletContext ServletConfig Servlet Context is a global configuration for servlets in a an application i.e this is same for all the servlets.  Servlet Config is a local configuration for each servlet in an application i.e each servlet has its own servlet configuration that may differ from the servlet config of another servlet. ServletContext is one per application. ServletConfig is one per servlet.  It is created at the time of deployment of the web application. It is initialized when a servlet is initialized.  Its scope is as long as the application is up and running, it...

read more

What are Filters in Java J2EE applications.

Ekansh Rastogi | 17 September 2014

Points To Remember A filter is hit before the servlet or a controller is hit and before the response is sent back to the client. Filters can be used to apply some action on application level. A filter implements the javax.servlet.Filter interface and the primary filter functionality is implemented by the doFilter() method of the filter. Filters can be used to manipulate both requests from client and response from server. What is a Filter in Java Web Applications ? A filter is a useful way of performing filtering operations in java web applications bith before a request reaches the backend...

read more

How to select Second largest value from a database.

Ekansh Rastogi | 16 September 2014

Why this question is important ? This is a most frequently asked question in an interview these days. This question tests the thinking of a candidate and how much the candidate knows about the database. This question  cannot be done without the use of a sub query and most of the people are not comfortable writing the sub-queries. So if you are not very comfortable with database queries you might get tricked in this question. Example  Suppose we have a table with id's from 1 to 1000 and we need to find the second largest id from this table.Let's say...

read more

Introduction To Spring Roo

Ekansh Rastogi | 16 September 2014

What is Spring Roo ? Spring Roo is a spring productivity tool that simply reduces the pain of a developer by doing all the configuration related stuff for a project. Spring Roo does not require any extra knowledge  expect java. Roo makes it fast and easy to build full Java applications in minutes. Why Use Spring Roo ? Following are the points why we should use Spring Roo. Higher Productivity - We can get started with the java project just in minutes and the roo follows the best practice standard methods to create the application for us Stock Standard Java...

read more

Sorting objects using Comparable Interface.

Ekansh Rastogi | 12 September 2014

Points To Remember Comparable is an interface and is available in java.lang package. A class implementing it should override compareTo() method. compareTo(Object obj) method returns  negative integer if object obj is greater than the object with  whom it is compared. 0 if both the objects have same values or are same. positive integer if object obj have is less than the object with whom it is compared. While overriding compareTo() method we must check If the two objects belong to the same class, else throw ClassCastException. If the two objects are not null, if either is null then throw NullPointerException....

read more

Difference between Comparator and Comparable Interfaces

Ekansh Rastogi | 12 September 2014

Difference between Comparator and Comparable Comparator Comparable It is available in java.util package. It is available in java.lang package. We need to override compare() method. We need to override compareTo() method. It takes two arguments as parameters.public int compare(Object obj1,Object obj2 )  It takes only one argument as a parameter.public int compareTo(Object obj) Its primary use is where we need to write the comparing logic outside the class which has to be compared.   It is used when we need to compare the instance of an object with a given object. Comparing logic is inside the class that needs to be compared....

read more

Difference between Interface and Abstract Class

Ekansh Rastogi | 11 September 2014

Difference Between Interface and Abstract Class Interface Abstract Class An interface is an unimplemented class. An abstract class is an incomplete class. All methods are by default public abstract. An abstract class can have both abstract and non abstract methods. All variables by default public static final by default Variables may be static final or may not be.  They cannot have any implemented methods. They can have any number of  implemented methods. An interface must be implemented by the base class. An abstract class must be extended by the base class. You need to override each method of an interface...

read more

What are classes in Java

Ekansh Rastogi | 11 September 2014

First things that comes in mind are A class is a blueprint from which objects are created. They are wrappers and have everything inside them e.g Functions/Methods/Variables etc. They can be public or default but not private or protected. Each Class has a name, and may belong to a package. A class can have both static and non static methods and variables. A class can not be static (however inner classes can be). Definition A class is the blueprint from which individual objects are created. A class containes A main method marked as public static void and taking an array...

read more

How to sort objects using Comparator Interface

Ekansh Rastogi | 11 September 2014

Points To Remember Comparator is an interface and is available in java.util package. A class that implement Comparator interface must override its compare() method.  We use Comparator when we have to write logic for comparing object of a class outside that class. compare(Object e1, Object e2): Can be called like compare(e1, e2) compare(Objecte obj1, Object obj2) method returns zero if the objects are equal. compare(Objecte obj1, Object obj2) method returns a positive value if obj1 is greater than obj2. compare(Objecte obj1, Object obj2) method returns a negative value if obj1 is smaller than obj2. It should throw ClassCastException if object types of e1...

read more

Program to reverse each word of the String.

Ekansh Rastogi | 09 September 2014

Program : Reverse each word of String  Write a program that takes a string input from the user and then reverse each word of the of the line as entered by the user.Expected input   : "This is a very good blog"Expected output : "sihT si a yrev doog golb" import java.io.*;public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); String inputString = obj.getStringFromUser(); String outputString = ""; String aux = ""; for(int itr=0;itr<inputString.length();itr++){ // reverse the words if a whitespace occurs. if(inputString.charAt(itr) == ' '){ outputString += reverseString(aux) + " "; aux = ""; }...

read more

Program to reverse a String

Ekansh Rastogi | 09 September 2014

Program -1 Reverse String with input String from arguments public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); System.out.println(obj.reverseString(args[0])); } public String reverseString(String str){ String aux = ""; for(int itr = str.length()-1;itr>=0;itr--){ aux += str.charAt(itr); } return aux; } } Running the program as : java ReverseString ekiras Output of the program : sarike Program -2 : Reverse String with input from command line at runtime. import java.io.*;public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); System.out.println(obj.reverseString(obj.getStringFromUser())); } public String reverseString(String str){ String aux = ""; for(int itr = str.length()-1;itr>=0;itr--){ aux += str.charAt(itr);...

read more

Different ways of creating Objects in Java

Ekansh Rastogi | 09 September 2014

Different ways of creating Objects Using new operator. Using Class.forName() and newInstance(). Using Factory Methods Using Object cloning Using Object deserialization Object Creation By Different Methods public class ObjectCreation { public static void main(String args[])throws Exception{ ObjectCreation objecByNewKeyword = createObjecByNewKeyword(); ObjectCreation objecByClassForName = createObjecByClassForName(); ObjectCreation objecByCloning = (ObjectCreation)createObjecByCloning(); // object to be cloned objecByNewKeyword.show("new keyword"); objecByClassForName.show("using Class.forName and newInstance"); objecByCloning.show("cloning"); } public static ObjectCreation createObjecByNewKeyword(){ ObjectCreation obj = new ObjectCreation(); return obj; } public static ObjectCreation createObjecByClassForName() throws ClassNotFoundException, InstantiationException, IllegalAccessException{ ObjectCreation obj = (ObjectCreation)Class.forName("ObjectCreation").newInstance(); return obj; } public static ObjectCreation createObjecByCloning()throws CloneNotSupportedException{ ObjectCreation obj = new ObjectCreation(); ObjectCreation clone =...

read more

What is a static block in Java ??

Ekansh Rastogi | 08 September 2014

Points To Remember A static block is called only once and is not a member of a class. A static block is executed before execution of any other method in the class. If there are more than one static block in a class then, they are executed in order of their occurence in a class. They do not have a return statement. They cannot contain this or super reference. What is a Static block in Java?? A static block is a block of code that gets executed first at the time the class is called or its object is created. Even...

read more

What is the Difference between Enumeration and Iterator

Ekansh Rastogi | 08 September 2014

Points To Remember In java 1.0, there were two primary collection classes HashMap and Vector. Enumeration was a class in Java 1.0 to Iterate through these collection classes.(They are not the enum types.) Iterator was introduced in Java 1.2 Difference between Enumeration and Iterator. Enumeration Iterator It was introduces in Java v1.0 It was introduced in java v1.2 Enumeration does not have remove() method Iterator has remove() method Enumeration provides a read only iteration over collection Iterator provides iteration over collections along with manipulation of objects like adding and removing from object. Enumeration is less safe and secure Iterator is...

read more

What is final keyword in Java.

Ekansh Rastogi | 08 September 2014

Where can Finally keyword be used ??Finally keyword can be  used with the following final variable, a variable marked as final acts like a constant variable whose value can not be changed once assigned throughout the life of the variable. final method, a method marked as final can never be overridden but can be overloaded.  final class, a class marked as final can never be extended. final object, final object is an object whose reference can not be changed once assigned. Final variable final variable when used with any variable, then this variable starts acting like a constant. Value of this variable can...

read more

How does a HashMap works internally in Java ??

Ekansh Rastogi | 07 September 2014

Points To Remember HashMap implements the Map Interface. It works on the principles of hashing.  It stores and retrieves data in a key value pair. HashMap can have only one key as a null element. HashMap stores both key and value in form of Entry object Map.Entry.  Initial capacity of HashMap is 16. (Since jdk 1.7 we can have HashMap with initial capacity as 0). Default load Factor of a HashMap is 0.75, after this a HashMap gets rehashed.  Q1 : How does HashMap work internally ?  We add data to the HashMap in key-value pair, by method put(key, value). When we...

read more

Create Mysql Database JDBC connection in Java.

Ekansh Rastogi | 04 September 2014

Points To Remember  Download Mysql Java Connector by clicking on the link. Put the above downloaded jar file in the lib folder of your project. Code : Mysql JDBC connection in Java import java.sql.Connection;import java.sql.DriverManager;public class JavaMysqlConnection { private String host = "localhost:3306"; // For running on localhost private String db = "databaseName"; private String userName = "userName"; private String password = "password"; public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://"+ host +"/"+db,userName, password); return conn; }catch(Exception e){ e.printStackTrace(); } return null; }} public class Test{ public static void main(String[] argv) { Connection conn = new JavaMysqlConnection().getConnection(); if(conn == null)...

read more

What is Method Overriding in Java ??

Ekansh Rastogi | 04 September 2014

When a base class extends a super class and both the base class and the super class have a method with same name, same types of parameters and same number of parameters, then the two methods are said to be overriden. Points To Remember Overriding of methods is always done in a base class or in other words, we always override a parent class method. The access specifier of the overriden method can not be less than the parent class method's access specifier e.g if a parent class method is marked as protected, you can override it with access specifiers...

read more

Difference between Method Overloading and Method Overriding

Ekansh Rastogi | 04 September 2014

Key Differences Method Overloading Method Overriding Method Overloading always happens within the same class. Method Overriding always happen between a super class and a sub class. In method overloading the return type of the method need not to be the same. In method overriding the return type of the method must be same  Number of arguments can be different. Number of arguments should be same. Overloaded methods can have different access specifiers. Overriding method should not have weaker access specifier than the method it is overriding. Type of arguments can be same or different. Type of arguments should be same....

read more

What is Method Overloading in Java ??

Ekansh Rastogi | 04 September 2014

We can have multiple methods with the same name as long as their parameter types or number of parameters differ. These methods are called overloaded methods. This is also referred as Static Polymorphism. Points To Remember Overloading of methods is always done in the same class. The access specifier of the overloaded method may or may not be same  to the other overloaded methods. Name of the overloaded methods should be same. The overloaded methods may have different return types. Overloaded methods should have at least one of the following Different argument types Different number of arguments They provide Static...

read more

Overriding equals() method of Object class in java

Ekansh Rastogi | 04 September 2014

Default equals() method of the java.lang.Object class compares the memory location of the objects and returns true if the two reference variables are pointing to the same memory location. i.e. they are the same objects. Points To Remember equals() method is the method of Object class. It compares the memory location of the two objects. equals() method in java is Reflexive. i.e, object must be equal to itself. equals() method in java is Symmetric.  i.e, if a.equals(b) then b.equals(a) must be true. equals() method in java is Transitive.  i.e,  if a.equals(b) and b.equals(c) the a.equals(c) must be true. equals() method in java is Consistent.  i.e, if two objects are...

read more

Can we have multiple main methods in Java ?

Ekansh Rastogi | 03 September 2014

Points to remember We can have only one entry point per class in Java. Thus we can have only one "public static void main(String args[])". Any other method with a different name or type or arguments will not be treated as a main method(). Yes, we can have multiple main methods in a java class. Surprised ?? Method Overloading, by using this you can have as many main() methods as you want as long as their types or arguments are different. However these are not actually the main() methods, these are just overridden methods and may act as any other...

read more

Why the main method in java is public static void

Ekansh Rastogi | 03 September 2014

What is the "main" method in java?? It is the entry point of execution of any java program. We must have a main(String args[]) or main(String ...) method in a class for its execution. We can have multiple main() methods in a class. Why is main method "public" ?? The main method is always marked as public  because it must always be visible or available to the JVM. You can even say that this is the java convention and it needs to be followed. If we make our main() method as private, our code will still compile without giving any...

read more

What are MIME types

Ekansh Rastogi | 02 September 2014

Points To Remeber MIME stands for Multi-purpose Internet Mail Extensions. MIME is an extension of the original Internet e-mail protocol that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video, images, application programs MIME types were originally used to send different file types through email services over SMT SMTP(Simple Mail Transfer Protocal) protocal.  MIME types form a standard way of classifying file types on the Internet e.g. using the "Content-type" header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.   Internet programs such as Web...

read more

How to display a pdf file in browser using java

Ekansh Rastogi | 01 September 2014

Display PDF in browser using Java from response response.setContentType("application/pdf");response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");response.setContentLength((int) FileInputStream input = new FileInputStream("File.pdf").length()); The above lines of code can be used to send a response to the view( like .jsp) as a pdf.  This will open the pdf in the browser and not make the pdf downloadable. Display PDF in browser view page To indicate to the browser that the file should be viewed in the browser : Content-Type : application/pdfContent-Disposition : inline; filename.pdf To have the file downloaded rather than viewed: Content-Type : application/pdfContent-Disposition : attachment; filename.pdf

read more

How to view table schema in Mysql

Ekansh Rastogi | 01 September 2014

Syntax : SHOW CREATE TABLE tablename When To Use ? You already have a table in the database and you want to view how this table was created. You want to check all the datatypes, default value, nullability of the columns. You want to see all the constraints and keys that are applicable to this table. This command can be used to recreate the table as it is with all constraints and keys set.  Example Suppose we have two tables Institute and User  and we want to check the schema of the tables or in simple terms how these tables...

read more

Hibernate @NotFound Annotation

Ekansh Rastogi | 28 August 2014

Hibernate provides the annotation @NotFound.  This annotation can be used in cases where we have relationships between the Entities e.g. ManyToOne or OneToMany or ManyToMany etc.Syntax - @NotFound(action=NotFoundException.IGNORE) When we want to access an entity using the relation from another entity, if the value of this entity is not available then the hibernate throws an exception. We  can use @NotFound annotation to ignore these exceptions. NotFoundException.IGNORE tells the hibernate to avoid throwing the exception if the record for the entity is not found. @Entity(name="user")@Table(name="user")public class User{}

read more

Hibernate Primary Key Generation Strategies

Ekansh Rastogi | 27 August 2014

There are 4 types of Generation Strategies that can be used to generate Id in hibernate. AUTO  e.g. strategy = GenerationType.AUTO IDENTITY e.g. strategy = GenerationType.IDENTITY SEQUENCE e.g. strategy = GenerationType.SEQUENCE TABLE e.g. strategy = GenerationType.TABLE strategy = GenerationType.AUTO This is the default Generation Strategy that is used by the hibernate. This strategy allows hibernate to decide what strategy to be used to generate the unique key for the table. Strategies used by hibernate can be different for different types of databases used. strategy = GenerationType.IDENTITY In this Generation Strategy the hibernate is going to use an identity column. Identity column is a...

read more

Difference between Grails Respond and Grails Render

Ekansh Rastogi | 27 August 2014

First things that comes in mind Respond was introduced in Grails v2.3. Render is used by Grails to render different forms of responses from simple text response, to views to templates. Respond automatically attempts to return the most appropriate type for the requested content type. Respond is a better version of render, and can do everything render does. Example In case you want to send data to the view in "xml" or in "json" format then you will have to do the following render : // renders text for a specified content-type/encodingrender(text: " some xml ", contentType: "text/xml", encoding: "UTF-8"render(text: "...

read more

What are Objects In Java

Ekansh Rastogi | 12 August 2014

First things that comes in mind are They are real things They occupy some space in memory They have a state and some characteristics Definition Java Objects are the real world entities that can have a state and some behavior. They are created from a blueprint i.e. classes. Example If we say that Person is a class, then person is a blue print of every human in this world and we are all the objects of this class Person.Since each object has some state and some characteristics, thus we may be similar or different from each other ion the basis of...

read more