Saturday, 30 August 2014

To getting the json from URL and converting the json in MAP Object

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;

public class ParseJson1 {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
        try {
            HashMap<String, String> map=new HashMap<String,String>();
            String genreJson = IOUtils.toString(url.openStream());
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
           Iterator i= genreJsonObject.entrySet().iterator();
            while(i.hasNext())
            {
           Entry ee=(Entry) i.next();
           System.out.println(ee.getKey());
           System.out.println(ee.getValue());
                }
          
      
           /*
            // get the title
            System.out.println(genreJsonObject.get("title"));
            // get the data
            JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
            // get the first genre
            JSONObject firstGenre = (JSONObject) genreArray.get(0);
            System.out.println(firstGenre.get("genre_title"));
        */
        
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

Note - Required jars commons-io-1.4.jar , json-simple.jar

Friday, 29 August 2014

To Reading data from given URL by using URL class and openStream() then Write in file

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class OpenStr {

    public int add(int a,int b)
    {
        return(a+b);
    }
   
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws IOException {
        String str="";
        BufferedWriter out=new BufferedWriter(new FileWriter("google.html"));
        // TODO Auto-generated method stub
try{
   
        URL u=new URL("http://www.w3schools.com/");
        DataInputStream in=new DataInputStream(u.openStream());
        while(in.readLine()!=null)
        {
           
            //System.out.println(in.readLine());
            str+=in.readLine();
           
        }
        in.close();
}catch (Exception e) {
    // TODO: handle exception
}   
       
        System.out.println(str);
        out.write(str);
        out.close();
    }

}

JAVAChat: Fiter The Collection of String From number of File...

JAVAChat: Fiter The Collection of String From number of File...: import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStr...

Fiter The Collection of String From number of Files

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FilterText {

    public static void main(String s[]) throws IOException {
        String line = null;
        List<String> modelsList = new ArrayList<String>();
        File directory = new File("C:\\Users\\vp0c42452\\Desktop\\texts\\text");
        if (directory.isDirectory()) {
            for (int x = 0; x < directory.listFiles().length; x++) {

                FileInputStream in = new FileInputStream(
                        directory.listFiles()[x]);

                InputStreamReader inputStreamReader = new InputStreamReader(in);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String[] splitArray = null;

                while (((line = reader.readLine()) != null)) {
                    splitArray = line.split(",");
                    String sss = null;
                    for (int i = 0; i < splitArray.length; i++) {
                        if (splitArray[i].contains("modelNum")) {
                            String[] ss = splitArray[i].split(":");
                            // for (int j = 0; j < ss.length; j++) {
                            sss = ss[1].substring(ss[1].indexOf("\"") + 1,
                                    ss[1].lastIndexOf("\""));
                            // }
                            if (sss != null && !modelsList.contains(sss))
                                modelsList.add(sss);
                        }
                    }

                }
            }
        }
        System.out.println(modelsList);

    }
}

Send Mails Using JAVA MAIL API

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {

 
    private static String RECIPIENT = "UserName1@gmail.com";

    public static void main(String[] args) {
        String from = "UserName1@gmail.com";
        String pass = "PassWord1";
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = "Welcome to vijay java mail Api!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(final String from, final String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        //props.put("mail.smtp.user", from);
        //props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("smtp.EnableSsl", "true");
       
    

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return new PasswordAuthentication("UserName@gmail.com", "Password");
            }
        });
       
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
          
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("Message delevered.");
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
   
    public static Authenticator getAuthentication(final String userName, final String password){
        Authenticator authenticator = null;
        authenticator = new Authenticator() {
            private PasswordAuthentication passwordAuthentication = new PasswordAuthentication(userName, password);
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return passwordAuthentication;
            }
        };
       
         return authenticator;
    }
}

Fetch the Inbox Mails with Attachments sepratly

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;

public class AttachmentReader {

    public static void parsemessage(Message message) throws MessagingException, IOException {
          System.out.println( "<"+message.getFrom()[0] + "> " + message.getSubject());
          Multipart multipart = (Multipart)message.getContent();
          System.out.println("     > Message has "+multipart.getCount()+" multipart elements");
            for (int j = 0; j < multipart.getCount(); j++) {
                BodyPart bodyPart = multipart.getBodyPart(j);
                if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) {
                        MimeMultipart mimemultipart = (MimeMultipart)bodyPart.getContent();
                        System.out.println("Number of embedded multiparts "+mimemultipart.getCount());
                        for (int k=0;k<mimemultipart.getCount();k++) {
                            if (mimemultipart.getBodyPart(k).getFileName() != null) {
                                System.out.println("     > Creating file with name : "+mimemultipart.getBodyPart(k).getFileName());
                                savefile(mimemultipart.getBodyPart(k).getFileName(), mimemultipart.getBodyPart(k).getInputStream());
                            }
                        }
                    }
                  continue;
                }
                System.out.println("     > Creating file with name : "+bodyPart.getFileName());
                savefile(bodyPart.getFileName(), bodyPart.getInputStream());
            }
        }
   
   
    public static void savefile(String FileName, InputStream is) throws IOException {
        File f = new File("Attachment/" + FileName);
        FileOutputStream fos = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int bytesRead;
        while((bytesRead = is.read(buf))!=-1) {
            fos.write(buf, 0, bytesRead);
        }
        fos.close();
    }
   
    
   
public static void main(String[] args) {
 try {
final String user="userName1@gmail.com";
final    String password="Password1";
String host="pop.gmail.com";
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");

props.put("mail.pop3.user", user);

props.put("mail.pop3.socketFactory", 995);

props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.put("mail.pop3.port", 995);
    Session session = Session.getInstance(props,
                 new javax.mail.Authenticator() {
                   
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
   
 
Store store = session.getStore("pop3");
 store.connect("pop.gmail.com",user,password);
 System.out.println("Connected");
 Folder folder = store.getFolder("inbox"); 
        folder.open(Folder.READ_WRITE); 
    
        Message[] message = folder.getMessages(); 
       
        System.out.println("Connected");
        System.out.println(message.length);
      //  for (int a = message.length; a>0; a--) {
        for (int a = 0; a < message.length; a++) { 
            System.out.println("-------------" + (a + 1) + "-----------"); 
            System.out.println(message[a].getSentDate()); 
            System.out.println(message[a].getSubject()); 
           
           // String pp=message[a].getSentDate().toString();
         //   System.out.println(pp+"       Ye hai date ");
           //String tt=message[a].getSubject();
           //String det=pp.substring(0, 20);
            message[a].writeTo(new FileOutputStream("Inbox/"+message[a].getFrom().toString()+".txt",true));
           // message[a].getFrom().toString()
           parsemessage(message[a]);
      
       
        }
       

 } catch (Exception e) {

e.printStackTrace();

}    
}

}

PDF TO DOC Converion with itext api in JAVA

 import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import com.lowagie.text.Document; import com.lowagie.text.Paragraph;

import com.lowagie.text.rtf.RtfWriter2;
public class App {

public static void main(String[] args) {
    try {

        Document document = new Document();

        File  file = new File("Target/file.doc");
        if(!file.exists())
            file.createNewFile();

        RtfWriter2.getInstance(document, new FileOutputStream("Target/file.doc"));
        System.out.println("file created");
        document.open();

    PdfReader reader = new PdfReader("Source/recommendation.pdf");
    int n = reader.getNumberOfPages();
    System.out.println("total no of pages:::"+n);
    String s="";
    for(int i=1;i<=n;i++)
    {

        s=PdfTextExtractor.getTextFromPage(reader, i);


        System.out.println("string:::"+s);
        System.out.println("====================");

        document.add(new Paragraph(s));
        document.newPage();
    }
    document.close();
    System.out.println("completed");
    } catch (Exception de) {}
    }

}