Saturday, September 21, 2013

Connect to facebook Graph API with python

Yes, this type of posts are all over the world wide web. However, there are thousands of methods and not all of them are going to work for you. I've tried to find the easiest way to interact with Graph API and that's what I'm going to describe, along with the problems I've faced throughout the process. I've been using PyDev in Eclipse.

1. Get python-facebook sdk. this seems to be the official one. Install it with this command
sudo pip install git+git://github.com/pythonforfacebook/facebook-sdk.git

2. If you have opened up eclipse before this process, you are going to get an import error. PyDev doesn't refresh the PYTHONPATH automatically. You have to got to

File > Properties > Edit the launch configuration > Refresh tab > Check refresh all resources

3. Now, you would need an access token to interact with the Graph API. Usually this is done with a browser requesting with app id and secret token and then facebook returns an access token. That's a bit tricky, I was looking for an easier method. However, for testing purpose, facebook also gives access tokens directly.
Go to this link : https://developers.facebook.com/tools/explorer and click on generate access token. It shall ask for the permissions you want to have in your application and then generate an access token for you. However, It's temporary and shouldn't be hard coded in your application forever.

4. Paste the following code in your editor. Among tons of others, I've found this one little and easy.
import facebook
token = 'your secret token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

And see the output in console, a nice list of your friends. Remember two points:

  1. If it fails to find 'facebook' module, you might need to restart eclipse.
  2. If it fails to find Graph API, re-install facebook module. You can remove it by issuing
    pip freeze
    to get the actual python-facebook module name and then
    pip uninstall that-module
     

Tuesday, July 2, 2013

Oh My Zsh! for Linux Users

If you use linux and do not use zsh then you are missing something you don't want to miss. Actually I'm grateful to my senior for introducing it to me.

Oh My Zshell is a project for extending and beautifying zshell. Follow that link and don't ever look back to any other shells. :)

For installation and usage:

http://railscasts.com/episodes/308-oh-my-zsh
http://www.stevendobbelaere.be/installing-and-configuring-the-oh-my-zsh-shell/

Screenshot of my current shell, using guake and oh-my-zshell :



Sunday, June 9, 2013

Restore missing "Create New Document" and extend it's functionality in ubuntu 13.04 Nautilus context menu

Hi,

One of the reported bugs of 13.04 is that, the creating blank document menu item is missing in nautilus context menu. It's restoration instruction was found in this link .

You just have to create an empty document inside your Templates folder in home directory and the missing menu item would be restored.

Now you can leverage the templates folder's functionality by adding different types of file schemas. For example you can create files with .txt, .html, .sh, .sql extensions and add appropriate template codes inside. For example, I have these files in this folder with those extensions and with the following contents:

untitled.txt
//nothing

untitled.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <title>Title Goes Here</title>
</head>
<body>
<p>This is my web page</p>
</body>
</html>


bash.sh
#!/bin/bash
//nothing

obsql.sql
CREATE TABLE prefix_table_name
(
  prefix_table_name_id character varying(32) NOT NULL,
  ad_org_id character varying(32) NOT NULL,
  ad_client_id character varying(32) NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby character varying(32) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby character varying(32) NOT NULL,
  
  
  CONSTRAINT prefix_table_name_key PRIMARY KEY (prefix_table_name_id),
  CONSTRAINT prefix_table_name_ad_client FOREIGN KEY (ad_client_id)
      REFERENCES ad_client (ad_client_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT prefix_table_name_ad_org FOREIGN KEY (ad_org_id)
      REFERENCES ad_org (ad_org_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
You can add any number of file types as you want.

Tuesday, June 4, 2013

Regular Commands in Linux

Hi,

Most of the time you may notice that you are having to give some regular commands in terminal when you start working in the morning. For example, in my case-opening up chrome, pgadmin, springsource toolsuite, skype, firefox, guake. Initially I had to click a few shortcuts or enter commands in the terminal. Then I've searched for a quicker and easier way and came up with this:

1. Opened up a text file in gedit/sublime-text.
2. Wrote this line:
#!/bin/bash
guake & /home/anik/ides/springsource/sts-3.1.0.RELEASE/STS & pgadmin3 & firefox & skype
3. Saved it as regularCommands.sh
4. Pasted the file inside /bin folder of the file system.
Then I was able to open up a terminal and just put "regularCommands" without the quotes or even omitting the ".sh" and all those programs were starting up one after another. Saves me time and energy.
Hope that helps. :)


Monday, April 29, 2013

2.1.3 Working with Filters and Servlets

Filters are java classes that can dynamically intercept requests, manipulates them and manipulates response before sending it back to the client.

Sometimes, it may be necessary to do the same thing in different servlets. In those cases, a filter may be defined and reuse it for all of them.

Tasks that a filter can perform includes
  • Authentication Filter
  • Image Conversion 
  • Data Conversion
  • Encryption 
  • Cache

To explain this concept, we shall create a servlet and two filters. Then we would see how can we call the first filter before the servlet is called, then the servlet and lastly the final filter would be called.

Code of servlet:
@WebServlet(name = "helloWorld", urlPatterns = "/helloWorld")
public class helloWorld extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                      response.getWriter().println("This line is from servlet");
    }
}
Then the code of first filter:
@WebFilter(filterName = "HelloAppenderFilter", urlPatterns = "/*")
public class HelloAppenderFilter implements Filter {
    private FilterConfig filterConfig = null;

    public void destroy() {
        filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        resp.getWriter().println("Hello (from filter 1)");
        chain.doFilter(req, resp);


    }

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }

}
Second filter:
@WebFilter(filterName = "WorldAppenderFilter", urlPatterns = "/*")
public class worldAppenderFilter implements Filter {
    private FilterConfig filterConfig;
    public void destroy() {
        filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        chain.doFilter(req, resp);
        resp.getWriter().println("World (from filter 2)");
        

    }

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }

}
If we check the url patterns of the both filters, we shall find no difference. Then how do we control the order of execution of these filters? Well, the answer lies in the web.xml file.
 
        HelloAppenderFilter
        /*
    
    
        WorldAppenderFilter
        /*
    
 

2.1.2 Sessions and Servlets

Purpose of using session is the same as of using cookies. The primary difference is, cookies are stored in client browser where sessions are stored in the server.



Sessions can be managed in four methods
  • Cookies
  • URL rewriting
  • Hidden form fields
  • SSL

Examples of these method would come later. For now, we shall use the servlet api to operate on a very simple session.


@WebServlet(name = "SessionServlet", urlPatterns = "/sessionTest")
public class SessionServlet extends HttpServlet {
    int counter = 0;
       public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out = response.getWriter();
           HttpSession mySession = request.getSession(true);

           synchronized (this){
               out.println(mySession.getId());
               out.println("
You have visited this page "+(++counter));
               out.println((counter == 1) ? "time":"times");
               if(counter % 5  == 0) mySession.invalidate();
           }

           out.close();
    }

}
In this code snippet, the retrieved which was associated with the request object. The boolean true means that a new session would be created if there is none in existence.

Saturday, April 27, 2013

2.1.1 Cookies and Servlets

As Http is a stateless protocol, it doesn't remember client information between request intervals. Each request is new to him. But in some kind of applications like shopping card apps, website tracking, visitor profile generation it is necessary that the server does remember information about the client.

Cookie is small amount of data captured by the server and stored in the client end. Each time the client visits a website, server checks if there is any cookie present in the clients end and then responses accordingly.

  • There are 6 parameters that can be passed to a cookie:
  • The name of the ccookie
  • The value of the cookie
  • The expiration date of the cookie
  • The path the cookie is valid for
  • The domain for a secure connection to exist to use the cookie
Again, there are two types of cookies:
  • Permanent/Persistent Cookies-Cookies are not destroyed after closing the browser.
  • Session/ Transient Cookies-in this case, cookies are destroyed after the browser is closed.

Ok, let's move on to create and retrieve some cookie on our own. We shall create a cookie that accepts user input and remembers it for a specified time. When the client visits the page within this time, the information is shown to him. 

First, let's set the cookie.

@WebServlet(name = "SetCookieServlet", urlPatterns = "/setCookie")
public class SetCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        Cookie songCookie = new Cookie("songCookie", "Welcome to the Hotel California!");
        songCookie.setMaxAge(10);              //in seconds
        response.addCookie(songCookie);       //important! This line actually transfers the cookie to the browser

    }
}

Now, in another servlet, we shall retrieve the cookie value.

@WebServlet(name = "GetCookieServlet", urlPatterns = "/getCookie")
public class GetCookieServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("songCookie")) {
                    out.println(cookie.getValue());
                }
            }
        }

    }
}


Hit the url /setCookie once. This will create the cookie which will be alive for 10 seconds. By this time, hit the url /getCookie. You should see the title of one of my most favorite songs.