Many websites are using blurred images in background. If you want to highlight part of the image, what will you do ? Maybe drawing some shape on the image with red marker. We can do this with SVG filter and mask components. UnBlurring the part of completely blurred image will give better and clean attention.
Please have look at below code.
<svg class="blur" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" width="750" height="498">
      <!-- Image that was blurred and half brightend -->      
      <image filter="url(#filter2)" xlink:href="https://lh3.googleusercontent.com/-zJ3ijSNpElc/VyGE80Uo5PI/AAAAAAAADk4/w2cGycz0gIoGz5HDci02WU70uXqJnhYAgCCo/s912/inNature.JPG" width="100%" height="100%"></image>
      <!-- filter to control blur and brightness -->      
      <filter id="filter2">        
        <!-- standard deviation to control blur -->
        <feGaussianBlur stdDeviation="7"></feGaussianBlur>
        <!-- standard deviation to control brightness -->         
        <feComponentTransfer>          
          <feFuncR  type="linear" slope="0.5"></feFuncR>
          <feFuncG type="linear" slope="0.5"></feFuncG>          
          <feFuncB type="linear" slope="0.5"></feFuncB>          
        </feComponentTransfer>      
      </filter>      
      <!-- mask to unblur the part of the image -->
      <mask id="mask1">       
        <circle cx="177" cy="166" r="150" fill="white" style="opacity: 1;"></circle>
      </mask>       
      <!-- image to show unblurred image part -->
      <image xlink:href="https://lh3.googleusercontent.com/-zJ3ijSNpElc/VyGE80Uo5PI/AAAAAAAADk4/w2cGycz0gIoGz5HDci02WU70uXqJnhYAgCCo/s912/inNature.JPG"
        width="100%" height="100%" mask="url(#mask1)"></image>    
</svg>
filter2 controls blur and brightness of the image. mask1 shows only specified part of the image. stdDevation attribute value represents the level of blur, If you want increase the blur effect, just increase stdDevation value. slope attribute value of feFunc effects the brightness of the image, this value should be in between 0 and 1. Decrease slope value to get darken blurred image in the background.  
Read More
Github is providing OAuth Service. You can implement Github Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Github Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Register App on Github

You can find detail OAuth2 flow on github developers page. First you need to create app in github developer account

Register App On Github

Click here to register you app. Enter required details in the shown form. Here I have registered demo app with name "SodhanaLibrary Demos". You can find sample details in below image.
Don't make "Client Secret Id" public.  Remaining details can be exposed to user

Prepare Login URL

Now you have to provide one URL for user to login with github. That URL should contain client id, redirect url, scope as parameters. Find below for sample URL for sodhanalibrary demo app
https://github.com/login/oauth/authorize?client_id=5338cfe15cb812789cf8&redirect_uri=http://demo.sodhanalibrary.com/oauth2git&scope=user
client_id - Provide your app client id
redirect_uri - Provide your app redirect url
scope - Scope is based on required details of user. Click here to find different scopes
state - It is unguessable string to avoid cross site forgery request attacks. It is optional

Get Access Token

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language.

Get Code value and format URL

Observe below URL. Highlighted words has to be replaced with  your own app details
String code = request.getParameter("code");
URL url = new URL("https://github.com/login/oauth/access_token?client_id="+clientID + "&redirect_uri="+ redirectURI+ "&client_secret=" + clientSecret + "&code=" + code);

Send request for Access Token

URL url = new URL(
        "https://github.com/login/oauth/access_token?client_id="
                + clientID + "&redirect_uri=" + redirectURI
                + "&client_secret=" + clientSecret + "&code=" +
                code);
HttpURLConnection conn = (HttpURLConnection) url
        .openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
String outputString = "";
BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
    outputString = outputString + line;
}
System.out.println(outputString);
String accessToken = null;
if (outputString.indexOf("access_token") != -1) {
    accessToken = outputString.substring(13,
            outputString.indexOf("&"));
}
System.out.println(accessToken);

Get User Details From Acces Token

url = new URL("https://api.github.com/user");
System.out.println(url);

HttpURLConnection myURLConnection = (HttpURLConnection) url
        .openConnection();
myURLConnection.setRequestProperty("Authorization", "token "
        + accessToken);
myURLConnection.setRequestProperty("User-Agent", appName);
myURLConnection.setRequestMethod("GET");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setConnectTimeout(7000);

