Tuesday 22 October 2013

Like button of facebook using javascript SDK

Facebook Like Button implementation code 



<div id="fb-root"></div>
<script>
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id))return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=your_API_id";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
//like button
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="16" data-height="16" data-colorscheme="light" data-layout="standard" data-action="like" data-show-faces="true" data-send="false">
</div>

Post on Facebook using javascript SDK


Post On facebook using javascript SDK

below id the code to create comment box on you page to post the comment on facebook page just you need to put your page facebook pageid/appid where you want to post the comment.

<script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
<![CDATA[
function postOnFB()
{
      window.fbAsyncInit = function() {
   FB.init({
   // window.location.reload();console.log(response);    FB.getLoginStatus(function(response) {      appId: ' YOUR APP ID ',
   xfbml: true,
   status: true,
   cookie: true,
   oauth: true,
    channelUrl : 'CHANNEL URL / REDIRACT URL', // Channel File
});


FB.Event.subscribe("auth.authResponseChange", function(response) {
    });
      if (response && response.status == 'connected') {   

           FB.api('/me', function(response) {
      });
   
        } else if (response.status === 'not_authorized') {
      } else {
      }
     
     });
  
 };

 (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
              

      FB.login(
                function(response) {
                    if (response.authResponse) {
                    var access_token = FB.getAuthResponse()['accessToken'];
                    console.log("token:==>");
                    console.log(access_token);
                    FB.api(
                    'me/photos',
                    'post', {
                    name:"My Post",
                    message: 'here is yor post message',
                    status: 'success',
                    access_token: access_token,
                    url:$("#myimage").attr("src");    /// yourimage url is here
                    },
                    function(response) {
                        if (!response || response.error) {
                        console.log(response);
                        alert('Error occured:' + response);
                        } else {
                        // document.getElementById('imguploadheader').innerHTML="Status";
                        alert(Sucessfully posted);
                        }
                    });
                    } else {
                    errordisplay();
                    $("#appendtext").html(
                    "User cancelled login or did not fully authorize.");
                    $("#uploadingpregress")
                    .css("display","none");
                    successfullyupload();

                    }
                }, {
                scope: 'user_photos,photo_upload,publish_stream,offline_access'
          });
}
]]></script>

Facebook login using javascript SDK

 FACEBOOK Login Example

index.html  /// 

<html><body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
  FB.init({
      appId: '490986011016528', // App ID
      channelUrl: 'http://localhost:8000/', // Channel File
      status: true, // check login status
      cookie: true, // enable cookies to allow the server to access the session
      xfbml: true  // parse XFBML
  });
        
FB.Event.subscribe('auth.authResponseChange', function(response) 
{
   if (response.status === 'connected') 
   {
   document.getElementById("message").innerHTML +=  "<br>Connected to Facebook";
   //SUCCESS
       }  
else if (response.status === 'not_authorized') 
{
     document.getElementById("message").innerHTML +=  "<br>Failed to Connect";
//FAILED
        } 
else 
  { document.getElementById("message").innerHTML +=  "<br>Logged Out";
       //UNKNOWN ERROR
      }
});
    };
    
    function Login(){
FB.login(function(response) {
   if (response.authResponse) 
{
     getUserInfo();
    }
 else 
{
         console.log('User cancelled login or did not fully authorize.');
    }
 },
   {scope: 'email,user_photos,user_videos'});
}
  function getUserInfo() {
    FB.api('/me', function(response) {
  var str="<b>Name</b> : "+response.name+"<br>";
     str +="<b>Link: </b>"+response.link+"<br>";
     str +="<b>Username:</b> "+response.username+"<br>";
     str +="<b>id: </b>"+response.id+"<br>";
     str +="<b>Email:</b> "+response.email+"<br>";
     str +="<input type='button' value='Get Photo' onclick='getPhoto();'/>";
     str +="<input type='button' value='Logout' onclick='Logout();'/>";
     document.getElementById("status").innerHTML=str;         
    });
    }
function getPhoto()
{
  FB.api('/me/picture?type=normal', function(response) {
  var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
     document.getElementById("status").innerHTML+=str;
    });
}
function Logout()
{
FB.logout(function(){document.location.reload();});
}
  // Load the SDK asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));
</script>
<div align="center">
<h2>Facebook OAuth Javascript Demo</h2>
<div id="status">
 Click on Below Image to start the demo: <br/>
<img src="http://hayageek.com/examples/oauth/facebook/oauth-javascript/LoginWithFacebook.png" style="cursor:pointer;" onclick="Login()"/>
</div>
<br/><br/><br/><br/><br/>
<div id="message">
Logs:<br/>
</div>
</div>
</body>
</html>
 
channel.html  /// 
 
