Skip to Content

Java mapping: To make changes to file placed in FTP location.

This code will help to copy(download) the file from source ftp location and perform some operation and place the file in the local target folder. I am not sure whether this idea can be used in generalised cases but it helps in a specific cases. In our project we had a scenario when we needed to carry on this action parallelly so we opted for java mapping to connect to FTP server to download files.


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;


public class FTPDownloader extends AbstractTransformation{

FTPClient ftpObj = null;
String usrName = “”;
String pswd = “”;
String serverAdd = “”;
String srcLoc = “”;
String trgLoc = “”;
String fileName = “”;
int reply;

@Override
public void transform(TransformationInput arg0, TransformationOutput arg1)
   throws StreamTransformationException {

     // Dynamic configuration — values will be passed through interface determination.

  usrName = arg0.getInputParameters().getString(“USERNAME”);
  pswd = arg0.getInputParameters().getString(“PASSWD”);
  serverAdd = arg0.getInputParameters().getString(“SERVERADD”);
  srcLoc = arg0.getInputParameters().getString(“SOURCE”);
  trgLoc = arg0.getInputParameters().getString(“TARGET”);
  fileName = arg0.getInputParameters().getString(“FILENAME”);
 
  // getTrace().addInfo(“Input Parameter: ” + usrName + “::” + serverAdd + “::” + fileName);

  ftpObj = new FTPClient();
  getTrace().addInfo(“FTP Connection Initiated– server :: ” + serverAdd);
  String response = Connect();
  getTrace().addInfo(response);
 
  if(FTPReply.isPositiveCompletion(reply)){
   getTrace().addInfo(“Download started :: ” + fileName);
   response = download();
   getTrace().addInfo(response);
  } else {
   getTrace().addInfo(response);
   response = “Connection Failed”;
  }
 
 
  // For setting the output argument
  String StartString = “<?xml version=\”1.0\” encoding=\”UTF-8\”?>”;
  String DocumentNameSpace = “<ns0:MT_Trigger xmlns:ns0=\”urn:test:com:test:test:test\”>”;
  String RemainingString = “<Record><Dummy/></Record></ns0:MT_Trigger>”;
  String outData = StartString + DocumentNameSpace + RemainingString;
  
  try {
   arg1.getOutputPayload().getOutputStream().write(outData.getBytes(“UTF-8”));
  } catch (IOException e) {
   e.printStackTrace();
  }

}

// To connect to the FTP server
public String Connect(){
  String response = “”;
  try {
  
    // connecting FTP server
   ftpObj.connect(serverAdd);
   reply = ftpObj.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    response = “FTP server refused connection”;
    ftpObj.disconnect();
   }else
    response = “FTP Connection Establised”;
  
    // User Authentication Started
   ftpObj.login(usrName,pswd);
   reply = ftpObj.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    response = response + ” User NOT Authenticated “;
    ftpObj.disconnect();
   }else{
    response = response + ” User Authenticated “;
   } 
  } catch (SocketException ex) {
   response = “Connection Failed :: Socket Exception :: ” + ex.toString();
   ex.printStackTrace();
  } catch (IOException ex) {
   response = “Connection Failed :: Input/Output Exception :: ” + ex.toString();
   ex.printStackTrace();
  } catch (Exception e){
   response = “Connection Failed :: General Exception :: ” + e.toString();
   e.printStackTrace();
  }
  return response;
}

// To download a file from the source location.

public synchronized String download(){
  String response = “”;
  String trgFilename = fileName;
  try {
    // To change the PWD(Present Working Directory)
   ftpObj.changeWorkingDirectory(srcLoc);
  
    // To copy the content from server and writing into target location
   boolean exists = (new File(“trgLoc+fileName”)).exists();

   DateFormat formatter = new SimpleDateFormat(“ddMMyyyyhhss”);
   Date dt = new Date(System.currentTimeMillis());
   // To remove redundancy of file
   if (exists){
    response = “duplilcate entry found”;
    trgFilename = fileName + formatter.format(dt) ;
   }
  
   File file = new File(trgLoc+trgFilename);
   FileOutputStream fStream = new FileOutputStream(file);
   ftpObj.retrieveFile(fileName,fStream);
   fStream.close();
   ftpObj.disconnect();
   response = “Download Successful”;
  }catch(IOException e){
   response = “Download Failed ::  Input/Output Exception :: ” + e.toString();
  }catch(Exception e){
   response = “Download Failed :: General Exception :: ” + e.toString();
  }
  return response;
}

}
interfaceDet.jpg

