Posts

Showing posts from September, 2016

Basic Authentication Setup Java Web Application

Image
This blog shows how to setup Basic Authentication in Web application. I am using Spring based Web Service to demonstrate the same. To start please ensure that you have spring application configured properly. On top of that i will show what changes needs to be be made to enable Basic Authentication. Securing application is one of the important activity which developer and designer has to keep in mind while designing. Basic authentication can be one of the basic security mechanism which can be enabled to secure web application or web service. Basic Authentication security is where application will expect the consumer to pass User and password in request header. In case if these values are not passed then spring framework will throw back Unauthorized error code. Following are the steps which needs to be followed. Step1: Add the spring security jar files in the application. Following are the jar files. spring-security-core.jar spring-security-config.jar spring-security-web.jar Step2: Add f...

GIT vs SVN

GIT vs SVN In the DevOps world, selection of right SCM tool is a significant decision. Since these tools are kind of driving force behind the process, a wrong SCM selection may lead to inefficiencies throughout your delivery pipeline. I personally have used CVS and SVN in most part of my career. Those projects were not really Agile projects. While we had some kind of CI and CD, there were no end to end DevOps process in place. So we were able live with it. Recently I started using GIT - both private GIT as well as public GITHUB and BIT BUCKET.  Also in the recent assignments, we don't just go with what is provided by customer. We demanded the right SCM. We study the customer needs and recommend centralized or distributed SCM.  In this blog, I will  compare the capabilities of GIT and SVN at very basic level. This blog does not cover the detailed scenarios like when GIT performs better over SVN and vice versa or how GIT's way of working on the content instead of file helps...

Mockito setup in Spring application

Mockito is used widely for application code Unit Testing. In this blog I will show the dependencies which are required to configure Mockito in Spring Web application. In the existing Spring based application, following dependent jar files needs to be added. asm-1.0.2.jar hamcrest-all-1.3.jar json-path-1.2.0.jar json-smart-2.1.0.jar junit-4.11.jar mockito-core-1.9.5.jar objenesis-2.1.jar after adding these jar file you are all set to start writing the Mockito based JUnit test cases. Few of the useful plugin for Eclipse IDE that will help in analyzing code coverage can be installed. The plugin which I used for code coverage is "EclEmma". This can be installed from Eclipse market place which gives report on percentage of code line which has been covered by Unit Testing.  In subsequent blogs i will show some sample Mockito Unit Test cases classes.

Use Swagger UI for showing interactive API documentation

Image
Following Swagger post I showed how to configure Swagger with Spring project . In this blog I will demonstrate using Swagger UI for showing interactive documentation. Swagger UI is part of the Swagger project and it allows you to generate, visualize and consume API. It is package which basically consist of html, css and javascript, and parses the json output generated from application code scanning. This scanning and configuration was explained in following post. Swagger UI Setup can be downloaded from " here ". Copy the files to a Dynamic Web project in eclipse and paste the content from "dist" folder to WebContent as shown below. Here I am using tomcat server to host this UI application. By doing so it will be easy to share the API application with other user. It shows following UI.  Please note that by default swagger will load the petstore Api details. I will cover customizing them in next point.  Swagger UI presents very nice interactive tool, using which users...

Reading log file path from environment Variable in logback

In this short blog i will be showing how to read the log folder location from environment variable. In general log path for an application is one time configuration. So why to keep multiple property files for each environments. Better approach could be using environment variable on server, which can be configured once. Here i am using Tomcat 7.x as a server. For Logback using following jars. logback-classic-1.1.3.jar logback-core-1.1.3.jar First lets start by creating environment variable in tomcat server. For this you need to open context.xml file located at TOMCAT_HOME/conf folder. Open with text editor and add following line in the file. <Environment name="LOG_PATH" type="java.lang.String" value="/logs"/> you are done with creation of environment variable which will be accessible via jndi lookup. next will be open logback.xml file which contains application logging configurations. Use JNDI lookup to retrieve the environment variable. Logback pro...

Swagger API doc for Spring Based Webservices