outputString = "";
reader = new BufferedReader(new InputStreamReader(
        myURLConnection.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString = outputString + line;
}
reader.close();
System.out.println(outputString);
GithubPojo gp = (GithubPojo) new Gson().fromJson(outputString,
        GithubPojo.class);
System.out.println(gp);

Download project

Click here to download project. All code snippets available in this project. Open OAuth2Git.java, and give your github app details over there

Read More
Reddit voting consists of up voting  and down voting. These votes decide rank of the post, which ultimately decides the position of the story link. Here in this article, we are going to see simple architecture and database structure to implement reddit voting system. 

Note 

It is really big project. Its difficult to explain every code snippet here. So please download the project

Database

Lets build database first. Click here to read complete explanation on reddit database. Execute below SQL commands on your MySQL console

CREATE schema demos;

CREATE TABLE reddit_post
(parent_id BIGINT(20) NOT NULL,post_id BIGINT(20) AUTO_INCREMENT,
  title varchar(200) NOT NULL,
  content varchar(2000) NOT NULL,
  link varchar(2083) NOT NULL,
  user_id varchar(25) NOT NULL,
  pic varchar(2083),
  status varchar(15) NOT NULL,
  type varchar(15) NOT NULL,
  votes INTEGER,
  created_time TIMESTAMP default CURRENT_TIMESTAMP,
  primary key(post_id)
);


CREATE TABLE reddit_votes
(
  post_id BIGINT(20) NOT NULL,
  user_id VARCHAR(25) NOT NULL,
  vflag SMALLINT NOT NULL,
  last_updated_time TIMESTAMP default CURRENT_TIMESTAMP,
  primary key(post_id,user_id),
  foreign key(post_id) references reddit_post(post_id)
);

CREATE TABLE reddit_user
(
  user_id VARCHAR(25),
  property VARCHAR(25) NOT NULL,
  value varchar(200) NOT NULL,
  last_updated_time TIMESTAMP default CURRENT_TIMESTAMP,
  primary key(user_id,property,value)
);

CREATE TABLE reddit_ranks
(
  post_id BIGINT(20) NOT NULL,
  hot double,
  new double,
  raising double,
  controversial double,
  top double,
  foreign key(post_id) references reddit_post(post_id)
);

CREATE TABLE reddit_rights
(
  post_id BIGINT(20) NOT NULL,
  property VARCHAR(25),
  user_id VARCHAR(25),
  assigned_user_id VARCHAR(25),
  foreign key(post_id) references reddit_post(post_id),
  foreign key(user_id) references reddit_user(user_id),
  foreign key(assigned_user_id) references reddit_user(user_id)
);

INSERT INTO reddit_user(user_id, property, value) values('admin','name', 'admin');
INSERT INTO reddit_user(user_id, property, value) values('srinivas','name', 'srinivas dasari');
INSERT INTO reddit_user(user_id, property, value) values('ramesh','name', 'ramesh');

INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(0,'java','sub reddit for java developers','/r/java','admin','java_subreddit.png', 'active', 'subreddit', 0);
INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(0,'angularjs','sub reddit for AngularJS developers','/r/angularjs','admin','angularjs_subreddit.png', 'active', 'subreddit', 0);
INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(0,'sql','sub reddit for sql developers','/r/sql','admin','sql_subreddit.png', 'active', 'subreddit', 0);

INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(1,'Java Restful Webservice Tutorial with Sample case study','','http://blog.sodhanalibrary.com/2013/09/restful-web-service-tutorial-with-java.html','srinivas','http://4.bp.blogspot.com/-IWnld2WXOCg/UinxJK9ahMI/AAAAAAAAAAw/b8mFC6bl41w/s1600/screen2.bmp', 'active', 'post', 1);
INSERT INTO reddit_votes(post_id, user_id, vflag) VALUES(LAST_INSERT_ID(),'srinivas',1);

INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(2,'Responsive Web Design Using AngularJS Material UI','','http://blog.sodhanalibrary.com/2015/08/responsive-web-design-using-angularjs.html','srinivas','',  'active', 'post', 1);
INSERT INTO reddit_votes(post_id, user_id, vflag) VALUES(LAST_INSERT_ID(),'srinivas',1);

INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(2,'Responsive Web Design Using AngularJS Material UI','','http://blog.sodhanalibrary.com/2015/08/responsive-web-design-using-angularjs.html','srinivas','',  'active', 'post', 1);
INSERT INTO reddit_votes(post_id, user_id, vflag) VALUES(LAST_INSERT_ID(),'srinivas',1);

INSERT INTO reddit_post(parent_id, title, content, link, user_id, pic, status, type, votes) VALUES(4,'','good one','/r/java/4/comments','ramesh','','active', 'comment', 1);
INSERT INTO reddit_votes(post_id, user_id, vflag) VALUES(LAST_INSERT_ID(),'srinivas',1);

Program Flow

Here we will see what are basic rules to implement this functionality
(In the given demo, the default user id is "admin", No authentication required)

Load posts

Send request from jQuery to server, Server will send details by digging database. Find below for database queries

Select only post data from reddit_posts
select * from reddit_post where TYPE = 'post'
Select user vote for post
select * from reddit_votes where POST_ID = ? and USER_ID = ?
Now display the given data to user using jQuery

User Voting

Whenever user clicks on up arrow or down arrow, That user vote either is to be inserted or updated in reddit_votes. Total votes in reddit_posts has to be updated

Query for inserting vote into reddit_votes
insert into reddit_votes (POST_ID,USER_ID,VFLAG) values (?,?,?)
Query for updating vote in reddit_votes
update reddit_votes set VFLAG=?,LAST_UPDATED_TIME=CURRENT_TIMESTAMP where POST_ID=? and USER_ID=?
Query for deleting vote ( User can withdraw his vote )
delete from reddit_votes where POST_ID = ? and USER_ID = ?
Query for updating total votes
update reddit_post set VOTES = (select sum(vflag) from reddit_votes where POST_ID = ?) where POST_ID = ?

jQuery Code

Find below for jQuery code, It will handle up voting and down voting. 
$.get( "GetRedditPosts", function( rdata ) {
    var jsondata = JSON.parse(rdata);
    var html = '';
    if(jsondata.result_code == -1) {
        alert(jsondata.error_message);
        return;
    }
    var data = jsondata.data;
    // display this data as html
    

        // click event action for up arrow button
    $(".upArrow, .upArrowActive").on('click', function(){
        // update the post with new votes count
    });
    
    $(".downArrow, .downArrowActive").on('click', function(){
                // update the post with new votes count               
    });
});

Java Code

There are 2 main servlet classes, VotePost and GetRedditPosts
GetRedditPosts servlet is for loading posts
@WebServlet("/GetRedditPosts")
public class GetRedditPosts extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result = new Result();
        try { 
            // select posts from database
            ArrayList<RedditPost> posts = RedditPostDAO.selectRedditPost("admin");
            result.setData(posts);
        } catch (DBException e) {
            result.setResult_code(-1);
            result.setError_msg("Database error");
        }  catch (Exception e) {
            result.setResult_code(-1);
            result.setError_msg(e.getMessage());
        }
        PrintWriter pw = response.getWriter();
        pw.write(CodeUtils.toJson(result));
        pw.flush();
    }
}
VotePost servlet is for insert, update, delete user vote 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Result result = new Result();
    try {
        RedditVotes rv = new RedditVotes();
        
        // id of the post
        rv.setPOST_ID(Integer.parseInt(request.getParameter("post_id")));
        
        // this is user vote (+1 is for up vote and -1 is for down vote) 
        rv.setVFLAG(Integer.parseInt(request.getParameter("vflag")));
        
        // this decides whether user want to withdraw his vote, 0 is for updating or inserting, other than 0 is for deleting vote
        rv.setREMOVE_FLAG(Integer.parseInt(request.getParameter("rflag")));
        
        // defaul userid for test
        rv.setUSER_ID("admin");
        
        if(rv.getREMOVE_FLAG() == 0) {
            // insert or update user vote
            RedditVotesDAO.insertRow(rv);
        } else {
            // delete user vote
            RedditVotesDAO.deleteRow(rv);
        }
        result.setData(RedditPostDAO.selectRedditPost(rv.getPOST_ID(),rv.getUSER_ID()));
    } catch (DBException e) {
        result.setResult_code(-1);
        result.setError_msg("Database error");
    }  catch (Exception e) {
        result.setResult_code(-1);
        result.setError_msg(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(CodeUtils.toJson(result));
    pw.flush();
}
Read More
GIF images consists of many frames, so size of GIF image is more as compared to normal image. Its not recommended to load GIF images first and its better to maintain one normal preview image for every GIF image. You can use first frame of GIF image as preview image. Click here to see my on-line tool for generating first frame of GIF image

How Facebook Handles GIF images

Facebook is not loading GIF images directly. Its converting user uploaded GIF images into simple video format. Find below inspected source code
Here We are not following facebook way of dealing GIF images. We are just loading GIF images
on user's interest

angGifPreview

I have created this angGifPreview AngularJS directive to create Facebook like GIF Preview.  You can find it on github

Implementaion

Add AngularJS

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

Add CSS and JS files

angGifPreview specific CSS and JS files
<link rel="stylesheet" href="angGifPreview/angGifPreview.css" />
<script src="angGifPreview/angGifPreview.js"></script>

HTML Markup

Find below for HTML markup. gif-preview element tag has 2 attributes 
gif : gif image path
preview : gif preview image path
<gif-preview preview="previewImage" gif="gifImage"></gif-preview>

JS CODE

import gifPreview module as like shown in below code
(function(angular) {
    'use strict';
    angular.module('sampleExample', ['gifPreview'])
      .controller('Controller', ['$scope', function($scope) {
          $scope.previewImage = 'sample_first_frame.png';
          $scope.gifImage = 'sample_giphy.gif';
    }]);
})(window.angular);
Read More
GIF images consists of many frames, so size of GIF image is more as compared to normal image. Its not recommended to load GIF images first and its better to maintain one normal preview image for every GIF image. You can use first frame of GIF image as preview image. Click here to see my on-line tool for generating first frame of GIF image

How Facebook Handles GIF images

Facebook is not loading GIF images directly. Its converting user uploaded GIF images into simple video format. Find below inspected source code
Here We are not following facebook way of dealing GIF images. We are just loading GIF images
on user's interest

jqGifPreview

I have created this plugin, you can find it on github. Lets see how to use this plugin

Add jQuery

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>

Add CSS and JS of jqGifPreview

<link rel="stylesheet" href="jqGifPreview/jqGifPreview.css" />
<script src="jqGifPreview/jqGifPreview.js"></script>

HTML markup

data-gif : gif image path
src : gif preview image path
<img class="myImg" src="sample_first_frame.png" data-gif="sample_giphy.gif" />

JS Code

$(function() {
    $(".myImg").jqGifPreview();
});
Read More
Many blogs have implemented this emotion voting feature. We can make use of this data for emotion intelligence and can make user interaction more. Observe below image, Here you can observe 5 type of emotions. Whenever user clicks particular emotion button, the data will go to server and will be stored in MySQL database

Database structure

Here, I am using MySQL database. I have created a table named votes under demos schema. Find below for table structure
ipaddress - This is client ipaddress ( this is just for record)
fingerprint - This is generated at client system to identify computer uniquely
article - This is the article URL
vote_cat -This is the voting category (exceted, happy, angry .... etc)
created -This is generated at client system to identify computer uniquely

Table Create Statement

Find below for table create statement
CREATE TABLE `votes` (
  `ipaddress` varchar(15) DEFAULT NULL,
  `fingerprint` varchar(100) NOT NULL DEFAULT '',
  `article` varchar(200) NOT NULL DEFAULT '',
  `vote_cat` varchar(20) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`fingerprint`,`article`)
)

Fingerprint Generation

Fingerprint is to identify user's computer uniquely. This can be generated using jQuery plugin fingerprint2.js
new Fingerprint2().get(function(result, components){
  console.log(result); //a hash, representing your device fingerprint
  console.log(components); // an array of FP components
});

Program Flow

Find below image for program flow

jQuery Code

Here you can observe posting user's action and getting article info
$(function(){
    $(".emotion").click(function(){
        var btn = $(this);
        new Fingerprint2().get(function(result, components){
            $.post( "VotePost", { fingerprint:result,voteCatogory:$(btn).attr("voteCatogory"), article:location.href }).done(function( data ) {
                // update article info
            });   
        });
    });
    
    new Fingerprint2().get(function(result, components){
        $.get( "GetVotesCount", { fingerprint:result,article:location.href }).done(function( data ) {
            // get article info
        });   
    });
});

Java Code

You need to download the project to see whole java code. Here I will explain only servlet code

VotePost servlet post method

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Result result = new Result();
    try {
        // get required details from client
        String voteCatogory = request.getParameter(Constants.VOTE_CATOGORY);
        String post = request.getParameter(Constants.ARTICLE);
        String fingerprint =  request.getParameter(Constants.FINGERPRINT);
        String ipAddress = request.getHeader("X-FORWARDED-FOR");  
        if (ipAddress == null) {  
          ipAddress = request.getRemoteAddr();  
        }
        
        // insert user vote into database
        VotePojo votes = new VotePojo();
        votes.setARTICLE(post);
        votes.setFINGERPRINT(fingerprint);
        votes.setVOTE_CAT(voteCatogory);
        votes.setIPADDRESS(ipAddress);
        VotesDAO.insertRow(votes);
        
        // send article info back to client
        result.setData(VotesDAO.selectArticle(post));
    } catch (DBException e) {
        result.setResult_code(-1);
        result.setError_msg("Database error");
    }  catch (Exception e) {
        result.setResult_code(-1);
        result.setError_msg(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(CodeUtils.toJson(result));
    pw.flush();
}

GetVotesCount Servlet get method

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Result result = new Result();
    try {
        // Get Article Information
        String postid = request.getParameter(Constants.ARTICLE);
        String fingerprint = request.getParameter(Constants.FINGERPRINT);
        ArticleInfo post = VotesDAO.selectArticle(postid);
        
        // Get article vote on user's computer
        VotePojo votes = VotesDAO.selectVote(postid, fingerprint);
        
        // add user article vote info to article info
        post.setVotes(votes);
        result.setData(post);
    } catch (DBException e) {
        result.setResult_code(-1);
        result.setError_msg("Database error");
    } catch (Exception e) {
        result.setResult_code(-1);
        result.setError_msg(e.getMessage());
    } 
    PrintWriter pw = response.getWriter();
    pw.write(CodeUtils.toJson(result));
    pw.flush();
}

