Thursday, July 20, 2017

Compile JAVA file in UNIX including dependent JAR files

javac -classpath /12.0.0/java/app/util/ojdbc14.jar:/12.0.0/java/app/util/commons-vfs2-2.0.jar:/12.0.0/java/app/util/commons-logging-1.2.jar:/12.0.0/java/app/util/bcprov-jdk15on-157.jar:/12.0.0/java/app/util/jsch-0.1.54.jar:/12.0.0/java/app/util/commons-vfs2-2.0-sources.jar  HelloSFTP.java


javac -classpath 'path where jar file exists' HelloSFTP.java

Wednesday, October 19, 2016

SFTP to remote UNIX box JAVA

Here is a sample code to SFTP all files from the local folder to a remote folder
Our code should create the folder in the remote box if the folder doesn't exist already




import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import java.io.Serializable;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.faces.context.FacesContext;


import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.share.ADFContext;



import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import oracle.jbo.Row;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
    private void transfer() {


        StandardFileSystemManager manager = new StandardFileSystemManager();
        System.out.println("this.getSelectedCompany()" + this.getSelectedCompany());
        ADFContext adfCtx = ADFContext.getCurrent();
        Map pageFlowScope = adfCtx.getPageFlowScope();

        try {

            String serverAddress = "**host_ip_address**";
            String userId = "**userID**";
     
            String password = "**password**";


    
         
            String remoteDirectory =
                "/a//b//c//d//e//f//outbound//xyz//vijay//" +
                pageFlowScope.get("company").toString() + "//";

     

            String localDirectory =
                "//i//j//k//l//m//n//" +
                pageFlowScope.get("company").toString() + "//";
            File dir = new File(localDirectory);
         
   File[] directoryListing = dir.listFiles();
         

   if (directoryListing != null) {
    //Initializes the file manager
                manager.init();
             

   for (File file : directoryListing) {

                    System.out.println("1--------------" + file.getPath());

                
                    if (!file.exists())
                        file.createNewFile();
             

                                    //Setup our SFTP configuration
                    FileSystemOptions opts = new FileSystemOptions();
                    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
                    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
                    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

                    //Create the SFTP URI using the host name, userid, password,  remote path and file name
                    String sftpUri =
                        "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory +
                        file.getName();
                    // manager.resolveFile(sftpUri);
                    System.out.println("sftpUri---->" + sftpUri);
                    // Create local file object
                    FileObject localFile = manager.resolveFile(file.getAbsolutePath());
                    System.out.println("localFile---->" + localFile);
                    // Create remote file object
                    FileObject remoteFile = manager.resolveFile(sftpUri, opts);

                    // Copy local file to sftp server
                    remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);

                    System.out.println("File upload successful");


                
                }
            } else {
                // Handle the case where dir is not really a directory.
                // Checking dir.isDirectory() above would not be sufficient
                // to avoid race conditions with another process that deletes
                // directories.
                throw new RuntimeException("Error. Directory file not found");
            }



        } catch (Exception ex) {
            ex.printStackTrace();
            // return false;
        } finally {
            manager.close();
        }

       
    }

Execute Shell Script from JAVA

Deploy this java program to a unix box where java is installed

The below code would run the command you specify



import java.io.*;

public class ExportToExcel {
    public ExportToExcel() {
        super();
    }

  
    public static void main(String args[]) {
      
        ExportToExcel e = new ExportToExcel();
      
       //in UNIX

       String command = "pwd";

        String output = e.executeCommand(command);

        System.out.println(output);

     
    }


    public String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }

}


Output:


  • /home/usr/javaprogram/

Reference;
http://stackoverflow.com/questions/21598359/compiling-java-file-from-another-java-class
https://www.mkyong.com/java/how-to-execute-shell-command-from-java/

Thursday, March 31, 2016

Send E-Mail using JavaMail API

package com.fm.vj.view.utils;


import com.tangosol.dev.assembler.New;

import java.util.Properties;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;

import javax.faces.context.FacesContext;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;


import javax.mail.Transport;
import javax.mail.internet.InternetAddress;


import javax.mail.internet.MimeMessage;

import oracle.adf.share.logging.ADFLogger;

import oracle.net.aso.n;

public class SendEmailUtil {
    public static final ADFLogger LOGGER = ADFLogger.createADFLogger(SendEmailUtil.class);


    /**
     * @param to
     * @param cc
     * @param from
     * @param subject
     * @param text
     */
    public static void getUtility(String to,String cc, String from, String subject, String text) {
     

 
        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        ResourceBundle rb = ResourceBundle.getBundle("com.jnj.brvo.view.bundles.BravoAppUIBundle");
        String host = rb.getString("SMTP_HOST"); //SMTP_HOST=SMTP.NA.FM.COM
       
        properties.setProperty("mail.smtp.host", host);
        // properties.setProperty("mail.smtp.port", "25");
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
           // message.addRecipient(Message.RecipientType.TO, new InternetAddress.parse(to));
           
            if (to.indexOf(',') > 0)  
                       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));  
                   else
                       message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

            if (cc.indexOf(',') > 0)  
                       message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));  
                   else
                       message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));

            // Set Subject: header field
            message.setSubject(subject);

            // Now set the actual message
            message.setText(text);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException e) {
           
         
                        String messageText =
                            "Warning/INFO : EMail works on the BOX . Cannot be sent from local machine; The host is " + host + "";
                        FacesMessage fm = new FacesMessage(messageText);

                        fm.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext context = FacesContext.getCurrentInstance();

                        context.addMessage(null, fm);
                        e.printStackTrace();
                   
        }
    }


}

Saturday, March 14, 2015