Saturday, October 30, 2010

SocialAuth - Java Library for oAuth and OpenID providers


SocialAuth is a Java library for you if your web application requires:
  • Authenticating users through external oAuth providers like Yahoo, Google, Twitter, Facebbook etc as well as through OpenID providers like myopenid.com.
  • Easy user registration. All you need to do is create a page where users can click on buttons for the above providers or other supported providers. Just call SocialAuth and you can get all their profile details.
  • Importing contacts from Google, Yahoo or Hotmail. Support for importing friends from Facebook and followers from Twitter coming soon !

Why SocialAuth?
There are so many libraries out there which implement OpenID and oAuth, so why another library? There many practical challenges that we faced while doing the implementation of above use cases. None of them is insurmountable but the developer could spend a couple of weeks solving these, which we actually did and hence decided to make things better for the community.
  • There are many libraries for implementing Open ID and many for implementing oAuth. It becomes a difficult exercise to choose one that will do the integration quickly with the providers you want.
  • Some libraries do not implement all the features and it becomes known only in the later stages of implementation – for example we found out that openid4java does not implement the hybrid protocol. We also found out that it is not easy to integrate dyuproject library.
  • Even after implementing using the library, it does not work out of the box for all providers. There are always certain things specific to a certain provider. For example the scopes are different as well as some steps in authorization may be different.
  • Getting the actual data, for example contacts of a user is out of the scope of these protocols and hence most libraries do not implement this functionality.
So what we implemented is a wrapper that leverages these existing libraries, and works out of the box without requiring you to face the above challenges. You get the same interface to deal with integration of every provider.

More details : http://www.theserverside.com/news/thread.tss?thread_id=61205


What is Captcha?


The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.

A CAPTCHA is a program that can tell whether its user is a human or a computer. You've probably seen them — colorful images with distorted text at the bottom of Web registration forms. CAPTCHAs are used by many websites to prevent abuse from "bots," or automated programs usually written to generate spam. No computer program can read distorted text as well as humans can, so bots cannot navigate sites protected by CAPTCHAs.

Example captcha image:
File:Captcha.jpg


Basic Java Questions(Core Java Faq) part 3


What is Constructor?
*       A constructor is a special method whose task is to initialize the object of its class.
*       It is special because its name is the same as the class name.
*       They do not have return types, not even void and therefore they cannot return values.
*       They cannot be inherited, though a derived class can call the base class constructor.
*       Constructor is invoked whenever an object of its associated class is created.

How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.

Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.

What are the differences between Contructors and Methods?

Constructors
Methods
Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, native, static, or synchronized Can be abstract, final, native, static, or synchronized
Return Type No return type, not even void void or a valid return type
Name Same name as the class (first letter is capitalized by convention) -- usually a noun Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this Refers to another constructor in the same class. If used, it must be the first line of the constructor Refers to an instance of the owning class. Cannot be used by static methods.
super
Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance
Constructors are not inherited
Methods are inherited

How are this() and super() used with constructors?
*       Constructors use this to refer to another constructor in the same class with a different parameter list.
*       Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

What are the differences between Class Methods and Instance Methods?
Class Methods
Instance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the class
Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.
Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an  instance of the class.
Instance methods are not declared as static.

How are this() and super() used with constructors?
*       Constructors use this to refer to another constructor in the same class with a different parameter list.
*       Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..

What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
*       Public- public classes, methods, and fields can be accessed from everywhere.
*       Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
*       Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
*       Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
 Situation 
 public 
 protected 
 default 
 private 
 Accessible to class
 from same package? 
yes
yes
yes
no
 Accessible to class
 from different package? 
yes
 no, unless it is a subclass 
no
no

What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
*       final Classes- A final class cannot have subclasses.
*       final Variables- A final variable cannot be changed once it is initialized.
*       final Methods- A final method cannot be overridden by subclasses.

What are the uses of final method?
There are two reasons for marking a method as final:
*       Disallowing subclasses to change the meaning of the method.
*       Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

What are static variables?
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
              static type  varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:
*       A static method can only call other static methods.
*       A static method must only access static data.
*       A static method cannot reference to the current object using keywords super or this.
*       reference to the current object using keywords super or this.


Google App Engine


Run web apps on Google's infrastructure. http://code.google.com/appengine/


How to add a captcha to JSP(Adding captcha)



A captcha is an image with some modified text on it. They're usually used to prevent automated scripts from accessing certain parts of your site. For example, you'd add a captcha on a wiki edit page or a forum reply page so a spammer doesn't make a bunch of fake content on your site.
This page will teach you how to add a captcha to your site by using reCAPTCHA. reCAPTCHA is a free (and ad-free) widget that will generate captchas for you.
First things first; you will need to sign up for a reCAPTCHA account. Don't worry, this is very straightforward. Sign up for an account here:http://recaptcha.net/whyrecaptcha.html. After you sign up, you will be given a public and a private key. Write these down because you'll need them later.
The second thing you'll want to do is download a reCAPTCHA library that simplifies using the reCAPTCHA API in java. You can download that here:http://code.google.com/p/recaptcha/downloads/list. Download the zip that says "for Java". Extract the jar and put it in your classpath.
Now for some code. Add this to your ActionBean:
public String getReCaptchaHtml() {
ReCaptcha recaptcha = createReCaptcha();
return recaptcha.createRecaptchaHtml("You did not type the captcha correctly", new Properties());
}

