View Facebook API Code

Before going to proceed further, following liberary must be available in your class path,
  • activation-1.1.jar
  • commons-lang-2.2.jar
  • commons-logging-1.1.1.jar
  • facebook-java-api-3.0.2.jar
  • facebook-java-api-annotation-processor-3.0.2.jar
  • facebook-java-api-schema-3.0.2.jar
  • jaxb-api-2.1.jar
  • jaxb-impl-2.1.9.jar
  • json-20080701.jar
  • restfb-1.6.12.jar
  • runtime-0.4.1.5.jar
  • stax-api-1.0-2.jar
We are using following two API to communicate with Facebook.
  1. Facebook API
  2. RestFB API
Create logging.properties file under src directory in your project. 

logging.properties 
create new servlet file which handles incoming and outgoing request from our application. We required only file to handle all the request. No need to worry about rest of the thing right now, just enjoy programming to integrate Facebook API. 

MainServlet.java  As you can see from the code, when the servlet called first time at that time code was null so it comes under the else part and redirect to facebook to validate their credential. 

once facebook gets approved it will return back with either code or token, depend upon our configuration.We have provided redirect_uri parameter to facebook to indicate that response came from facebook will be proceed by this servlet. 

in our case both servlet are same. Means we are using the same servlet to send a request to facebook and proceed response from facebook. Once we received code/token, one can send a request to get an access token of your application, Access token play very important role for communicating. 

Note : I have changed my API_KEY & SECRET_KEY so you can changed with yours. If you don't know how to get API & Secret key then visit this post Steps to FBI API. Before going to start with Facebook integration, Please refer documentation first that would be easy to understand code as well as flow.

posted under , | 1 Comments

Step by Step guide to integrate Facebook API using java

In this section, I will provide you step by step guide to integrate Facebook API using java. It would be very easy to implement Facebook API  but for that we need to follow certain steps in proper sequence.

Step 1  :  Create account on Facebook website. http://facebook.com/
Step 2  :  Login into your account on Facebook.
Step 3  :  Now go to following URL : https://developers.facebook.com
Step 4  :  You will find app tab in top menu, click to continue or directly go to following URL https://developers.facebook.com/apps  
Step 5  :  Now click on create new App.
Step 6  : This will open new model dialog box and ask you for app name. Please provide unique application name. skip rest of the details and click on continue.
Step 7  : This will redirect you to show list of registered application now click on edit settings. This page is very very important because it provides your application id (app-id) as well as application secret(app secret). Copy both app-id and app-secret to another file and save it. both credentials are required to communicate with Facebook API.
Now go under following section: Select how your app integrates with Facebook
and select Website with Facebook Login and provide Site URL path to your local web application path (in my case)  like :  http://localhost:8084/FBAPI
and make sure that you have enabled sandbox mode and save changes. 
That's it . There are many other settings but they are optional, you can set them as per your requirement. 
Step 8 : Now last and final step to set Facebook API to work. Getting an access token. Access token perform very important role while communicating with Facebook API. Without an access taken, it was not possible to get any information from Facebook API. These is a only step where people gets confused where to get an access token of our application. Don't worry I have provided steps to get an access token of your application.
Step 9 : Go to https://developers.facebook.com/tools/explorer
Facebook provide very powerful utility to get an access token of your application and provide a very dynamic feature to access Graph API on the fly.
We will discuss it later on. Now when you open above link you will find your list of application in selection box. Now select proper application if you have more then one application in your account otherwise no need to select any application. once you select application, now click on Get Access Token button to continue.
These will open new pop up box to select list of permission your application will be required from user to access their private data.
select permission details as per your requirement and finish it.
You will see your generated token inside the text box.
Note : Always keep in mind that if you change your permission, you request token gets changes accordingly so after every modification in permission you will get new access token. Access token plays very important role to communicate with Facebook, we have to send access token as parameter on each request.

  


posted under , | 1 Comments

How to create system notification popup like outlook using Swing in java

It would be very easy to make system notification pop up like Microsoft outlook in swing.

I have created following two java classes to make system notification works. First class handled the basic and core level implementation like creating a form and making AWT api to work. Second class is used for testing purpose. 

