Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Thursday, 1 December 2016

Integrating Google+ Social media login with your webpage/website

Elopade.com has a new google+ social media login.

Discussing elopade.com code will be lengthy, so i have come with a simulating  google+ integration with jsp & servlet demo example.

so here we go..

project structure:



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" version="3.0">
  <display-name>socialMediaLogin</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp
-------------------------------------

<!DOCTYPE html>
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
if (session.getAttribute("username") == null) {
%>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>

<form action="LoginServlet" method="post">
UserName: <input type="text" name="user" id = "user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">

<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8080/aSession/oauth2callback&response_type=code&client_id=54353647045-1bj3evf69hq0eop496o5k7lktk1p6rpu.apps.googleusercontent.com&approval_prompt=force">Login With Gmail</a>

</form>
</body>
</html>
<%
} else {
response.sendRedirect("LoginSuccess.jsp");
}
%>


GooglePojo.java
------------------------------------

package com.session;


public class GooglePojo
{
  String id;
  String email;
  boolean verified_email;
  String name;
  String given_name;
  String family_name;

  public String getId()
  {
    return this.id;
  }

  public void setId(String id)
  {
    this.id = id;
  }

  public String getEmail()
  {
    return this.email;
  }

  public void setEmail(String email)
  {
    this.email = email;
  }

  public boolean isVerified_email()
  {
    return this.verified_email;
  }

  public void setVerified_email(boolean verified_email)
  {
    this.verified_email = verified_email;
  }

  public String getName()
  {
    return this.name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  public String getGiven_name()
  {
    return this.given_name;
  }

  public void setGiven_name(String given_name)
  {
    this.given_name = given_name;
  }

  public String getFamily_name()
  {
    return this.family_name;
  }

  public void setFamily_name(String family_name)
  {
    this.family_name = family_name;
  }

  public String toString()
  {
    return
 
      "GooglePojo [id=" + this.id + ", email=" + this.email + ", verified_email=" + this.verified_email + ", name=" + this.name + ", given_name=" + this.given_name + ", family_name=" + this.family_name + "]";
  }
}


GsonUtility.java
----------------------------------

package com.session;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonUtility
{
  static Gson gson = new Gson();
  
  public static String tojson(Object object)
  {
    return gson.toJson(object);
  }
  
  public static String getFbAccessTokenFromJson(String j)
  {
    JsonObject json = (JsonObject)new JsonParser().parse(j);
    JsonObject authr = (JsonObject)json.get("authResponse");
    String act = authr.get("access_token").getAsString();
    return act;
  }
  
  public static String getJsonElementString(String name, String gs)
  {
    try
    {
      JsonObject json = (JsonObject)new JsonParser().parse(gs);
      return json.get(name).getAsString();
    }
    catch (Exception localException) {}
    return null;
  }
  

  public static String getElementString(String string, String line1)
  {
    if (line1.indexOf(string) != -1)
    {
      int k = string.length();
      return line1.substring(k + 1, line1.indexOf("&"));
    }
    return line1;
  }
}


LoginServlet.java
--------------------------------------

package com.session;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "uid";
private final String password = "pwd";

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");

if (userID.equals(user) && password.equals(pwd)) {
HttpSession session = request.getSession(true);
session.setAttribute("username", user);
response.sendRedirect("LoginSuccess.jsp");
} else {
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}

}

}


OAuth2Callback.java
----------------------------------------------------