<script src="//connect.facebook.net/en_US/all.js"></script>

 


Change a port of the jetty server maven plugin

Below code you need to put inside plugins tag of pom.xml file. which will create a jetty server using maven jetty plugin and will also allow you specify port number instated of using default(8080). 

pom.xml


<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<scanIntervalSeconds>3</scanIntervalSeconds>
<contextPath>/</contextPath>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8090</port>   //put your new port here
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
</configuration>
</plugin>
This code will change the port of your jetty server to 8090 from default port 8080.

please follow the blog if you like it.
Thanks

Tuesday 15 October 2013

Spring Security Login Using Hibernate Example

Spring Security with Authentication


First you need to create table in following structure

create table user_info( 
                       user_name varchar(50),
                       passwd varchar(200),
                       enabled int(1),
                       authority varchar(50) 
                     );

insert into user_info values('jayesh','password',1,'ROLE_USER');

you need to create a file named Spring-security.xml if not exists.
if you have the file than use below code to set up the spring log in configuration.
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/resources/**" security="none" />

 <http auto-config="true" use-expressions="true">
  <intercept-url pattern="/login*" access="permitAll" /> 
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
  
 <form-login login-page="/login" authentication-failure-url="/loginfailed" default-target-url="/Home/"  />
  <logout logout-url="/logout" logout-success-url="/login"  invalidate-session="true"  />
  <session-management >
  <concurrency-control max-sessions="1" expired-url="/loginExp" />
  </session-management>
 </http>
 
 <authentication-manager>
 
  <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"

        users-by-username-query="
        select user_name,passwd,enabled
        from user_info where user_name=?"

        authorities-by-username-query="
        select user_name,authority from user_info         
        where user_name =?  " />
  </authentication-provider> 
  
 </authentication-manager>

 
</beans:beans>
 
 
login.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC  - Spring Authentication Example</title>
</head>
<body>  
 <form action="j_spring_security_check" method="POST"> 
 
  UserName: <input type="text" name="j_username" /> 
 
  Password: <input type="password" name="j_password" />
  
  <input type="submit" value="Login" />
 
 </form>
</body>
</html>
 

Thursday 3 October 2013

Simple Login With Spring Security

Spring Security

here i have used form-login to configure spring security login.

if you want to restrict user to access all url and want to allow specific url portion then you can use do that by <intercept-url />

and using form-login we can control the user authentication filer or success.and we can display our custom login form.

when you are using <http-basic /> then web browser is displaying a log in dialog for user authentication.

To enable HTTP basic, just change “form-login” to “http-basic” tag.
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
                       xmlns:beans="http://www.springframework.org/schema/beans" 
                       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                       xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                       http://www.springframework.org/schema/security
                       http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
 
 <http>
 <intercept-url pattern="/welcome*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
   authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
 </http>
 <authentication-manager>
    <authentication-provider>
        <user-service>
  <user name="jayesh" password="jayesh" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
 </authentication-manager>
 
</beans:beans> 
login.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<form action="j_spring_security_check" method="POST">

UserName: <input type="text" name="j_username" />
Password:  <input type="password" name="j_password" />

<input type="submit" value="Login" />
</form>
</body>
</html>

HttpSessionListner implementation with service calls in spring

Here’s a simple “HttpSessionListener” example to do the login and logout time entry in the database.using service 

Java Source

package com.jayesh;
 
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener {
 
 private MyDbService myDbService;
  public static int getTotalActiveSession(){
 return totalActiveSessions;
  }
 
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
           ApplicationContext ctx = 
                WebApplicationContextUtils.
                      getWebApplicationContext(session.getServletContext());
 
          MyDbService  myDbService= 
                      (MyDbService) ctx.getBean("myDbServiceBeaniId");               
   myDbService.addLoginTime();                                                                                                                  System.out.println("session time is inserted in database");                   
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
                                MyDbService  myDbService= 
                      (MyDbService) ctx.getBean("myDbServiceBeaniId"); 
                                System.out.println("sessionDestroyed and logout time inserted");
  } 
}

web.xml


<web-app ...>
       <listener>
              <listener-class>com.jayesh.SessionCounterListener</listener-class>
       </listener>
</web-app>
 
 
spring-secutity.xml
 
<beans:bean id="myBdServiceBeanId" class="com.jayesh.service.MyDbServices"></beans:bean>

How it work?

- If a new session is created , e.g “request.getSession();” , the listener’s sessionCreated() will be executed.
- If a session is destroyed, e.g session’s timeout or “session.invalidate()”, the listener’s sessionDestroyed() will be executed.
  HttpSession session = request.getSession(); //sessionCreated() is executed
  session.setAttribute("url", "mydomain.com"); 
  session.invalidate();  //sessionDestroyed() is executed