Monday, March 11, 2019

How to upload Image file from AngularJS 6 to Spring Controller and then finally on FTP Server

Step 1:- Configuring Local FTP Server.
package com.test.siddhu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
public class FTPFunctions {
// Creating FTP Client instance
FTPClient ftp = null;
public FTPFunctions()
{
}
public void StartServer()
{
try {
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();

factory.setPort(21);
serverFactory.addListener("default", factory.createListener());
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("C:\\Test\\users.properties"));
serverFactory.setUserManager(userManagerFactory.createUserManager());
// start the server
FtpServer server = serverFactory.createServer();
server.start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception occured ———————");
e.printStackTrace();
}
}
// Constructor to connect to the FTP Server
/**
* @param host
* @param port
* @param username
* @param password
* @throws Exception
*/
public FTPFunctions(String host, int port, String username, String password) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host,port);
System.out.println("FTP URL is:"+ftp.getDefaultPort());
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(username, password);
ftp.setFileType(FTP.LOCAL_FILE_TYPE);
ftp.enterLocalPassiveMode();
}

// Main method to invoke the above methods
public static void main(String[] args) {
try {
FTPFunctions objFTPFunctions = new FTPFunctions();
objFTPFunctions.StartServer();
ftpobj.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Image1
Step 2:- Create a Spring Boot controller for your AngularJS6 Frontend.

1-SpringBootRestApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.siddhu"})
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
2- SiddhuController
package com.siddhu.welcome;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.siddhu.beans.SiddhuBean;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
@Controller
public class SiddhuController {
private static final String welcomemsg = "This is test message. %s!";
@GetMapping("/siddhu/message")
@ResponseBody
public SiddhuBean welcomeUser(@RequestParam(name="name", required=false, defaultValue="Java Fan") String name) {
return new SiddhuBean(String.format(welcomemsg, name));
}
//by siddhu getting Image from FTP File directly start[
@GetMapping(value = "/siddhu/image")
public @ResponseBody String getImage() throws IOException {
String encodedImage = "";
byte[] res = null;
try{
FTPFunctions ftpobj = new FTPFunctions("localhost", 21, "admin", "admin");
//ftpobj.retriveFTPFile("/uploadftp/siddhuupload.txt");
/*BufferedImage image = new BufferedImage(200, 200, 1);
ImageInputStream iis = ImageIO.createImageInputStream(ftpobj.retriveFTPFile("/uploadftp/siddhu.jpg"));
image = ImageIO.read(iis);*/
//BufferedImage image = new BufferedImage(100, 100, 5);
BufferedImage image = ImageIO.read(ftpobj.retriveFTPFile("/uploadftp/5008255e16468b1f8b1a55abd242db7e.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
res=baos.toByteArray();
encodedImage = Base64.encode(baos.toByteArray());
System.out.println("The encoded image byte array is shown below.Please use this in your webpage image tag.\n"+encodedImage);

}
catch(Exception e) {
e.printStackTrace();
System.out.println("Some problem has occurred. Please try again");
}
return encodedImage;
}
//by siddhu getting Image from FTP file directly end]

//by siddhu uploading image start[



@RequestMapping(value = "/siddhu/upload", method = RequestMethod.POST)
public @ResponseBody void uploadImage(@RequestParam("uploadedFile") MultipartFile uploadedFileRef, @RequestParam("fileName") String fileName) throws IOException {
try{
System.out.println("--------------------------------------------------------"+uploadedFileRef.getContentType()+"----"+uploadedFileRef.getOriginalFilename()+"--"+uploadedFileRef.getName());
InputStream inputStream = new BufferedInputStream(uploadedFileRef.getInputStream());
FTPFunctions ftpobj = new FTPFunctions("localhost", 21, "admin", "admin");
ftpobj.uploadMultipleFTPFile(inputStream, fileName, "/uploadftp/");
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Some problem has occurred. Please try again");
}
//return encodedImage;
}
//by siddhu uploadoing image end]
}
3 - FTPFunctions
package com.siddhu.welcome;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
public class FTPFunctions {
// Creating FTP Client instance
public FTPClient ftp = null;
public InputStream objInputStream = null;
public ImageInputStream iis = null;
public FTPFunctions()
{
}
public void StartServer()
{
try {
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
// set the port of the listener
factory.setPort(21);
// define SSL configuration
/*SslConfigurationFactory ssl = new SslConfigurationFactory();
ssl.setKeystoreFile(new File("C:\\Test\\ftpserver.jks"));
ssl.setKeystorePassword("password");*/
// set the SSL configuration for the listener
/*factory.setSslConfiguration(ssl.createSslConfiguration());
factory.setImplicitSsl(true);*/
// replace the default listener
serverFactory.addListener("default", factory.createListener());
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("C:\\Test\\users.properties"));
serverFactory.setUserManager(userManagerFactory.createUserManager());
// start the server
FtpServer server = serverFactory.createServer();
server.start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception occured ???????");
e.printStackTrace();
}
}
// Constructor to connect to the FTP Server
/**
* @param host
* @param port
* @param username
* @param password
* @throws Exception
*/
public FTPFunctions(String host, int port, String username, String password) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host,port);
System.out.println("FTP URL is:"+ftp.getDefaultPort());
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(username, password);
//ftp.setFileType(FTP.LOCAL_FILE_TYPE);
//by siddhu to show image properly on the screen and also to upload image properly in FTP else image will be corrupt.
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
// Method to upload the File on the FTP Server
public void uploadFTPFile(String localFileFullName, String fileName, String uploadDir)
throws Exception
{
try {
InputStream input = new FileInputStream(new File(localFileFullName));
this.ftp.storeFile(uploadDir + fileName, input);
}
catch(Exception e){
}
}
// Download the FTP File from the FTP Server
public void downloadFTPFile(String ftpSource, String destination) {
try (FileOutputStream fos = new FileOutputStream(destination)) {
this.ftp.retrieveFile(ftpSource, fos);
} catch (IOException e) {
e.printStackTrace();
}
}
// by siddhu Download the FTP File from the FTP Server start [
//public ImageInputStream retriveFTPFile(String ftpSource) {
public InputStream retriveFTPFile(String ftpSource) {

try {
objInputStream = this.ftp.retrieveFileStream(ftpSource);


} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("objInputStream--------------------->"+objInputStream);
return objInputStream;
//return iis;
}
// by siddhu Download the FTP File from the FTP Server end ]

//by siddhu to upload multipart start[
public void uploadMultipleFTPFile(InputStream inputStream, String fileName, String uploadDir)
throws Exception
{
try {

System.out.println("---------------------------here reached filename----------------"+uploadDir + fileName);
System.out.println("---------------------------here reached inputStream ----------------"+inputStream );
this.ftp.storeFile(uploadDir + fileName, inputStream);
System.out.println("upload completed");
}
catch(Exception e){
}
}
//by siddhu to upload multipart end]



private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
// list the files in a specified directory on the FTP
public boolean listFTPFiles(String directory, String fileName) throws IOException {
// lists files and directories in the current working directory
boolean verificationFilename = false;
FTPFile[] files = ftp.listFiles(directory);
for (FTPFile file : files) {
String details = file.getName();
System.out.println(details);
if(details.equals(fileName))
{
System.out.println("Correct Filename");
verificationFilename=details.equals(fileName);
//assertTrue("Verification Failed: The filename is not updated at the CDN end.",details.equals(fileName));
}
}
return verificationFilename;
}
// Disconnect the connection to FTP
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
}
}
}

}
Image2
Step 3:- Create angularjs 6 application and use following code
1- add-component.component.html
<--div>
<--img [src]="url" height="200" > <--br/>
<--input type='file' #fileInput placeholder="Upload file..." (change)="onSelectFile($event)" accept="image/*">
<--/div>
<--div>
<--button type="button" (click)="upload()">Upload<--/button>
<--/div>

2- add-component.component.ts
getUserImage()
{
console.log("reached here");
this.myService.getUserImage().subscribe(
(data: any) => {
// data = JSON.parse(data['_body']);
console.log('data=====================',data);
this.image_base = data;
},
err => console.log(err), // error
() => console.log('getData Complete') // complete
);
}
// tslint:disable-next-line:member-ordering
@ViewChild('fileInput') fileInput;
upload() {
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
console.log("-----------fileBrowser.files[0]---------"+fileBrowser.files[0].name);
console.log("-----------fileBrowser.files[0].type---------"+fileBrowser.files[0].type);
formData.append("uploadedFile", fileBrowser.files[0]);
formData.append("fileName", fileBrowser.files[0].name);
formData.append("contentType", fileBrowser.files[0].type);
this.myService.upload(formData).subscribe(
(data: any) => {
// do stuff w/my uploaded file
console.log("data=====================",data);
},
err => console.log(err), // error
() => console.log('getData Complete') // complete
);
}
}
3- auth.service.ts
upload(formData) {
const headers = new HttpHeaders();
headers.append("Content-Type", formData.get("contentType"));
//const options = new RequestOptions({headers: headers});
return this.myhttpClient.post('http://localhost:8083/siddhu/upload', formData, { headers: headers });
}
Image3Image4Image5
Step 1:- Start FTP Server
Step 2:- Start Spring Controller
Step 3:- Start AngualarJS
Image6.JPG
Check if image is loaded properly on the FTP.
Image7

