Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts
HTML5 web sockets provides stable connectivity to servers. By using these web sockets we can setup a stable connection between browser and sever, and then we can send or receive messages.

Like shown in below image, users send and receive messages on real time


Observe below GIF, One is chrome and another is firefox, Whatever we type in chrome, that will be displayed in firefox.

Lets write java program for sharing editor

Java Program

To run below program, you need add java_websocket dependency. Here it is the maven dependency xml.
<dependency>
  <groupId>org.java-websocket</groupId>
  <artifactId>Java-WebSocket</artifactId>
  <version>1.3.0</version>
</dependency>

Once you install the above dependencies, run below program
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class App extends WebSocketServer {

    private static int TCP_PORT = 4444;
    private String value = "";

    private Set<WebSocket> conns;

    public App() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<WebSocket>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        conn.send(value);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        value = message;
        for (WebSocket sock : conns) {
            sock.send(message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }
    
    public static void main(String[] args) {
        new App().start();
    }
}

HTML Code 

This code contains textarea element. Whatever user types in that textarea, it will be sent to java web socket server. Java server will send that message to all its connections. That is how one user's text will be shown to all users. 
<!DOCTYPE html>
<html>
    <head>
    <style>
        .layout {
            width:800px;
            margin:auto;
        }
        
        textarea {
            max-width:800px;
            width:80%;
            border:1px solid #ccc;
            font-size:14px;
            height:400px;
        }
    </style>
    <script>
        var ws = new WebSocket("ws://127.0.0.1:4444/");
        var elm = document.getElementById('myTextArea');
    
        ws.onopen = function() {
            console.log("Opened!");
        };
    
        ws.onmessage = function (evt) {
            myTextArea.value = evt.data;
        };
    
        ws.onclose = function() {
            alert("Closed!");
        };
    
        ws.onerror = function(err) {
            alert("Error: " + err);
        };
    
        function share(event) {
            ws.send(event.target.value);
        }
    </script>
    </head>
    <body>
       <div class="layout">
        <h1>Sharing editor</h1> 
        <textarea id="myTextArea" onkeyup="share(event)" rows="100" cols="50"></textarea>
       </div>
    </body>
</html>
Read More
This is continuation of article Login With Twitter Using Java. By using Twitter OAuth features, If you want to update status of user from your java web application, This article will help you. Suppose if you create a news sharing website, Your website will get more traffic if users share those news on their twitter's timeline. They can do that directly from your application if they given access to your application. Twitter is having java library twitter4j to access twitter services. Download twitter4j and add those jars to WEB-INF folder.
---   Click here to see demo  ---  Download eclipse code ---

Project

I have provided sample project here, download it. Open Setup.java and give your twitter app credentials, database credentials. Create MySQL database schema with name "demos". Created below specified table. Import this project into Eclipse, add it to tomcat server, run index.html

There are 2 types of Update Status features are there.  
  1. Update status to your own profile using access token and access token secret which were generated manually
  2. Update status on user's timeline using oauth access token and access token secret that were saved in database

Process - Oauth Status Update

  1. Register your application in twitter developers page
  2. Provide access link to user ( Generate link using Twitter4j ) 
  3. User will be redirected to twitter access page. User will give permission to application
  4. Access token will be sent to Callback URL
  5. Get access token and store it in database
  6. Whenever you want to update status on user's timeline, get access token from access token secret from database and update status using them
   // configure twitter object with consumer key and consumer secret 
   ConfigurationBuilder cb = new ConfigurationBuilder();
   cb.setDebugEnabled(true)
     .setOAuthConsumerKey(Setup.CONSUMER_KEY)
     .setOAuthConsumerSecret(Setup.CONSUMER_SECRET); 
   TwitterFactory tf = new TwitterFactory(cb.build());
   Twitter twitter = tf.getInstance();
   
   // get user details from by user id
   UserPojo user = TwitterDAO.selectUser(4);
   // set access token and access token secret and user id
   AccessToken accessToken1 = new AccessToken(user.getAccess_token(), user.getAccess_token_secret(), user.getTwitter_User_id());
   twitter.setOAuthAccessToken(accessToken1);
   
   // update status from
   twitter.updateStatus("Sample tweet from standalone java");

Process - Status Update To Your Own Profile

If you want to update status to your own profile, you can do it with default access token and access token secret. Observe below screenshot.  
Build AccessToken object with above access token and access token secret and user id. Update status as like above
Read More
If you implement "Login With Twitter" for your website, users don't need to remember  password for your website, so users will feel comfortable to use your website. In advance, you can access users  timeline feed. Twitter is providing Twitter4J to implement twitter api using java, download this twitter4j and add it to build path

Project

I have provided sample project here, download it. Open Setup.java and give your twitter app credentials, database credentials. Create MySQL database schema with name "demos". Created below specified table. Import this project into Eclipse, add it to tomcat server, run index.html

Implementation

  1. When user click on Login with twitter button, Provide them access link which is generated by Twitter4j with your app credentials. 
  2. User will be redirected to twitter api page
  3. Once user gives permission, access token and oauth verifier will be sent to callback URL
  4. Now verify the access token with oauth verifier. It will generate access token object which will have access token and access token secret 
  5. Now save access token and access token secret in database with user details like twitter user id and screen name.
User cant change their twitter user id, so we can use this to identify user. If user login again, we can process user's account using twitter user id. Whenever you want to update status on user's timeline, you can do with these saved access tokens.

Create App In Twitter Developer Page

Open twitter apps webpage.  Create your app and get Consumer Key and Consumer Secret Key. Observe below diagram.

Database Table

Created database table like below.

CREATE TABLE `demos`.`twitter_user` (
  `user_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `twitter_user_id` INT NULL COMMENT '',
  `screen_name` VARCHAR(45) NULL COMMENT '',
  `access_token` VARCHAR(100) NULL COMMENT '',
  `access_token_secret` VARCHAR(100) NULL COMMENT '',
  `created_date` DATETIME NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
  PRIMARY KEY (`user_id`)  COMMENT '',
  UNIQUE INDEX `twitter_user_id_UNIQUE` (`twitter_user_id` ASC)  COMMENT '');

Prepare Signin Link

Observe below code. Configure twitter object with Consumer Key and Secret Key, Generate request token with callback URL, save it to session. Generate authentication URL and redirect to that URL
// configure twitter api with consumer key and secret key
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey(Setup.CONSUMER_KEY)
  .setOAuthConsumerSecret(Setup.CONSUMER_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
request.getSession().setAttribute("twitter", twitter);
try {
    
    // setup callback URL
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/callback");

    // get request object and save to session
    RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
    request.getSession().setAttribute("requestToken", requestToken);
    
    // redirect to twitter authentication URL
    response.sendRedirect(requestToken.getAuthenticationURL());

} catch (TwitterException e) {
    throw new ServletException(e);
}

Callback Servlet

Callback servlet will receive oauth_verifier parameter. Verify access token with that verification code, then you will get access token object, Now save or update access token or access token secret to database. Here we identify user with twitter user id that is always constant. TwitterDAO.selectTwitterUser method gives user object based on twitter user id.
// Get twitter object from session
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
//Get twitter request token object from session
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
String verifier = request.getParameter("oauth_verifier");
try {
    // Get twitter access token object by verifying request token 
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
    request.getSession().removeAttribute("requestToken");
    
    // Get user object from database with twitter user id
    UserPojo user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    if(user == null) {
       // if user is null, create new user with given twitter details 
       user = new UserPojo();
       user.setTwitter_user_id(accessToken.getUserId());
       user.setTwitter_screen_name(accessToken.getScreenName());
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.insertRow(user);
       user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    } else {
       // if user already there in database, update access token
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.updateAccessToken(user);
    }
    request.setAttribute("user", user);
} catch (TwitterException | DBException e) {
    throw new ServletException(e);
} 
request.getRequestDispatcher("/status.jsp").forward(request, response);

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','https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnrg6ZTRjpbd0UHrIuAKy7JA9SuvA4lTGcZyDR2r9S3VPovZc9ihg6figFEWY86ItsfKnM78JbtSXtduMX4zW3N-Hjue0BOpCviVxCYeH0GHIMx99-BNXr8foQ1Ayzn44_ERS2fCo8i04/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
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

Blogroll

Popular Posts