Saturday 24 May 2014

Mail in java with multiple recipients,multiple cc with multiple file attachment

I am going to show you one simple Java program from which you can send email to multiple persons with multiple attachment,you can also add CC  to your mail from this program,
I will give you one general program which consist multiple recipients ,Multiple CC recipients and multiple file attachment
You can change it according to your preferences.


package com.sendMail;

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

    public class sendMailWithAttach {
        private static String SMTP_HOST_NAME = "smtp.gmail.com";
        private static String SMTP_PORT = "587";
        private static  String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        public static String  sendMail(String recipients[],String 
           ccrecipients[], String subject,String message, String sentfrom,
           String filepath1,String filepath2) throws MessagingException
          {
            boolean debug = true;
            String sendStatus=null;
            Properties props = new Properties();
            props.put("mail.smtp.host",SMTP_HOST_NAME);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
            props.put("mail.smtp.port",SMTP_PORT);
            props.put("mail.oyazen.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.starttls.enable", "true");
           // This block is used to create session event
            Session session = Session.getDefaultInstance(props,new
             javax.mail.Authenticator()
                  {
                    protected PasswordAuthentication getPasswordAuthentication()
                           {
                            return new
                            PasswordAuthentication("yourEmailId","password");
                            }
                    });
             // If you want to enable debug then set a session debug true,
             session.setDebug(debug);
             Message msg = new MimeMessage(session);
             InternetAddress addressFrom = new InternetAddress(sentfrom);
             msg.setFrom(addressFrom);
             InternetAddress[] addressCC = new
             InternetAddress[ccrecipients.length];
                 for (int i = 0; i < ccrecipients.length; i++)
                      {
                       addressCC[i] = new InternetAddress(ccrecipients[i]);
                      }
              msg.setRecipients(Message.RecipientType.CC,addressCC);
              InternetAddress[] addressTo = new InternetAddress[recipients.length];
                   for (int i = 0; i < recipients.length; i++)
                        {
                            addressTo[i] = new InternetAddress(recipients[i]);
                        }
               msg.setRecipients(Message.RecipientType.TO, addressTo);
               msg.setSubject(subject);
               BodyPart messageBodyPart1 = new MimeBodyPart();
               BodyPart messageBodyPart2 = new MimeBodyPart();
               BodyPart messageBodyPart3 = new MimeBodyPart();
               Multipart multipart = new MimeMultipart();
               MimeBodyPart htmlPart = new MimeBodyPart();
               htmlPart.setContent(message, "text/html");
                  multipart.addBodyPart(htmlPart);
                  //Creating config for two file
               FileDataSource fileDataSource1 =new FileDataSource(filepath1);
               messageBodyPart1.setDataHandler(new  
               DataHandler(fileDataSource1));
               messageBodyPart1.setFileName("FileFirst");
               multipart.addBodyPart(messageBodyPart1);
               FileDataSource fileDataSource2 =new FileDataSource(filepath2);
               messageBodyPart2.setDataHandler(new 
              DataHandler(fileDataSource2));
               messageBodyPart2.setFileName("FileSecond");
               multipart.addBodyPart(messageBodyPart2);
               msg.setContent(multipart);
                  try {
                       Transport.send(msg);
                       sendStatus="Mail Succes";
                       }
                       catch(Exception e) {
                            e.printStackTrace();
                       }
          return sendStatus;
     }
       
/**
 * Main method
 * */       
    public static void main(String args[])
        {
           String recipient[]={"abc@gmail.com","xyz@gmail.com"};
           String CCrecipient[]={"CCabc@gmail.com","CCxyz@gmail.com"};
           String sentfrom="FromMe@gmail.com";
           String subject="Testing";
           String message="hello PFA";
           String filepath1="/home/amit/Key.txt";
           String filepath2="/home/amit/Key.txt";
           try {
                String result=sendMail (
                 recipient,CCrecipient,subject,message,sentfrom,filepath1,filepath2);
            }
           catch (MessagingException e) {
                e.printStackTrace();
            }
       }
    }


Please let me know if you face any issue while running this example

Thursday 22 May 2014

Works with Windows registry

Today I am going to explain how we can fetch required data from windows registry like unistalltion String,
In one of my project I followed below steps to get uninstalltion String to unistall required softwares.

If you have OS 32 then you need to read this registry to get data
HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall

or if you have OS 64
Then you need to check both
HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall
and
HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall

First way to accomplish this work
Step 1=

First we need to save registry data into a text file,you can execute this string from java class

Runtime.getRuntime().exec("reg export HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall "+"\""+ tempFile + "\"");

Step 2=
This text file consist some unreadable character so first we need to remove those,
you can put your logic to create a new file with the help of tempFile after removing unreadable character
I  used this code to get readable file

InputStreamReader input = null;
OutputStreamWriter output = null;
try {
input = new InputStreamReader(new FileInputStream(new File(tempFile)));
output = new OutputStreamWriter(new FileOutputStream(readableFile));
while (true) {
int ch = input.read();
if (ch < 0)
break;
else if ('\n' == (char) ch || ch >= 32 && ch <= 127) {
output.write(ch);

}
}


Step 3=
Now you have readable file which have data like
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\3519-9895-1195-8563]
"DisplayName"="testSoft"
"DisplayIcon"="C:\\Program Files (x86)\\testSoft-03\\.install4j\\i4j_extf_10_3zfp0v_1at2cp6.ico"
"UninstallString"="C:\\Program Files (x86)\\ntestSoft\\bin\\uninstall.exe"
"Publisher"="testSoft, Inc."
"URLInfoAbout"="http://testSoft.com"
"InstallLocation"="C:\\Program Files (x86)\\testSoft"
"DisplayVersion"="2.7.2-03"
"VersionMajor"=dword:00000002
"VersionMinor"=dword:00000007

So from this file you can fetch required value and to unistall any software  you can fetch value of UninstallString and execute  below query
Runtime.getRuntime().exec("+softPath+").waitFor();
where softPath=C:\\Program Files (x86)\\testSoft\\bin\\uninstall.exe

Second way 

You can  also use wmic to get registry data,but there is some issue with that when you use this you can see, it doesn't have data of all softwares which installed on your system,
No doubt it easy, so to get complete software data you can combine  both way in one to accomplish your work

To uninstall any software with the help of wmic

you can follow above two steps to generate readable format,you just need to change string query of first step
Runtime.getRuntime().exec("cmd /c wmic product get description >"+"\""+ tempFile + "\"");
I have used description to get software name
after that to uninstall any software  I just need to execute this String
Runtime.getRuntime().exec("wmic product where name=\'"+ description + "\' call uninstall").waitFor();

Hope it helps any one

Tuesday 20 May 2014

Get Data variation of sonar to create custom excel report

If you are using sonar for your projects and want to generate a excel report.
then you can complete this task by two way,
first one by using web API provided by sonar team
or do R & D with sonar DB(Not a standard way as mention on sonar group dashboard)

First way-
To go with web Api you can use sonar web client,
after that you can use below code to call web service for desired data.


 String url = "http://localhost:9000/";(url of Sonar)
 String login = "root";(Database user name)
 String password = "root";(Database password)
 Sonar sonar = new Sonar(new HttpClient4Connector(new Host(url, login,password)));
 Resource soanrExample= sonar.find(ResourceQuery
            .createForMetrics("projectKey", "statements"));

projectKey=You can get this from projects table or from your pom its combination of
                     <groupId>:<artifactId>

Measure statements = soanrExample.getMeasure("statements");
    System.out.println("statements : " + statements.getMetricKey()
            + " === " + statements.getFormattedValue());
like "statments" you can also pass "test" "coverage",minor_violations etc

Second Way-

As I am facing issue with variations I am not able to get variation data through web API(which shows in bracket 73 statements(+4))

So for this I did some work on DB part.
These are some steps which I followed to get variation data

Step1-
Get Project key with the help of WEB API(or through DB from projects table)

Step2-
Get project_id from projects table with the help of project key

Step3-
Get period1_param,period2_param etc from snapshots table  with the help of project Id,
from here you can get variation period like 15 days or 30 days,Like this

       if(rs.getString("period1_param")!=null){
  if(rs.getString("period1_param").equalsIgnoreCase("7")){
VARIATIONCOUNT7DAYS="1";
 }
 if (rs.getString("period1_param").equalsIgnoreCase("30")) {
VARIATIONCOUNT30DAYS="1";
 }
  }

Step4-
Use this query to generate data per project

select distinct proj.name NAME_OF_PROJ,metric.name metric_name, metric.description Description, projdesc.value value,projdesc.variation_value_1,projdesc.variation_value_2,projdesc.variation_value_3,projdesc.variation_value_4,projdesc.variation_value_5 ,snap.created_at CREATED_DATE from projects proj inner join snapshots snap on snap.project_id=proj.id inner join " + "(select max(snap2.id) as id from snapshots snap2 where snap2.project_id  in ("+projectId+") GROUP BY snap2.project_id ) as Lookup on Lookup.id=snap.id inner join project_measures projdesc on projdesc.snapshot_id=snap.id inner join metrics metric on  projdesc.metric_id =metric.id where  metric.id between '1' and "+metricid_Count+'

This query gives you all required data with the variation value,
You can put additional logic  to get compare variation for different period,

Hope this help any one.
Let me know if I miss anything