When any API is created one of the major challenge is to create documentation, also once documentation is created then updating it over the period of time for any changes which are done in API. In this blog I will be demonstrating how to create API documentation for REST webservices using Swagger tool. Swagger is very mature API doc creation tools. It provides interactive documentation with very good ecosystem like Swagger UI, Swagger Editor. Swagger is intelligent enough to scan through the code automatically and it generates am output which are easily readable by human and even system. In this blog i will be showing swagger integration with Spring based rest webservices(bottom up). Prerequisite for this blog is that you have Spring API project created and working. To start first download following jar files and add them in your project. aopalliance-1.0.jar aspectjrt-1.8.6.jar aspectjweaver-1.8.6.jar classmate-1.2.0.jar guava-18.0.jar mapstruct-1.0.0.CR1.jar spring-hateoas-0.18.0.RELE...

Setup Ubuntu Virtual Machine on Windows

Image
In this blog i will be showing how to configure Virtual machine in windows machine. In this blog i will show the demo using Virtual Box which is an open source tool, and it can be freely downloadable from Virtual Box  . Download the "VirtualBox-5.1.4-110228-Win" installer from above link. Download " Ubuntu " OS. Ensure that you have sufficient disk space and decent RAM, as VM needs use from the available resources. Double click on the installer , and follow the wizard steps. Below is combined screenshot of installation steps. Virtual box installation steps screenshot After installation is complete, start virtual box application.  Before we go further ensure that you downloaded Ubuntu OS from the link mentioned above. Ubuntu setup will be required while creating Virtual Machine. There are various OS supported, you can see that while setting up. Start the Virtual Box application, click on New menu, and select following in the popup             ...

SSO on Windows using Waffle - Java Web Application

Image
Waffle is open source API which helps in windows based authentication. If project requirements is to auto login a user with Windows login credentials then Waffle provides one option to achieve the same. Waffle supports Negotiate, NTLM and Kerberos. In this blog I will create a Java Web Project to demonstrate how to get the windows logged in credentials using Waffle. Prerequisites: Tomcat Eclipse Create a new Dynamic Web Project in eclipse.  Create Dynamic Web Project Add following jar files related to Waffle setup. commons-logging-1.1.1.jar guava-r07.jar jna.jar platform.jar waffle-jna.jar Next step will be to add the filter classes to handle SSO with windows.  Add filter class "waffle.servlet.NegotiateSecurityFilter", this class takes care of doing negotiation with windows system by invoking necessary classes with in the waffle jars.  Sample code for the same is given below for web,xml file. <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:x...

Handling Cross site Scripting

Image
Typically in web application cross site scripting issue is one of the most occurring issues. Cross site scripting vulnerability occurs when hackers are able to execute script code in your application. This can happen due exploiting weakness in the application code. Like Trusting data which comes from any of the system. Lack of data filter for data cleansing before data goes inside the system. Use of Scriptlet  <%=%> for printing data in JSP without validating the data. CSS can broadly be categorized in two subsections. If hackers are able to persist their malicious code in application persistence layer (DB), and whenever any application user visits the web page, these malicious code gets executed and hacker will be able to exploit user. This type is persistent and are more dangerous.          Hacker can add dynamic redirection to some of his malicious site, and capture confidential data. As this redirection happened from the parent site user also will...

SQL Injection security Vulnerability

Image
This article i will be covering SQL Injection security vulnerability. What is SQL Injection? SQL Injection means, modifying application query in such a way that it tweaks the actual query results. With this issue present in application Hacker can easily manipulate the query and can gain access to application data and functionality. How to address this issue? There are many things which application developer can take care during the development phase which can avoid these issues. Usage of PreparedStatement while doing database operations. Usage of CallableStatement which is used to call database Procedures.  Input validations and Data Encoding. Database related constraints like, usage of proper grant, privilege, views etc.    Below is simple example on how the attacker can use this vulnerability to exploit system. Lets assume that in the web application there is login screen which prompts user to enter user credentials.  In the application to validate the user fo...

Parallel AJAX calls