private ReCaptcha createReCaptcha() {
String publicKey = //your public key
String privateKey = //your private key
return ReCaptchaFactory.newReCaptcha(publicKey, privateKey, true);
}
With this, we can add the reCAPTCHA widget to our JSP like so:
${actionBean.reCaptchaHtml}
But one thing remains: We don't have a way to tell if the user submitted the correct value. Lets assume the method that gets called on submit is named "submit". Here's how you would add a validation method that ensures that the captcha code was entered correctly:
@ValidationMethod(on = "submit")
public void captchaValidation(ValidationErrors errors) {
ReCaptchaResponse response = createReCaptcha().checkAnswer(context.getRequest().getRemoteAddr(),
context.getRequest().getParameter(
"recaptcha_challenge_field"),
context.getRequest().getParameter(
"recaptcha_response_field"));
if (!response.isValid()) {
errors.add(
"Captcha", new SimpleError("You didn't type the captcha correctly!"));
}
}
This will give you a completely functional captcha.


HOW TO ADD CAPTCHA TO BLOGGER.COM BLOGS TO MINIMIZE COMMENT SPAM?



To start, log in to your blogger.com account and click on the "Settings" tab. You'll see a top nav menu like this:
Blogger Settings Tab
Click on the "Comments" sub-menu and you'll see a pile of different options, with the one you want about 2/3 of the way down the screen:
Blogger Word Verification Option
Select "Yes" here, choose "Save Settings", and you'll now have word capture enabled on your comments and that should, almost like magic, either eliminate your comment spam completely or at least reduce it to an easily manageable trickle of annoyance rather than a tsunami of pain.
Here's how it'll end up looking once you have everything configured:
Comment Captcha
By the way, if you hear people talk about captcha or comment captcha this is what they're talking about, even if the Blogger folk (who are, of course, owned by Google) refer to it in their interface as "word verification".


Basic Java Questions(Core Java Faq) part 2


How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
        // From subclass
              super.overriddenMethod();


What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
*       You can only go back one level.
*       In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.

How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
                              public final void exampleMethod() {

                          //  Method statements

                          }

What is an Interface?
An interface is a description of a set of methods that conforming implementing classes must have.
Note:
*       You can’t mark an interface as final.
*       Interface methods must be static.
*       An Interface cannot extend anything but another interfaces.
Can we instantiate an interface?
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:
*       If even a single method is abstract, the whole class must be declared abstract.
*       Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
*       You can’t mark a class as both abstract and final.

Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

What are the differences between Interface and Abstract class?
Abstract Class
Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .
An Interface cannot contain constructors .
Abstract classes are fast.
Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
*       You see that something in your design will change frequently.
*       If various implementations only share method signatures then it is better to use Interfaces.
*       you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
*       If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
*       When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
*       Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.

Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.


How to upload file with Java Servlet


This is a simple example of how to upload files using JSP and Servlet 3.0 which is a part of Java EE 6. While in earlier versions of Servlets we had to use commons fileupload or other libraries, this feature has been integrated into the Servlet 3.0 specification. Here is the code for a simple servlet and a JSP file that makes a file upload request to the servlet.


  1. FileUploadServlet.java
    package com.blogspot.aoj.servlet3;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;

    import org.apache.log4j.Logger;

    @WebServlet(urlPatterns = "/fileUpload")
    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(FileUploadServlet.class);

    public FileUploadServlet() {
    super();
    }

    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
    logger.info(part.getName());
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    byte[] b = new byte[i];
    is.read(b);
    logger.info("Length : " + b.length);
    String fileName = getFileName(part);
    logger.info("File name : " + fileName);
    FileOutputStream os = new FileOutputStream("c:/temp/logs/" + fileName);
    os.write(b);
    is.close();
    }

    }

    private String getFileName(Part part) {
    String partHeader = part.getHeader("content-disposition");
    logger.info("Part Header = " + partHeader);
    for (String cd : part.getHeader("content-disposition").split(";")) {
    if (cd.trim().startsWith("filename")) {
    return cd.substring(cd.indexOf('=') + 1).trim()
    .replace("\"", "");
    }
    }
    return null;

    }

    protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }

    }
    Note:
    • There is no need to use a deployment descriptor the @WebServlet annotation is enough, which uses the urlPatterns property to define servlet mappings
    • The @MultipartConfig is used to indicate that the servlet expects requests wofmultipart/form-data MIME type which is required for file upload. Using@MultipartConfig allows you to use the request.getParts get the parts of the request
    • The getFileName method gets the file name from the content-disposition header.
  2. upload.jsp
    <html>
    <head>
    <title>File Upload with Servlet 3.0</title>
    </head>
    <body>
    <form action="fileUpload" enctype="multipart/form-data" method="post">
    <input type="file" name="uploadFile" /> <input type="submit" /></form>
    </body>
    </html>