Sunday, March 10, 2019

Showing Image file directly from FTP in AngularJS without storing in local drive or serverside

Step 1:- We are using Spring Boot application to exposed Image in the form of Base 64 Byte Array
//by siddhu getting Image from FTP File directly start[
@GetMapping(value = "/siddhu/image")
public @ResponseBody String getImage() throws IOException {
String encodedImage = "";
byte[] res = null;
try{
FTPFunctions ftpobj = new FTPFunctions("localhost", 21, "admin", "admin");
//ftpobj.retriveFTPFile("/uploadftp/siddhuupload.txt");
/*BufferedImage image = new BufferedImage(200, 200, 1);
ImageInputStream iis = ImageIO.createImageInputStream(ftpobj.retriveFTPFile("/uploadftp/siddhu.jpg"));
image = ImageIO.read(iis);*/
//BufferedImage image = new BufferedImage(100, 100, 5);
BufferedImage image = ImageIO.read(ftpobj.retriveFTPFile("/uploadftp/5008255e16468b1f8b1a55abd242db7e.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
res=baos.toByteArray();
encodedImage = Base64.encode(baos.toByteArray());
System.out.println("The encoded image byte array is shown below.Please use this in your webpage image tag.\n"+encodedImage);

}
catch(Exception e) {
e.printStackTrace();
System.out.println("Some problem has occurred. Please try again");
}
return encodedImage;
}
//by siddhu getting Image from FTP file directly end]

Step 2:- In AngularJS side we write one service that will call this controller method
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private myhttpClient : HttpClient) { }

getUserImage() {
return this.myhttpClient.get('http://localhost:8083/siddhu/image',{responseType: 'text'});
}

}

B- At component ts level we write following code
image_base: string;
getUserImage()
{

console.log("reached here");
this.myService.getUserImage().subscribe(
(data: any) => {
//data = JSON.parse(data['_body']);
console.log("data=====================",data);
this.image_base = data;
},
err => console.log(err), // error
() => console.log('getData Complete') // complete
);
}

C- In html level write following line
<--div>
<--img src="data:image/jpeg;base64,{{image_base}}"/>

<--/div>
Note:- If you are getting cross-origin error try to open your chrome browser with below
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Image1
Step 3:- FTP Image expoture code
Image2

1- Start FTP Server
Image3.JPG
2- Start Spring BOOT Application
Image4
3- Start AngularJS6 application
Image5
4- Hit the url and you will be able to see belwo screen

Image6Image7
Note:-
- Please refer to below given url to load the file from local server file system
https://shdhumale.wordpress.com/2019/03/08/how-to-display-image-exposed-as-bytearray-in-angularjs6/
- Refer below url for setting ftp on your local machine.
https://shdhumale.wordpress.com/2018/09/14/how-to-use-apache-ftp-server-for-upload-and-download-file/

Friday, March 08, 2019

How to display image exposed as bytearray in AngularJS6

Step 1:- We are using Spring Boot application to exposed Image in the form of Base 64 Byte Array
@GetMapping(value = "/siddhu/image")
public @ResponseBody String getImage() throws IOException {
String encodedImage = "";
byte[] res = null;
try{
BufferedImage image = ImageIO.read(new File("c:\\to_delete\\5008255e16468b1f8b1a55abd242db7e.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
res=baos.toByteArray();
encodedImage = Base64.encode(baos.toByteArray());
System.out.println("The encoded image byte array is shown below.Please use this in your webpage image tag.\n"+encodedImage);

}
catch(Exception e) {
e.printStackTrace();
System.out.println("Some problem has occurred. Please try again");
}
return encodedImage;
}

Step 2:- In AngularJS side we write one service that will call this controller method
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private myhttpClient : HttpClient) { }

getUserImage() {
return this.myhttpClient.get('http://localhost:8083/siddhu/image',{responseType: 'text'});
}

}

B- At component ts level we write following code
image_base: string;
getUserImage()
{

console.log("reached here");
this.myService.getUserImage().subscribe(
(data: any) => {
//data = JSON.parse(data['_body']);
console.log("data=====================",data);
this.image_base = data;
},
err => console.log(err), // error
() => console.log('getData Complete') // complete
);
}

