Wednesday, 29 May 2013

ASCII Art Java Example

package com.jay;
 
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
import javax.imageio.ImageIO;
 
public class ASCIIArt {
 
  public static void main(String[] args) throws IOException {
 
 int width = 100;
 int height = 30;
 
        //BufferedImage image = ImageIO.read(new File("your path/logo.jpg"));
 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 Graphics g = image.getGraphics();
 g.setFont(new Font("SansSerif", Font.BOLD, 24));
 
 Graphics2D graphics = (Graphics2D) g;
 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
 graphics.drawString("JAVA", 10, 20);
 
 //save this image
 //ImageIO.write(image, "png", new File("your path/ascii-art.png"));
 
 for (int y = 0; y < height; y++) {
  StringBuilder sb = new StringBuilder();
  for (int x = 0; x < width; x++) {
 
   sb.append(image.getRGB(x, y) == -16777216 ? " " : "$");
 
  }
 
  if (sb.toString().trim().isEmpty()) {
   continue;
  }
 
  System.out.println(sb);
 }
 
  }
 
}

Tuesday, 7 May 2013

What does “event bubbling” mean? [In context of CSS]

“Delegation” and “bubbling” are terms that gets thrown round a lot in JavaScript; but what exactly do these terms mean?

Event Bubbling

In JavaScript, events bubble. This means that an event propagates through the ancestors of the element the event fired on. Lets show what this means using the HTML markup below;
<div>
    <h1>
        <a href="#">
            <span>Hello</span>
        </a>
    </h1>
</div>
Lets assume we click the span, which causes a click event to be fired on the span; nothing revolutionary so far. However, the event then propagates (or bubbles) to the parent of the span (the <a>), and a click event is fired on that. This process repeats for the next parent (or ancestor) up to the document element.
You can see this in action here. Click “Hello” and see the events as they get fired.
That’s all event bubbling is; an event fired on an element bubbles through its ancestor chain (i.e. the event is also fired on those elements). It’s important to note that this isn’t a jQuery feature, nor is it something that a developer must turn on; it’s a fundamental part of JavaScript that has always existed.
Ok, that’s a little bit of a lie… sort of.
By default, not all events bubble. For instance submit does not normally bubble, nor does change. However, jQuery masks this in the event handling code using all sorts of voodoo, so it will seem that they do bubble when using jQuery.

Friday, 26 April 2013

Why you should never use a CAPTCHA [by Josh Fraser]

I hate CAPTCHAs (you know, those squiggly bits of impossible to read text you have to fill out before you can do anything on some websites). I think all of us can relate to the experience of trying to register for a service or comment on a blog only to be stopped cold by an impossible CAPTCHA. Maybe you got it on the second or third try, but chances are you’ve also had occasions when you’ve bailed and decided it just wasn’t worth the effort.  Today I want to convince you to never add a CAPTCHA to your site.
Let’s start by looking at why CAPTCHAs were invented. The acronym stands for Completely Automated Public Turing test to tell Computers and Humans Apart. Quite a mouthful, eh? The idea is to have something that a computer can create but only a human can read. Whether or not humans can read CAPTCHAs is debatable, but that’s the idea anyway.  

Lots of sites use these things to attempt to stop automated requests. For example, you’ve got to fill out a CAPTCHA to get a Gmail account, send a message with a link on Facebook or even just email directions on Mapquest. CAPTCHAs are most often used to stop abuse around systems where there is a high incentive for automated systems to be used, like spamming everyone on Facebook. There are also a lot of people using CAPTCHAs where an alternative solution would suffice.

My biggest beef with CAPTCHAs is that they are so freaking annoying for users. They add an incredible amount of friction to the process — friction that you probably can’t afford. Sure, some CAPTCHA’s are better than others, but none are great. I understand you want to protect your site from spam and abuse, but are you ready to lose potential users over it?  The trade off just isn’t worth it, especially if you are a startup!

One of the things I’ve noticed is that many people use CAPTCHAs when a simple non-intrusive spam-stopper would suffice. For example, say you have a blog and notice you are starting to get a large amount of spam comments. You decide to add a CAPTCHA to fix the problem. The thing is, you’re not big enough to be a victim of a targeted attack, you’re just getting generic spam bots. You don’t need a CAPTCHA.

It’s far easier to stop generic spam bots than a targeted attack. There are a lot of different techniques you can employ, but a simple option is to add an extra field with a tempting name like “email” to your form that is then hidden using CSS. Humans can’t see the field and as a result will never fill it out. Any request that comes in with the field completed can easily be eliminated as spam. The beauty of this is you have a pretty effective spam-stopper without ruining the user experience or adding any friction to the process. A simple technique like this is probably enough to stop the majority of spam bots.

But what if you really are big enough to be at the receiving end of a targeted attack? What if you’re Facebook or Google? They might not be fun, but aren’t CAPTCHAs a necessary evil?  I don’t think so. CATCHAs still aren’t going to protect you. The bad news is that most CAPTCHA systems have already been cracked using OCR software making it trivial for your system to be compromised. For the rest, hackers have been known to set up porn sites that require you to enter a CAPTCHA in exchange for access to the adult content. What are you going to do to prevent that? Not to mention, there’s a booming business in India right now for breaking CAPTCHAs. The going rate is $2 per 1,000. Can you compete with that? If someone wants into your site, I’m sorry, but your annoying little CAPTCHA isn’t going to stop them.

Some people have taken more creative approaches to the CAPTCHA problem.  Joe Stump tweeted the other day about one solution he discovered. You’ll see a lot of these around the web, often added by people who hate CAPTCHAs but haven’t stopped to think through the details. I remember seeing one approach that Hot or Not used that asked users to pick the 3 most attractive people out of 9 pictures. While these sort of solutions are more fun for users than a traditional CATPCHA, they are usually still pretty worthless at providing any real security. 

For example, with Hot or Not, the odds of a computer correctly guessing the 3 attractive people are 1 in 84. While those aren’t great odds for a human, they’re not bad for a computer — especially if you have a botnet at your disposal! Other approaches like the ones that ask you to do simple math or ask simple questions like “what is known as man’s best friend?” are vulnerable too. In most cases, all you’d need to do to crack the CAPTCHA is throw the question at Google and analyze the responses that come back.  These systems are often also vulnerable by having a limited list of questions to ask so it doesn’t take long for a hacker to build up a dictionary of correct answers to feed to the bot.

reCAPTCHA from Google is another anti-bot alternative.  They proudly talk about all the good they are doing by using the technology to help digitize books. But even reCAPTCHA can be broken with 23% accuracy and it’s just as frustrating for users as the other alternatives.
So where does that leave us?  CAPTCHAs are annoying, you probably don’t need one and even if you did it could still be broken pretty easily.

The most balanced approach is to add some basic security to stop generic bots and then stop worrying and get rid of the CATPCHA altogether! Instead, watch out for suspicious IP’s and monitor for nefarious behavior (like spam links being sent to multiple users, large # of requests from one IP, etc).

We live in a world where spammers are a real problem and must be addressed, but CAPTCHAs are not the answer. You simply can not afford the friction. By using a CAPTCHA you are making the internet a whole lot less fun for all of us.

Monday, 22 April 2013

Servlets Vs Portlets



Similarities


    Servlets and Portlets are web based components which use Java for their implementation.

    Portlets are managed by a portlet container just like servlet is managed by servlet container.

    Both static and dynamic content can be generated by Portlets and Servlets.

    The life cycle of portlets and servlets is controlled by the container

    The client/server model is used for both servlets and portlets

    The packaging and deployment are essentially the same, WAR/EARs.

Dissimilarities

    Servlets can render complete web pages, whereas portlets renders html fragments. These fragments are aggregated by the portal into a complete web page.

    The content type of JSR 168 portlets can be only cHTML, XHTML, WML. It does not support other content types.

    Portlets are not allowed to generate HTML code that contains tags such as body, frame, frameset, head, html, or title.

    A Portlet unlike a servlet doesn’t have URL attached to it so it cannot be accessed directly. Access is only through the portal page which holds the portlet.

    Portlets can be provided with controls to manipulate its window states or portlet modes.

    Multiple instances of a single portlet can be placed onto the same page.

    Portlets support persistent configuration and customization, profile information.

    Portlets can have two types of request viz. render request and action request.

    Portlets have two scopes within session; application scope for communication across portlets and portlet scope for intra portlet communication.

    Portlet cannot set the character set encoding of the response nor can it set the HTTP response headers.

    Portlets doesn’t have access to request URL. So it cannot access the query parameters appended to the URL.
    Portlets cannot set cookies.

    Typical methods of Portlet API are doView(), doEdit(), doHelp() and processAction() while those of servlet are doService(), doPost(), doGet().

Saturday, 20 April 2013

JDK 8 Feauture

Here are some of the features coming in JDK8
  • Improvement in java.lang package
  • Annotations on Java Types
  • DocTree API
  • Parallel Array Sorting
  • Bulk Data Operations for Collections
  • Collections Enhancements from Third-Party Libraries
  • Base64 Encoding and Decoding
  • New HTTP Client
  • More Security enhancement                                         
If you want to explore more about Lambda check here http://openjdk.java.net/projects/lambda/
Technical discussions on Lambda Dev here http://mail.openjdk.java.net/mailman/listinfo/lambda-dev

What is the solution of JAR Updates and its dependencies...?



 Answer is:  Apache Maven 
----------------------------------------------------------------------------------
 Introduction
Maven, a Yiddish word meaning accumulator of knowledge, was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. There were several projects each with their own Ant build files that were all slightly different and JARs were checked into CVS. We wanted a standard way to build the projects, a clear definition of what the project consisted of, an easy way to publish project information and a way to share JARs across several projects.
The result is a tool that can now be used for building and managing any Java-based project. We hope that we have created something that will make the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project.
Maven's Objectives
Maven's primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with:
  • Making the build process easy
  • Providing a uniform build system
  • Providing quality project information
  • Providing guidelines for best practices development
  • Allowing transparent migration to new features
For more Details.. Go Through http://maven.apache.org/what-is-maven.html and any doubt about it send me mail ….

Zip Format Compress With JAVA Code

package com.jay.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MyZip
{
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String SOURCE_FOLDER = "C:\\testzip";

    MyZip(){
    fileList = new ArrayList<String>();
    }

    public static void main( String[] args )
    {
        MyZip MyZip = new MyZip();
        MyZip.generateFileList(new File(SOURCE_FOLDER));
        MyZip.zipIt(OUTPUT_ZIP_FILE);
    }

    /**
     * Zip it
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile){

     byte[] buffer = new byte[1024];

     try{

        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        System.out.println("Output to Zip : " + zipFile);

        for(String file : this.fileList){

            System.out.println("File Added : " + file);
            ZipEntry ze= new ZipEntry(file);
            zos.putNextEntry(ze);

            FileInputStream in =
                       new FileInputStream(SOURCE_FOLDER + File.separator + file);

            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            in.close();
        }

        zos.closeEntry();
        //remember close it
        zos.close();

        System.out.println("Done");
    }catch(IOException ex){
       ex.printStackTrace();  
    }
   }

    /**
     * Traverse a directory and get all files,
     * and add the file into fileList 
     */
    public void generateFileList(File node){

        //add file only
    if(node.isFile()){
        fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
    }

    if(node.isDirectory()){
        String[] subNote = node.list();
        for(String filename : subNote){
            generateFileList(new File(node, filename));
        }
    }

    }

    /**
     * Format the file path for zip
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file){
        return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}