Consider a scenarios where you have multiple source of data and that needs to be consolidated in the UI and presented to the users. There can be different ways to implement this. One option can be using AJAX approach. JQuery provides a way to initiate parallel AJAX calls. In this blog i will be showing a sample code to achieve same. Using Jquery provided "$.when" function, which provides a way of executing asynchronous events. $.when takes asynchronous ajax events as a parameter, and the output of these AJAX events will return in ".then" in the same order. $.when(ajax1, ajax2,....).then(resp1,resp2,....); Following is the sample code to make parallel ajax call. var url1="http://localhost:8080/url1"; var url2="http://localhost:8080/url2"; var param="s=abcd"; $.when( $.ajax({timeout:10000,error:function(){handleErrorScenario();},type: "get", url:url1, async : true, data:param}), $.ajax({timeout:10000,error:function(...

Using Apache CXF initiate SOAP call

Image
IN this blog i will be showing how to consume SOAP webservice in java by generating Client code using Apache CXF. Prerequisites for this blog are as follows. Eclipse Mars Java Apache CXF WSDL file for any SOAP webservice. Install CXF Apache CXF can be downloaded from " CXF ". After downloading setup, unzip it in your system.  Configure cxf in eclipse.  Go to Windows - Preferences - Webservice - CXF 2.0 Preferences Then select CXF Runtime - click on Add - Specify CSF installed location - Click on Finish. I have highlighted the steps with blocks in below screen shot. Setting Up CXF in Eclipse Create Web Project or Paste WSDL in existing project. After configuring you need create Project in eclipse, or if you are using it in existing project then paste the WSDL file which you have received from service provider. Next step will be to generate the client code Right click on wsdl file, Go to - Webservice - Generate Client Webservice Client popup will come, next specify the Configur...

Cross domain Calls in AJAX with Jsonp

Web browser doesnot allow initiating cross domain call from javascript. There are multiple ways to initiate cross domain calls, I will be showing example on how to make cross domain call from javascript using jsonp. Using Jquery following is the way to initiate Cross Domain call. in $.ajax method, "dataType" parameter should be set to "jsonp", here jsonp means Json with padding, with jsonp a javascript code is injected in client browser, which enables code to make cross domain call. function initiateCrossDomainCall(url) { $.ajax({ dataType: 'jsonp', // json with padding type:"GET", url : url, success: function ( data) { parseResp(data); }, error: function ( data, status, error) { parseErrorResp(data, status, error) }, timeout: 2000 }); } function parseResp(data){ //add code to parse responsedata. } function parseErrorResp(data, status, error){ // parse errr resp...

Creating Exception Handler in Spring

In this blog i will show how to create Exception handler in Spring. I assume that you already have Spring application setup and it is running. Exception handling is one of the piece which gets ignored and in latter stages of the development it becomes unmanageable task. There will not be a consistent and common approach if it is not taken up at the beginning stages. Spring framework makes developers life pretty simple with the api which it provides for Exception handling at global/application level. Nice thing about this approach is that it becomes a single place for handling all the exception and becomes more manageable. In this example i will be creating MyAppExceptionHandler. This will be single class which will be responsible for handling any exception scenario. to start with create a class " MyAppExceptionHandler " this needs to implement an interface named " HandlerExceptionResolver " and " Ordered ". Implement the default method which your IDE wil...

Configure SonarQube with Jenkins

Image
   Jenkins provides easy integration with different kinds of plugins which are helpful in overall improvement and management of development life cycle and code quality. One of such plugin is SonarQube.     SonarQube is code quality analysis software. It runs through the code and identifies code quality issues. It has got web portal where you can generate different kinds of reports like Technical Debt Code Issue, with actual code linkage. Different types of reports. Maintains the history of issue details. Can check increase and decrease. Rules configuration. Quality Gates Code duplication and Many others.     There is provision in Jenkins to integrate this plugin, which can be executed during the building of applications. Also there is option of failing the build process if the code quality does not match the defined quality gate in Sonar.   Now i will show how to integrate this plugin with Jenkins. Assumption is that Jenkins is installed in your system...