C- In html level write following line
<--div>
<--img src="data:image/jpeg;base64,{{image_base}}"/>

<--/div>
Note:- If you are getting cross-origin error try to open your chrome browser with below
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Image1Image2Image3Image4Image5Image6Image7

Thursday, February 21, 2019

SSO Circle Integration with our Application War file in Tomcat Web Server.

1- Set up you Spring MVC application. You will get many SpringMVC online example. For quick movement I had taken ready made SpringFormMVC example from here
https://www.journaldev.com/14476/spring-mvc-example
2- Download ready made spring security example provided by Spring for the same. You can download this example from
https://repo.spring.io/list/release/org/springframework/security/extensions/spring-security-saml/
3- Add following line of code in your application pom.xml from step-2 pom.xml to get all the necessary jar required.
'<!-- Add Spring Web and MVC dependencies -->
'<dependencies>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-webmvc'</artifactId>
'<version>3.1.2.RELEASE'</version>
'</dependency>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-web'</artifactId>
'<version>3.1.2.RELEASE'</version>
'</dependency>
'<!-- Servlet -->
'<dependency>
'<groupId>javax.servlet'</groupId>
'<artifactId>servlet-api'</artifactId>
'<version>2.5'</version>
'<scope>provided'</scope>
'</dependency>
'<dependency>
'<groupId>javax.servlet.jsp'</groupId>
'<artifactId>jsp-api'</artifactId>
'<version>2.1'</version>
'<scope>provided'</scope>
'</dependency>
'<dependency>
'<groupId>javax.servlet'</groupId>
'<artifactId>jstl'</artifactId>
'<version>1.2'</version>
'</dependency>


'<dependency>
'<groupId>org.slf4j'</groupId>
'<artifactId>slf4j-log4j12'</artifactId>
'<version>1.6.3'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework.security.extensions'</groupId>
'<artifactId>spring-security-saml2-core'</artifactId>
'<version>1.0.0.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework.security'</groupId>
'<artifactId>spring-security-config'</artifactId>
'<version>3.1.2.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-core'</artifactId>
'<version>3.1.2.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-beans'</artifactId>
'<version>3.1.2.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-context'</artifactId>
'<version>3.1.2.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>
'<dependency>
'<groupId>org.springframework'</groupId>
'<artifactId>spring-aop'</artifactId>
'<version>3.1.2.RELEASE'</version>
'<scope>compile'</scope>
'</dependency>


'<dependency>
'<groupId>javax.servlet'</groupId>
'<artifactId>jsp-api'</artifactId>
'<version>2.0'</version>
'<scope>provided'</scope>
'</dependency>
'<dependency>
'<groupId>junit'</groupId>
'<artifactId>junit'</artifactId>
'<version>4.4'</version>
'<scope>test'</scope>
'</dependency>
'</dependencies>
'<build>
'<plugins>
'<plugin>
'<artifactId>maven-compiler-plugin'</artifactId>
'<version>3.6.1'</version>
'<configuration>
'<source>1.8'</source>
'<target>1.8'</target>
'</configuration>
'</plugin>
'<plugin>
'<artifactId>maven-war-plugin'</artifactId>
'<version>3.0.0'</version>
'<configuration>
'<warSourceDirectory>WebContent'</warSourceDirectory>
'</configuration>
'</plugin>
'</plugins>
'<finalName>${project.artifactId}'</finalName> '<!-- added to remove Version from WAR file -->
'</build>

4- Comment all your code in application web.xml and take entry from step- 2 web.xml of example and add it in your application web.xml
'<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
'<display-name>spring-mvc-example'</display-name>
'<!-- Add Spring MVC DispatcherServlet as front controller -->
'<!-- '<servlet>
'<servlet-name>spring'</servlet-name>
'<servlet-class>
org.springframework.web.servlet.DispatcherServlet
'</servlet-class>
'<init-param>
'<param-name>contextConfigLocation'</param-name>
'<param-value>/WEB-INF/spring-servlet.xml'</param-value>
'</init-param>
'<load-on-startup>1'</load-on-startup>
'</servlet>

'<servlet-mapping>
'<servlet-name>spring'</servlet-name>
'<url-pattern>/'</url-pattern>
'</servlet-mapping> -->