1. NotificationPopup.java 
package com.vsquaresolution.system.nofitifcation;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Toolkit;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class NotificationPopup extends JDialog {
  private final LinearGradientPaint lpg;

  public NotificationPopup() {
    setUndecorated(true);
    setSize(300, 50);
    // size of the screen
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    // height of the task bar
    final Insets scnMax = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());
    final int taskBarSize = scnMax.bottom;

    setLocation(screenSize.width - getWidth(), screenSize.height - taskBarSize  - getHeight());

    // background paint
    lpg = new LinearGradientPaint(0, 0, 0, getHeight() / 2, 
 new float[] { 0f, 0.3f, 1f }, new Color[] 
 { new Color(1f, 1f, 1f), new Color(1f, 1f, 1f), 
  new Color(1f, 1f, 1f) });

    // blue background panel
    setContentPane(new BackgroundPanel());
  }

  private class BackgroundPanel extends JPanel {
    public BackgroundPanel() {
      setOpaque(true);
    }

    @Override
    protected void paintComponent(final Graphics g) {
      final Graphics2D g2d = (Graphics2D) g;
      // background
      g2d.setPaint(lpg);
      g2d.fillRect(1, 1, getWidth() - 2, getHeight() - 2);
      g2d.setColor(Color.ORANGE); //border color

      // border
      g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
    }
  }

  public static void main(final String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (final Exception e1) {
          e1.printStackTrace();
        }

        final NotificationPopup f = new NotificationPopup();

        final Container c = f.getContentPane();
        c.setLayout(new GridBagLayout());

        final GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.weightx = 1.0f;
        constraints.weighty = 1.0f;
        constraints.insets = new Insets(5, 5, 5, 5);
        constraints.fill = GridBagConstraints.BOTH;

        final JLabel l = new JLabel("You have got 2 new Messages.");
        l.setOpaque(false);

        c.add(l, constraints);

        constraints.gridx++;
        constraints.weightx = 0f;
        constraints.weighty = 0f;
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.NORTH;

//        final JButton b = new JButton(new AbstractAction("x") {
//
//          @Override
//          public void actionPerformed(final ActionEvent e) {
//            f.dispose();
//          }
//        });

//        b.setOpaque(false);
//        b.setMargin(new Insets(1, 4, 1, 4));
//        b.setFocusable(false);
//
//        c.add(b, constraints);

        f.setVisible(true);
      }
    });
  }
}
2. TestNotificationPopUp.java
package com.vsquaresolution.system.nofitifcation;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestNotificationPopUp extends javax.swing.JFrame {
    
    public TestNotificationPopUp() {
        initComponents();
        
    }
    
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Antenna");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(" System "));

        jButton5.setText("Open Notification");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                .add(182, 182, 182)
                .add(jButton5)
                .add(256, 256, 256))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(28, 28, 28)
                .add(jButton5)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// //GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

       SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            try {
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (final Exception e1) {
              e1.printStackTrace();
            }

            final NotificationPopup f = new NotificationPopup();

            final Container c = f.getContentPane();
            c.setLayout(new GridBagLayout());

            final GridBagConstraints constraints = new GridBagConstraints();
            constraints.gridx = 0;
            constraints.gridy = 0;
            constraints.weightx = 1.0f;
            constraints.weighty = 1.0f;
            constraints.insets = new Insets(5, 5, 5, 5);
            constraints.fill = GridBagConstraints.BOTH;

            final JLabel l = new JLabel("You have got 2 new Messages.");
            l.setOpaque(false);

            c.add(l, constraints);

            constraints.gridx++;
            constraints.weightx = 0f;
            constraints.weighty = 0f;
            constraints.fill = GridBagConstraints.NONE;
            constraints.anchor = GridBagConstraints.NORTH;

            f.setVisible(true);
          }
        });

    }//GEN-LAST:event_jButton5ActionPerformed
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestNotificationPopUp().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton5;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    
}

posted under , | 3 Comments

Only allow number in textfield using javascript

JavaScript function that allow only number in text field