package com.session;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/oauth2callback")
public class OAuth2Callback extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
try
{
String code = request.getParameter("code");
System.out.println(code);
String urlParameters = "code=" +
code +
"&client_id=" + Setup.CLIENT_ID +
"&client_secret=" + Setup.CLIENT_SECRET +
"&redirect_uri=" + Setup.REDIRECT_URL +
"&grant_type=authorization_code";
System.out.println(urlParameters);
URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line1 = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
line1 = line1 + line;
}
String s = GsonUtility.getJsonElementString("access_token", line1);
url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token=" +
s);
conn = url.openConnection();
line1 = "";
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
line1 = line1 + line;
}
GooglePojo data = (GooglePojo) new Gson().fromJson(line1, GooglePojo.class);
writer.close();
reader.close();
request.setAttribute("auth", data);
session.setAttribute("username", data.getName());
request.getRequestDispatcher("/LoginSuccess.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}



Setup.java
----------------------------------------

package com.session;


public class Setup {
  public static final String CLIENT_ID = "545876977045-1bj3eerere0eop496o5k7lktk1p6rpu.apps.googleusercontent.com";
  public static final String CLIENT_SECRET = "LRdeGc8kerreroUBtS2Oy83";
  public static final String REDIRECT_URL = "http://localhost:8080/aSession/oauth2callback";
}


LoginSuccess.jsp
------------------------------------------

<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
int one = 1;
if ( one == 1) {
// String username = request.getAttribute("username").toString(); 
/* session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty() */
%>
<%@page import="com.session.GooglePojo"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
blahs
</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>

LogoutSuccess.jsp
--------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
if (session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty()) {
String username = session.getAttribute("username").toString();
session.invalidate();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
User <%=username%> Have been Logged Out Successfully.

<br/><a href="index.jsp"><input type="button" value="Login"></a>

</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>

welcome2.jsp
------------------------------

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%
if (session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty()) {
String username = session.getAttribute("username").toString();
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>welcome 2</title>
</head>
<body>
<h3>Hi <%=username %>, Login successful.</h3>
<br>
<a href="LogoutSuccess.jsp"><input type="button" value="Logout"></a>
<footer>
</footer>
</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>


Please note: I have not given my real client id or secre key for this demo. You will have to generate your own secret key and client id for the URL you need to integrate with social media.

You can see how this functionality works with mu current website:elopade.com

Wednesday, 2 September 2015

Building stand-alone and online e-pharma product

So hello there!

Hope you have at-least begun to think that you can program if you want to.

Now, honestly I will not cover the basic basics on my blogs, reason being there are many resources available online, fool-proof and have been published with much research. Get hold of them.
Google as many materials you can.

But what I am trying to do is to build practical applications with you using those basics. What i will do is give you a road-map on how to go through the basics.  


How to go about Basics:
Do you read novels? Like when I was reading The Bible for the first time, i couldnt understand much. So  I read it abstractly for the 1st time and did not try to understand it deeply. But the 2nd time it made more sense because I knew what was coming. Now it makes more sense each time. 

Likewise, in any subject, go through the basics and their examples abstractly – 1 full cycle of contents. Then get deeper on your 2nd read and so forth.


PRODUCT GOAL: We are going to make “e-pharma” system . This system will capture all vital business transactions of an independent pharmacy. When I say independent pharmacy, I am talking about a  pharmacy which is not a sub-unit of any hospital and where you don’t need to register yourself as any patient to get medicines but you can simply buy them on legitimate medical prescriptions.


PRODUCT TYPES:
1.      Stand-alone e-pharma
2.      Online e-pharma

Stand-alone e-pharma: 
In Stand-alone applications you have database on your own personal system, your system acts like server and client. (Please see my post on simple java app, to understand server and client architecture, also google other resources too to understand it).

In standalone system, your database (tables, information) , is stored in your own system. All the Screens to store information are run on your personal PC without internet.

We will use Swing, JDBC and MySQL to build standalone.


Web/Online e-pharma: Here all your information is not necessarily stored on your personal system, it could be stored on a remote server and you could be calling them through your personal system, like online booking.

We will use Servlets, JDBC, java, JSP, Spring, Hibernate to build online e-pharma.


Helpful links to learn the basics of these languages:

JAVA:


Apart from them, I personally really like Java for Students by Ajay Pherwani. You don’t have to be a student to buy this book neither feel that you are too old to read it. I personally used this book to start with java and now use it time and again to brush up my basics.


MySQL and RDBMS


Google and download different PDFs and PPTs to understand RDBMS, (Relational Database Management System).

Like wise google as many. I  personally use the book “The Complete Reference MySQL” .


JSP (Java Server Pages)

Google as many links as you can.
Book - Complete Reference, TATA McGraw Hill.

----------------------------------------------------------------------------
Make a plan and go through them abstractly for 1st time. Don’t get discouraged if you don’t understand. I personally did not understand them for first time even though I am an IT graduate. So don’t get discouraged, but practice and get deeper each time you read and practice them.

ROAD MAP to building e-pharma:

Database Designing is common for stand-alone and web e-pharma, so we will use 1 database for both the systems.
So our 1st step would be to design Database for e-pharma.
And the second step, would be to create screens for both – stand-alone and web e-pharma.

So get yourself prepared to build a real system. My next blog is on e-pharma database designing. We will be creating an RDBMS (which you will find out if you go through the tutorials I have recommended or else google it).
Following database design, will be designing transaction and Master screens (I will explain the difference in upcoming blogs).

Thankyou.