'<context-param>
'<param-name>contextConfigLocation'</param-name>
'<param-value>
/WEB-INF/securityContext.xml
'</param-value>
'</context-param>
'<servlet>
'<servlet-name>saml'</servlet-name>
'<servlet-class>org.springframework.web.servlet.DispatcherServlet'</servlet-class>
'<load-on-startup>1'</load-on-startup>
'</servlet>
'<servlet-mapping>
'<servlet-name>saml'</servlet-name>
'<url-pattern>/saml/web/*'</url-pattern>
'</servlet-mapping>

'<servlet-mapping>
'<servlet-name>saml'</servlet-name>
'<url-pattern>/siddhu/*'</url-pattern>
'</servlet-mapping>
'<filter>
'<filter-name>springSecurityFilterChain'</filter-name>
'<filter-class>org.springframework.web.filter.DelegatingFilterProxy'</filter-class>
'</filter>
'<filter-mapping>
'<filter-name>springSecurityFilterChain'</filter-name>
'<url-pattern>/*'</url-pattern>
'</filter-mapping>
'<listener>
'<listener-class>org.springframework.web.context.ContextLoaderListener'</listener-class>
'</listener>
'<welcome-file-list>
'<welcome-file>/index.jsp'</welcome-file>
'</welcome-file-list>
'<error-page>
'<exception-type>java.lang.Exception'</exception-type>
'<location>/error.jsp'</location>
'</error-page>
'</web-app>
Note: here we had added path url-pattern as /siddhu/* to differentiate our application path.
5- Take complete securityContext.xml of Step-2 application and keep it inside web-inf folder as it is.
6- Take code from your servlet-context.xml and add it in saml.servlet.xml given in next step.
7- Take saml-servlet.xml from step-2 and keep it inside web-inf folder as it is.
Note: depending on your available jsp code please modify bean:property valye in prefix as show below
'<?xml version="1.0" encoding="UTF-8"?>
'<beans:beans
xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
'<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
'<!-- Enables the Spring MVC @Controller programming model -->
'<annotation-driven />
'<context:component-scan
base-package="org.springframework.security.saml.web" />
'<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
'<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
'<!-- '<beans:property name="prefix" value="/WEB-INF/views/" /> '<beans:property
name="suffix" value=".jsp" /> -->
'<beans:property name="prefix" value="/WEB-INF/views/" />
'<beans:property name="suffix" value=".jsp" />
'</beans:bean>
'</beans:beans>
8- Copy all your java file inside saml.web packages
9- Copy security and templates folder from Step-2 example inside your application code.
10- Add index.jsp,error.jsp and logour.jsp from Step-2 inside your application WebContent

Image1

11- Deploy your application on Tomcat
12- Take your application meta data using below url
http://localhost:8282/spring-security-saml2-sample/saml/metadata
and Copy the contents to your clipboard.
you can also take the whole SP Meta data form this site.
https://saml-federation.appspot.com/saml/web/metadata
13- Now we need to tell our IDP that this is the SP from where you will get request for authentification and need to confirm if it is valid. For this we need to add this SP Meta data inside our site :https://idp.ssocircle.com/sso/hos/SelfCare.jsp
Update the metadata of your new profile at https://idp.ssocircle.com/sso/hos/ManageSPMetadata.jsp.
13- click on the Add new service provided option to add our SP details in it.
14- Add proper deatails in FQDN as this need to be unique I prefer to add in the format i.e."urn:test:sppringmvc:pune".
In the below given meta data from SP add whole xml which we had copied in Step 12
Save the change and you will see our SP is added in the site as shown below.

Thats all now lets move for testing our action we did till now
1- Logout of SSO Circle Service site. i.e. https://idp.ssocircle.com/sso/UI/Logout
2- Go to http://localhost:8282/spring-mvc-example/siddhu/home
3- As this is first time login the user will be asked or will be redirected to the SSO Circle login.
4- Login with our SSO Circle credentials which we had done in past.
5- On successful login we will be redirected to your local service provider page and authenticated. i.e. your url will be local host with the details information
Image2Image3Image4Image5Image6

Wednesday, January 30, 2019

SAML implementation using SSOCircle IDP and Spring Security SP example


Step 1:- Frist create your account in SSO Circle site
https://idp.ssocircle.com/sso/UI/Login?gx_charset=UTF-8
image1image2


Step 2:- After successful user creation during login to the ssocircle and check your My Profile
image3

Step 3:- As we did not have any IDP with us i.e. IDP which provide us the authentification. we need to tell the SSO to use itself as our default IDP.
For doing this please fo this url
https://saml-federation.appspot.com/saml/discovery?returnIDParam=idp&entityID=saml-federation.appspot.com
and select the idp which we want
image4
Check on radio button and click on single sign on button
image5image6

click on I'm not a robot and click "continue SAML single sign on" button
You will be diverted to this page

image7image8
Till here we are done with the IDP now lets deal with SP. i.e. SP=Servivce provided our application which will be used by the end user.
Step4:- for now we are using ready made spring security example provided by Spring for the same. You can download this example from
https://repo.spring.io/list/release/org/springframework/security/extensions/spring-security-saml/
Note:- As this is Spring exmaple I prefer to use STS along with Maven and Cradle plugin. Please down load the same from Spring Sites.
Step 5:- Build the above download application using maven plugin.
Step 6:- Please deploy your war file created in Step5 in you local tomcat.
Step 7:- Then download the metadata at http://localhost:8080/spring-security-saml2-sample/saml/metadata.
and Copy the contents to your clipboard.
you can also take the whole SP Meta data form this site.
https://saml-federation.appspot.com/saml/web/metadata
image9
image10
Click on the SP and take the complete SP Metat data
Step5:- Now we need to tell our IDP that this is the SP from where you will get request for authentification and need to confirm if it is valid. For this we need to add this SP Meta data inside our site :https://idp.ssocircle.com/sso/hos/SelfCare.jsp
Update the metadata of your new profile at https://idp.ssocircle.com/sso/hos/ManageSPMetadata.jsp.
image11
click on the Add new service provided option to add our SP details in it.
image12
Add proper deatails in FQDN as this need to be unique I prefer to add in the formate i.e."urn:fortesting:YourName:YourCity".
In the below given meta data from SP add whole xml which we had copied in Step 7 i.e. from this url https://saml-federation.appspot.com/saml/web/metadata
Save the change and you will see our SP is added in the site as shown below.
image13
Thats all now lets move for testing our action we did till now
1- Logout of SSO Circle Service site. i.e. https://idp.ssocircle.com/sso/UI/Logout
2- Go to http://localhost:8080/spring-security-saml2-sample
3- As this is first time login the user will be asked or will be redirected to the SSO Circle login.
4- Login with our SSO Circle credentials which we had done in past.
5- On successful login we will be redirected to your local service provider page and authenticated. i.e. your url will be local host with the details informatoin
image14
chose our IDP and click start single sign on button.
See the url it is local host and when you click on the single sign button it divert us to this IDP site login page https://idp.ssocircle.com/.
image15image16
Enter your credential and click login it will again redirect you to your local host

image17image18

Reference:-
https://docs.spring.io/spring-security-saml/docs/1.0.x/reference/html/chapter-quick-start.html
https://docs.spring.io/spring-security-saml/docs/1.0.x/reference/html/chapter-sample-app.html
https://saml-federation.appspot.com/

Wednesday, January 23, 2019

ReactNative with Genny motion

1- Install Andriod SDK or IDE which comes with SDK https://developer.android.com/studio/
2- Install Genny Motions (When you try to open it will ask for Virtual box) https://www.genymotion.com/
3- Install New Oracle Virtual Box
4- Set the SDK path in Genny Motions i.e. Gennny Motion -->Setting --> ADB. Add the path till sdk of android.
5- Create new virtual machine in Genny Motion i.e. new Virtual Device.
6- Set ANDRIOD_HOME path in environment Variable till andriod sdk.
7- Also Set path in environment variable till andriod sdk.
7- Set path till C:\Users\{USERNAME}\AppData\Local\Android\Sdk\platform-tools
8- Create and React Native app Execute this command in sequence
- Install NPM
- Install Node
- npm install -g expo-cli
- expo init AwesomeProject
cd AwesomeProject
npm start
or
npm run android

Note:- If you are using Genny motion or andriod virtual device make sure to chose Android API greated than 8 API.
Note: - If you get this error Error: Cannot find module '@babel/runtime/helpers/interopRequireDefault'
*** - Solution for above error is :- PS C:\Visual_Source_Code_WorkSpace_ReactNative\AwesomeProject> npm install --save @babel/runtime
Note:- If you run react-native run-android and got this error
> Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-27 Android SDK Platform 27
build-tools;27.0.3 Android SDK Build-Tools 27.0.3
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
*** - Solution :- In SDK manager of android select the respective 27 andriod version.
expo_hostexpo_software_installation_virtualboxgenny_motion_sdk_settinggenny_motion_virtualbox_screenpath_entryvscode