thank and regards,

Praveen T

2 Comments
You must be Logged on to comment or reply to a post.
  • import java.io.BufferedReader;

    import java.io.File;

      import java.io.FileInputStream;

      import java.io.FileOutputStream;

      import java.io.IOException;

      import java.io.InputStream;

      import java.io.InputStreamReader;

      import java.io.OutputStream;

      import java.util.Map;

      import com.sap.aii.mapping.api.StreamTransformation;

      import com.sap.aii.mapping.api.AbstractTrace;

      import com.sap.aii.mapping.api.StreamTransformationException;

      import java.util.HashMap;

      import org.apache.commons.net.ftp.FTPClient;

      import org.apache.commons.net.ftp.FTPReply;

      public class FTPTest implements StreamTransformation {

      private Map map = null;

      private AbstractTrace trace = null;

      public void setParameter(Map arg0) {

      map = arg0;   // Store reference to the mapping parameters

      if (map == null) {

      this.map = new HashMap();

      }

      }

      /*public static void main(String args[]) {  //FOR EXTERNAL STANDALONE TESTING

      try{

      FileInputStream fin = new FileInputStream(“C:/Users/ashutosh.a.upadhyay/Desktop/Data.xml”);

      FileOutputStream  fout = new FileOutputStream  (“C:/Users/ashutosh.a.upadhyay/My Documents/ashuXML2.xml”); //OUTPUT FILE (PAYLOAD)

      FTPTest mapping = new FTPTest ();

      mapping.execute(fin, fout);

      }

      catch (Exception e1){

      e1.printStackTrace();

      }

      }*/

        

      public void execute(InputStream inputstream, OutputStream outputstream) throws StreamTransformationException  {

      try{

      String text = “”;

      String line = “”;

      System.out.println(inputstream.toString());

      InputStreamReader in = new InputStreamReader(inputstream);

      BufferedReader bin = new BufferedReader(in);

      while((line = bin.readLine()) != null){

      System.out.println(line);

      text = text+line;

      text = text+”\n”;

      }

      System.out.println(text);

      outputstream.write(text.getBytes());

      FTPClient client = new FTPClient();

      client.connect(“<FTPServerName>”);

      int reply = client.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {

      //trace.addInfo(“FTP server refused connection”);

      System.out.println(“FTP server refused connection”);

      client.disconnect();

      }

      else{

      //trace.addInfo(“FTP Connection Establised”);

      System.out.println(“FTP Connection Establised”);

      }

      client.login(“anonymous”, “”);

      reply = client.getReplyCode();

      if (!FTPReply.isPositiveCompletion(reply)) {

      System.out.println(“User NOT Authenticated “);

      client.disconnect();

      }

      else{

      //trace.addInfo(“User Authenticated “);

      System.out.println(“User Authenticated “);

      }

      client.changeWorkingDirectory(“<Directory>”);

      System.out.println(“Directory searched”);

      String remoteFile = “test.xml”;       

      System.out.println(“Start uploading file…”);  

    OutputStream outputStream = client.storeFileStream(remoteFile);

      outputStream.write(text.getBytes());

      outputStream.close();

      in.close();

      bin.close();

      outputstream.close();

      inputstream.close();

      boolean done = client.completePendingCommand();

    if (done){

      //trace.addInfo(“The file is uploaded successfully.”);       

      System.out.println(“The file is uploaded successfully.”);    

      }

      else{

      //trace.addInfo(“The file is not uploaded.”);

        System.out.println(“The file is not uploaded.”);

      }

      client.disconnect();

      //trace.addInfo(“FTP connection disconnected”);

      System.out.println(“FTP connection disconnected”);

      //writing output file

      in.close();

      bin.close();

      outputstream.close();

      inputstream.close();

      }

               

      //Code to Transform the Input stream to Output

      catch (IOException e) {

      e.printStackTrace();

      throw new StreamTransformationException(“Can not read XML. “+ e.getMessage(), e);

      }

      catch(Exception e){

      e.printStackTrace();

      throw new StreamTransformationException(“General Exception :: “+ e.getMessage(), e);

      }

      }

      }