Read More
AngularJS Material UI is not providing any Accordion functionality script. So here I made some accordion with UI elements provided in Material UI.

Accordion

Accordion is consists of headers and content. Observe above image. HOLDEN, FORD, TOYOTA are headers here. Whenever user clicks on plus icon, the content will be displayed and plus icon will be minus. Observe below JSON of header and body data.
JSON data
$scope.accordianData = [
        {
            "heading" : "HOLDEN",
            "content" : "GM Holden Ltd, commonly known as Holden, is an Australian automaker that operates in Australasia and is headquartered in Port Melbourne, Victoria. The company was founded in 1856 as a saddlery manufacturer in South Australia."
        },
        {
            "heading" : "FORD",
            "content" : "The Ford Motor Company (commonly referred to as simply Ford) is an American multinational automaker headquartered in Dearborn, Michigan, a suburb of Detroit. It was founded by Henry Ford and incorporated on June 16, 1903."
        },
        {
            "heading" : "TOYOTA",
            "content" : "Toyota Motor Corporation is a Japanese automotive manufacturer which was founded by Kiichiro Toyoda in 1937 as a spinoff from his father's company Toyota Industries, which is currently headquartered in Toyota, Aichi Prefecture, Japan."
        }
    ];

Markup

Here data.expanded variable which makes Accordion collapse and expand. Whenever user clicks on it, this variable will be toggled
<div class="md-accordion" ng-repeat="data in accordianData">
    <md-toolbar ng-init="data.expanded = false" ng-click="data.expanded = !data.expanded">
        <div class="md-toolbar-tools">
            <h2>
                <span>{{data.heading}}</span>
            </h2>
            <span flex=""></span>
            <span ng-class="{expandCollapse:true, active:data.expanded}"></span> 
        </div>
    </md-toolbar>
    <div ng-class="{dataContent:true, activeContent:data.expanded}">{{data.content}}</div>
<div>
The above demo will collapse and expand only that particular div. What we have to do, collapse all other div, when user clicks on item ?. Here is the solution

Markup

When use clicks on particular item here it will collapse all expand that item
<div class="md-accordion" ng-repeat="data in accordianData">
    <md-toolbar ng-init="data.expanded = false" ng-click="collapseAll(data)">
        <div class="md-toolbar-tools">
            <h2>
                <span>{{data.heading}}</span>
            </h2>
            <span flex=""></span>
            <span ng-class="{expandCollapse:true, active:data.expanded}"></span> 
        </div>
    </md-toolbar>
    <div ng-class="{dataContent:true, activeContent:data.expanded}">{{data.content}}</div>
<div>
Function
$scope.collapseAll = function(data) {
   for(var i in $scope.accordianData) {
       if($scope.accordianData[i] != data) {
           $scope.accordianData[i].expanded = false;   
       }
   }
   data.expanded = !data.expanded;
};
Read More

Blogroll

Follow this blog by Email

Popular Posts