Friday, 31 July 2015

How to Delete Files / Folders on Windows, Mac OS X and Linux Machine from Java?


In this tutorial we will go over all steps in details to delete Files and Folders on Windows OS, Mac OS X and Linux.
Here I
  1. Create file DeleteWindowsFileFolder.java
  2. Create crunchifyDeleteWindowsFolder(List of Directories) which first check for if directory exists or not? If exists then it will delete all files under it.
  3. Create crunchifyDeleteFiles(file) which deletes file.
package Pack;

import java.io.File;
import java.io.IOException;
 
/**
 * @author Rajkumar Sahoo
 *
 */
 
public class DeleteWindowsFileFolder {
public static void main(String[] args) {
 
// For Windows Provide Location: c:\\crunchify, c:\\temp
// For Mac OS X Provide Location: /Users/<username>/Downloads/file.ppsx
// For Linux Provide Location: /tmp/crunchify-file.txt
String[] crunchifyDir = { "D:\\crunchify", "c:\\temp", "/Users/<username>/Downloads/file.ppsx",
"/tmp/crunchify-file.txt" };
String result = crunchifyDeleteWindowsFolder(crunchifyDir);
System.out.println("Result: " + result);
}
 
public static void crunchifyDeleteFiles(File myFile) throws IOException {
 
if (myFile.isDirectory()) {
// Returns an array of strings naming the files and directories in the directory denoted by this abstract
// pathname.
String crunchifyFiles[] = myFile.list();
 
for (String file : crunchifyFiles) {
// Creates a new File instance from a parent abstract pathname and a child pathname string.
File fileDelete = new File(myFile, file);
 
// recursion
crunchifyDeleteFiles(fileDelete);
}
 
} else {
// Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory,
// then the directory must be empty in order to be deleted.
myFile.delete();
System.out.println("File is deleted : " + myFile.getAbsolutePath());
}
}
 
public static String crunchifyDeleteWindowsFolder(String[] crunchifyDirectories) {
 
try {
for (String crunchifyDir : crunchifyDirectories) {
File directory = new File(crunchifyDir);
 
// Tests whether the file or directory denoted by this abstract pathname exists.
if (!directory.exists()) {
System.out.println("File does not exist: " + directory);
} else {
try {
// recursion approached
crunchifyDeleteFiles(directory);
System.out.println("Cleaned Up Files Under Directory: " + directory + "\n");
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
return "Execution Complete";
} catch (Exception e) {
return "Execution Failed";
}
}
 
}

Output :
File is deleted : D:\crunchify\New Microsoft Word Document.docx
Cleaned Up Files Under Directory: D:\crunchify

File does not exist: c:\temp
File does not exist: \Users\<username>\Downloads\file.ppsx
File does not exist: \tmp\crunchify-file.txt
Result: Execution Complete


Read an XML File in Java (DOM Parser)



In this tutorial we show how can you read the contents of an XML File using a DOM parser.
This xml contains list of employees (id,name etc)
Here is the Employee bean object.

package Pack;

public class Employee {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String role;
     
    public Employee(){}
     
    public Employee(int id, String name, int age, String gender, String role){
        this.id=id;
        this.age=age;
        this.name=name;
        this.gender=gender;
        this.role=role;
    }
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    
    
    @Override
    public String toString() {
        return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +
                " Role=" + this.role;
    }
     
     

}

Here is the java program that uses DOM Parser to read and parse XML file to get the list of Employee. 
/*
 * Author :Rajkumar Sahoo
 * */

package Pack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLReaderDOM {

    public static void main(String[] args) {
        String filePath = "employees.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("Employee");
            //now XML is loaded as Document in memory, lets convert it to Object List
            List<Employee> empList = new ArrayList<Employee>();
            for (int i = 0; i < nodeList.getLength(); i++) {
                empList.add(getEmployee(nodeList.item(i)));
            }
            //lets print Employee list information
            for (Employee emp : empList) {
                System.out.println(emp.toString());
            }
        } catch (SAXException | ParserConfigurationException | IOException e1) {
            e1.printStackTrace();
        }

    }


    private static Employee getEmployee(Node node) {
        //XMLReaderDOM domReader = new XMLReaderDOM();
        Employee emp = new Employee();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            emp.setName(getTagValue("name", element));
            emp.setAge(Integer.parseInt(getTagValue("age", element)));
            emp.setGender(getTagValue("gender", element));
            emp.setRole(getTagValue("role", element));
        }

        return emp;
    }


    private static String getTagValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodeList.item(0);
        return node.getNodeValue();
    }


}

Modify XML File in Java using DOM parser

Modify XML File in Java using DOM parser


In this tutorial we show how can you read and modify the contents of an XML File using a DOM parser.

  • We are going to use Document.getElementsByTagName() to get the elements of the document with specific tag name.
  • Use Node.getAttributes() to get a NamedNodeMap of the element’s attributes.
  • Use NamedNodeMap.getNamedItem to get a specific attributes by name.
  • Use Node.setTextContent() to set the value of that specific attributes.
  • Use Node.removeChild or Node.addChild in order to remove or add a new property for the specific element.
You download the jar file named as jdom-2.0.4.jar


/*
 * Author : Rajkumar Sahoo
 * */