function onlyIntegerNumber(evt){
  var e = evt; // for trans-browser compatibility
  var charCode = e.which || e.keyCode;
  if(charCode == 9){
    return true;
  }
  if((charCode >=35 && charCode <38) || charCode ==39 || e.which ==0){
   alert("Please enter only digit (0-9)");
   return false;
  }
  
  if ((charCode > 31) && (charCode < 48 || charCode > 57) ){
          alert('Please enter only digit (0-9)');
         return false;
   }else{
    return true;
   }
}

function isNumberKey(evt){
    var e = evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    
    if(charCode == 46 || charCode == 9){
     return true;
    }
    if((charCode >=35 && charCode <38) || charCode ==39 || e.which ==0){
     alert("Allow only numeric characters (0-9 or .)");
        return false;
    }
    if ((charCode > 31) && (charCode < 48 || charCode > 57) ){
       noty(options);
           return false;
     }else{
    return true;
     }
}

posted under | 0 Comments

How to create generic request processing method using javascript or ajax

SendRequest.js File (Generic Request Processing file)

 
function sendRequest($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer){
 
 var $currentTime = new Date();
 var $timeStamp = $currentTime.getHours() + $currentTime.getMinutes()
 + $currentTime.getSeconds() + $currentTime.getMilliseconds()
 + $currentTime.getDay() + $currentTime.getMonth()
 + $currentTime.getFullYear() + Math.random();

 $.ajax({
 url : $ajaxUrl + "?" + $arguments + "&stamp=" + $timeStamp,
 cache : false,
 beforeSend : function() {
 /* call method before send request to server  */
 showProgressBar();
 },
 complete : function($response, $status) {
 /* hide progress bar once we get response */
 hideProgressBar();
 if ($status != "error" && $status != "timeout") {
 /* for set response in div */
 if($ajaxResponseLayer !="")  
 { 
  if($response.responseText.search("showMessage")>-1){
  //alert('in if ::');
  $("#errorDiv").html($response.responseText.trim());
  processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response.responseText);
  return false;
  }
  $("#"+$ajaxResponseLayer).html($response.responseText);
  processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response.responseText);
 }
 
 }
 },
 error : function($obj) {
 /* call when error occurs */
 hideProgressBar();
 alert("Something went wrong while processing your request."+$obj.responseText);
 }
 });  
}

function processAfterResponse($ajaxUrl,$arguments,$timeStamp,$ajaxResponseLayer,$response){
  if($ajaxUrl =='enterURLAfterProcessing.html'){

   }
}

function closeDialogBox(modelId){
  $("#"+modelId).dialog( "close" );
}

function showProgressBar() {
  document.getElementById('ajax_loader').style.display = 'block';
}

function hideProgressBar() {
  document.getElementById('ajax_loader').style.display = 'none';
}

function IsEmail(email) {
  var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

function onlyIntegerNumber(evt){
  var e = evt; // for trans-browser compatibility
  var charCode = e.which || e.keyCode;
  if(charCode == 9){
    return true;
  }
  if((charCode >=35 && charCode <38 alert="" charcode="" digit="" e.which="=0){" enter="" false="" humanmsg.displaymsg="" if="" lease="" noty="" only="" options="" return=""> 31) && (charCode < 48 || charCode > 57) ){
          alert('Please enter only digit (0-9)');
         return false;
   }else{
    return true;
   }
}

function isNumberKey(evt){
    var e = evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    
    if(charCode == 46 || charCode == 9){
     return true;
    }
    if((charCode >=35 && charCode <38 .="" alert="" characters="" charcode="" e.which="=0){" false="" if="" llow="" numeric="" only="" or="" return=""> 31) && (charCode < 48 || charCode > 57) ){
       noty(options);
           return false;
     }else{
    return true;
     }
}
if(typeof String.prototype.trim !== 'function') {
   String.prototype.trim = function() {
     return this.replace(/^\s+|\s+$/g, ''); 
   };
}


Note : We have to take good care while using trim() function of JavaScript. because it has compatibility issue with IE 8 and older version. So we have to put following line of code in JS, where we used trim function, otherwise function will be given an exception so JavaScript will not be processing further.
if(typeof String.prototype.trim !== 'function') {
   String.prototype.trim = function() {
     return this.replace(/^\s+|\s+$/g, ''); 
   };
}

posted under | 2 Comments
Newer Posts Older Posts Home

Followers

Powered by Blogger.

Populares

Custom Search