package Pack;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadAndModifyXMLFile {

public static final String xmlFilePath = "D:\\employees.xml";

public static void main(String argv[]) {

try {

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

Document document = documentBuilder.parse(xmlFilePath);

// Get employee by tag name
//use item(0) to get the first node with tage name "employee"
Node employee = document.getElementsByTagName("employee").item(0);
System.out.println("employee :"+employee);
// update employee , set the id to 10
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("id");
nodeAttr.setTextContent("2");

// append a new node to the first employee
Element address = document.createElement("address");

address.appendChild(document.createTextNode("Noida sec-62"));

employee.appendChild(address);

// loop the employee node and update salary value, and delete a node
NodeList nodes = employee.getChildNodes();

for (int i = 0; i < nodes.getLength(); i++) {

Node element = nodes.item(i);

if ("salary".equals(element.getNodeName())) {
element.setTextContent("20000");
}

// remove firstname
if ("firstname".equals(element.getNodeName())) {
employee.removeChild(element);
}

}

// write the DOM object to the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);

StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);

System.out.println("The XML File was ");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}


Write XML (DOM) File in Java

Simple way to write data into XML file.


Here I am create      
  • Root XML element with name: Companies
  • Company Element
  • Every Company Element has an attribute id
  • Every Company Element have 3 elements – Name, Type, Employee
You download the jar file named as jdom-2.0.4.jar

/*
 * Author :Rajkumar Sahoo
 * */

package Pack;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import Pack.Employee;

public class JDOMXMLWriter {

    public static void main(String[] args) throws IOException {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee(1, "Pankaj",25,"Male","Java Developer"));
        empList.add(new Employee(2, "Mona",34,"Female","Manager"));
        empList.add(new Employee(3, "Dave",45,"Male","Support"));
       
        String fileName = "employees.xml";
        writeFileUsingJDOM(empList, fileName);
    }

    private static void writeFileUsingJDOM(List<Employee> empList, String fileName) throws IOException {
        Document doc = new Document();
        doc.setRootElement(new Element("Employees",  Namespace.getNamespace("http://rajukumarsahoo.blogspot.in/")));
        for(Employee emp : empList){
            Element employee = new Element("Employee");
            employee.setAttribute("id",""+emp.getId());
            employee.addContent(new Element("age").setText(""+emp.getAge()));
            employee.addContent(new Element("name").setText(emp.getName()));
            employee.addContent(new Element("gender").setText(emp.getGender()));
            employee.addContent(new Element("role").setText(emp.getRole()));
            doc.getRootElement().addContent(employee);
        }
        //JDOM document is ready now, lets write it to file now
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream(fileName));
    }

}



Tuesday, 7 July 2015

Facebook Like Extracting URL Data using Jquery and Ajax in JAVA

Hello friends today I tell you how to  extracting URL data using Jquery and Ajax in jsp.

Step:1- index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facebook Extract Link Data</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

 
 <script type="text/javascript">


 $(document).ready(function()
{

$("#contentbox").keyup(function()
{
var content=$(this).val();

var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

var url= content.match(urlRegex);


if(url.length>0)
{

$("#linkbox").slideDown('show');
$("#linkbox").html("<img src='link_loader.gif'>");
$.get("getData.jsp?url="+url,function(response)
{
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];

var logo=(/src='(.*?)'/m).exec(response)[1];


$("#linkbox").html("<img src='"+logo+"' class='img'/><div><b>"+title+"</b><br/>"+url)

});

}
return false();
});

});
</script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;

}
.img
{
float:left; width:150px; margin-right:10px;
text-align:center;
}
#linkbox
{
border:solid 2px #dedede; min-height:50px; padding:15px;
display:none;
}
</style>
</head>

<body>

<div id="xxx"></div>
<div style="margin:50px; padding:10px; width:460px">
<div style="height:25px">

<div style="float:left"><b>Facebook Box</b><br />Eg: 9lessons programmin blog http://www.9lessons.info</div>
</div>
<textarea id="contentbox"></textarea>

<div id="linkbox">
</div>
</div>

</div>

</body>
</html>

Step:2-getData.jsp

<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.net.URL"%>
<%@page import="java.io.BufferedInputStream"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%

String url=request.getParameter("url");
//System.out.println(url);


URL url1 = new URL(url);
System.out.println("111111111111    :"+url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();

BufferedReader in = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));

String inputLine;
StringBuffer html = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();

out.println(html);
System.out.println(html);


%>


</body>

</html>

Step:2-getData.jsp (Alternate )

In this case you need 3 jars

1.commons-httpclient.jar
2.commons-logging.jar
3.httpcore-4.0.1.jar

<%@page import="org.apache.commons.httpclient.*,org.apache.http.HttpStatus,
org.apache.commons.httpclient.methods.*"%>

<%
           String url=request.getParameter("url");
             HttpClient client = new HttpClient();
           HttpMethod method = new GetMethod( url );
          try{
               client.executeMethod( method );
               if (method.getStatusCode() == HttpStatus.SC_OK)
               {
           String res= method.getResponseBodyAsString();
               out.print(res);
             
             
               }
               else
               {
                     out.println("Status Code of hitting URL:  "+method.getStatusCode());
               }
               }catch(Exception e){ e.printStackTrace();}
               
%>


Out Put: