Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.14 KB | None | 0 0
  1. package net.eqtconsulting.dam.sftp.transformer;
  2.  
  3. import java.io.File;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7.  
  8. import org.apache.commons.logging.Log;
  9.  
  10. import com.artesia.common.exception.BaseTeamsException;
  11. import com.artesia.server.transformer.ExportJobTransformationResult;
  12. import com.artesia.server.transformer.impl.AbstractManagedDirectoryDeliveryTransformer;
  13. import com.artesia.transformer.TransformerInstance;
  14. import com.artesia.transformer.TransformerInstanceValue;
  15. import com.jcraft.jsch.JSchException;
  16. import com.jcraft.jsch.SftpException;
  17. import com.jcraft.jsch.SftpProgressMonitor;
  18.  
  19. import net.eqtconsulting.dam.sftp.utils.EQTSftpProgressMonitor;
  20. import net.eqtconsulting.dam.sftp.utils.FTPSUtils;
  21. import net.eqtconsulting.dam.sftp.utils.SFTPUtils;
  22. import net.eqtconsulting.log.EqtLogger;
  23.  
  24. public class SendSFTPCambioNombre extends AbstractManagedDirectoryDeliveryTransformer {
  25.  
  26.     private static final String VERSION = "20161007-1200";
  27.     private static final Log log = new EqtLogger(SendSFTPCambioNombre.class, VERSION);
  28.  
  29.     // private static final String PATH = System.getenv("TEAMS_HOME") +
  30.     // "/deploy/";
  31.     // private static final String CONFIG_FILE = PATH +
  32.     // "sendSFTPTransformer.properties";
  33.  
  34.     private static final String TRANSFORMATION_SUCCESSFUL_ERROR_CODE = "FSWS_OK";
  35.  
  36.     /* PROPIEDADES DE LA CLASE */
  37.     private String sftp_user = null;
  38.     private String sftp_pass = null;
  39.     private String sftp_host = null;
  40.     private String sftp_port = null;
  41.     private String sftp_protocol = null;
  42.     private String sftp_destination_directory = null;
  43.  
  44.     private String send_file_xml = null;
  45.     private String new_filename = null;
  46.     private String sftp_send_exception_ok = null;
  47.  
  48.     private String defaultAssetPropertiesFileXML = "assetProperties.xml";
  49.  
  50.     private Map<String, File> mapFiles;
  51.  
  52.     private String results = null;
  53.  
  54.     public ExportJobTransformationResult performDelivery(TransformerInstance paramTransformerInstance,
  55.             List<File> fileList, boolean bool) throws BaseTeamsException {
  56.         return performDelivery(paramTransformerInstance, fileList);
  57.     }
  58.  
  59.     @Override
  60.     protected ExportJobTransformationResult performDelivery(TransformerInstance paramTransformerInstance,
  61.             List<File> fileList) throws BaseTeamsException {
  62.  
  63.         log.debug("<<< performDelivery");
  64.         String messageID = null;
  65.         String message = null;
  66.         Exception catchedException = null;
  67.         this.results = null;
  68.         this.mapFiles = new HashMap<String, File>();
  69.         try {
  70.             this.handleArgParameters(paramTransformerInstance, fileList);
  71.             this.showTrace(paramTransformerInstance, fileList);
  72.             for (String f : this.mapFiles.keySet()) {
  73.                 log.debug(">>>>>>>>>>>>>>>>File to send " + f + " - " + this.mapFiles.get(f));
  74.             }
  75.             this.sendFilesToSFTP();
  76.         } catch (SendSFTPCambioNombreException e) {
  77.             log.warn("Catched SendSFTPTransformerException: " + e.getMessage());
  78.             messageID = "ERROR_ENVIANDO_ARCHIVOS";
  79.             message = e.getMessage();
  80.             catchedException = e;
  81.         } catch (NumberFormatException e) {
  82.             log.warn("Catched NumberFormatException: " + e.getMessage());
  83.             messageID = "NUMBER_FORMAT_EXCEPTION";
  84.             message = e.getMessage();
  85.             catchedException = e;
  86.         } catch (SftpException e) {
  87.             log.warn("Catched SftpException: " + e.getMessage());
  88.             messageID = "SFTP_EXCEPTION";
  89.             message = e.getMessage();
  90.             catchedException = e;
  91.         } catch (JSchException e) {
  92.             log.warn("Catched JSchException: " + e.getMessage());
  93.             messageID = "JSCH_EXCEPTION";
  94.             message = e.getMessage();
  95.             catchedException = e;
  96.         } finally {
  97.             if (results != null) {
  98.                 messageID = TRANSFORMATION_SUCCESSFUL_ERROR_CODE;
  99.                 catchedException = null;
  100.                 // success = true;
  101.             } else {
  102.                 // success = false;
  103.             }
  104.         }
  105.         if (catchedException == null) {
  106.             log.trace("<<<PerformDelivery OK");
  107.             if (this.sftp_send_exception_ok.equals("TRUE")) {
  108.                 throw new BaseTeamsException(messageID, message);
  109.             }
  110.         } else {
  111.             log.trace("<<<PerformDelivery with error");
  112.             throw new BaseTeamsException(messageID, message, catchedException);
  113.         }
  114.  
  115.         Boolean success;
  116.         if (this.results.equals("OK")) {
  117.             success = true;
  118.         } else {
  119.             success = false;
  120.         }
  121.  
  122.         ExportJobTransformationResult transformResult = new ExportJobTransformationResult(success);
  123.         transformResult.setTransformedFiles(fileList);
  124.         for (File f : fileList) {
  125.             log.debug("Sent File " + f.getName());
  126.  
  127.         }
  128.         log.debug("<<< End result2: " + transformResult.toString() + " ------------ " + this.results + "|-"
  129.                 + fileList.size() + "|");
  130.  
  131.         return transformResult;
  132.     }
  133.  
  134.     public void sendFilesToSFTP()
  135.             throws NumberFormatException, SftpException, JSchException, SendSFTPCambioNombreException {
  136.         log.debug("Inicio exportacion archivos");
  137.         // String message = null;
  138.         String messageError = null;
  139.         try {
  140.             if (this.sftp_protocol.equalsIgnoreCase("SSH")) {
  141.                 log.debug("Enviando archivos por SSH");
  142.                 SFTPUtils sftpUtils = new SFTPUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
  143.                         sftp_destination_directory);
  144.                 SftpProgressMonitor sftpProgressMonitor = new EQTSftpProgressMonitor();
  145.                 this.results = sftpUtils.uploadFilesToSFTP(mapFiles, sftpProgressMonitor);
  146.             } else if (this.sftp_protocol.equalsIgnoreCase("SSL")) {
  147.                 log.debug("Enviando archivos por FTP sobre SSL");
  148.                 FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
  149.                         sftp_destination_directory, sftp_protocol);
  150.                 this.results = ftpsUtils.exportFilesToFTPS(mapFiles);
  151.             } else if (this.sftp_protocol.equalsIgnoreCase("TLS")) {
  152.                 log.debug("Enviando archivos por FTP sobre TLS");
  153.                 FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
  154.                         sftp_destination_directory, sftp_protocol);
  155.                 this.results = ftpsUtils.exportFilesToFTPS(mapFiles);
  156.             } else if (this.sftp_protocol.equalsIgnoreCase("FTP")) {
  157.                 log.debug("Enviando archivos por FTP");
  158.                 FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
  159.                         sftp_destination_directory, sftp_protocol);
  160.                 this.results = ftpsUtils.exportFilesToFTP(mapFiles);
  161.             } else {
  162.                 log.debug("Enviando archivos por " + this.sftp_protocol);
  163.                 messageError = "Protocolo no Reconocido";
  164.                 log.error(messageError);
  165.             }
  166.         } catch (NumberFormatException e) {
  167.             log.error("NumberFormatException: " + e.getMessage());
  168.             messageError = "NumberFormatException";
  169.             throw e;
  170.         } catch (SftpException e) {
  171.             log.error("SftpException: " + e.getMessage());
  172.             messageError = "SftpException";
  173.             throw e;
  174.         } catch (JSchException e) {
  175.             log.error("JSchException: " + e.getMessage());
  176.             messageError = "JSchException";
  177.             throw e;
  178.         }
  179.         if (this.results == null) {
  180.             log.error("Error enviando archivos : " + messageError);
  181.             throw new SendSFTPCambioNombreException("Error enviando archivos : " + messageError);
  182.         } else {
  183.             this.results = "OK";
  184.         }
  185.         log.debug("<<< Results value >>> ------------ " + this.results + "|");
  186.     }
  187.  
  188.     /**
  189.      * Retrieves parameters from arguments for this export job execution
  190.      *
  191.      * @param paramTransformerInstance
  192.      * @param fileList
  193.      * @throws SendSFTPCambioNombreException
  194.      */
  195.     private void handleArgParameters(TransformerInstance paramTransformerInstance, List<File> fileList)
  196.             throws SendSFTPCambioNombreException {
  197.         log.trace(">>>handleArgParameters");
  198.         /* SART OBTAINING DESIRED PARAMS */
  199.         log.info("Obtaining execution arguments...");
  200.         for (TransformerInstanceValue valor : paramTransformerInstance.getAttributeValues()) {
  201.             if (paramTransformerInstance.getAttributeValues().size() > 0) {
  202.                 switch (valor.getArgumentNumber()) {
  203.                 case 1:
  204.                     this.sftp_host = valor.getValue();
  205.                     log.trace("Leido host: " + this.sftp_host);
  206.                     break;
  207.                 case 2:
  208.                     this.sftp_port = valor.getValue();
  209.                     log.trace("Leido puerto: " + this.sftp_port);
  210.                     break;
  211.                 case 3:
  212.                     this.sftp_user = valor.getValue();
  213.                     log.trace("Leido usuario: " + this.sftp_user);
  214.                     break;
  215.                 case 4:
  216.                     this.sftp_pass = valor.getValue();
  217.                     log.trace("Leido password: " + this.sftp_pass);
  218.                     break;
  219.                 case 5:
  220.                     this.sftp_destination_directory = valor.getValue();
  221.                     log.trace("Leido directorio de destino: " + this.sftp_destination_directory);
  222.                     break;
  223.                 case 6:
  224.                     this.sftp_protocol = valor.getValue();
  225.                     log.trace("Leido protocolo: " + this.sftp_protocol);
  226.                     break;
  227.                 case 7:
  228.                     this.send_file_xml = valor.getValue();
  229.                     log.trace("Leido envio xml S/N: " + this.send_file_xml);
  230.                     break;
  231.                 case 8:
  232.                     this.new_filename = valor.getValue();
  233.                     log.trace("Leido nuevo nombre de fichero: " + this.new_filename);
  234.                     break;
  235.                 case 9:
  236.                     this.sftp_send_exception_ok = valor.getValue();
  237.                     log.trace("Leido send Exception: " + this.sftp_send_exception_ok);
  238.                     break;
  239.                 default:
  240.                     log.warn("Unknown transformer instance value received and ignored: " + valor.getArgumentNumber()
  241.                             + " - " + valor.getValue());
  242.                     break;
  243.                 }
  244.             } else {
  245.                 log.error("Unknown transformer instance values received.");
  246.             }
  247.         }
  248.         int fileNameNum = 0;
  249.         for (File f : fileList) {
  250.             if (f.getName().equalsIgnoreCase(defaultAssetPropertiesFileXML)
  251.                     && extractFileNameExtension(f.getName()) != null
  252.                     && extractFileNameExtension(f.getName()).equalsIgnoreCase("xml")) {
  253.                 log.trace("EQT - Nombre fichero xml: " + f.getName());
  254.                 // Tratamos el fichero de propiedades xml
  255.                 if (send_file_xml != null && send_file_xml.equalsIgnoreCase("S")) {
  256.                     log.trace("EQT - send_file_xml: " + send_file_xml);
  257.                     if (new_filename != null && !new_filename.trim().equalsIgnoreCase("")) {
  258.                         log.trace("EQT - nuevo nombre XML: " + extractFilename(new_filename) + ".xml");
  259.                         mapFiles.put(extractFilename(new_filename) + ".xml", f);
  260.                     } else {
  261.                         log.trace("EQT - antiguo nombre XML: " + f.getName());
  262.                         mapFiles.put(f.getName(), f);
  263.                     }
  264.                 }
  265.             } else {
  266.                 if (new_filename != null && !new_filename.trim().equalsIgnoreCase("")) {
  267.                     log.trace("EQT - nuevo nombre contenigo: " + new_filename);
  268.                     if (fileNameNum > 0) {
  269.                         String fileNameNoExt = extractFilename(new_filename);
  270.                         String fileNameExt = extractFileNameExtension(new_filename) != null
  271.                                 ? extractFileNameExtension(new_filename) : "";
  272.                         mapFiles.put(fileNameNoExt + fileNameNum + "." + fileNameExt, f);
  273.                         log.debug(">>>>>>>>>>>>>>>>>>Added file1: " + fileNameNoExt);
  274.                     } else {
  275.                         mapFiles.put(new_filename, f);
  276.                         log.debug(">>>>>>>>>>>>>>>>>>Added file1: " + new_filename);
  277.                     }
  278.                     fileNameNum++;
  279.                 } else {
  280.                     log.trace("EQT - nuevo nombre contenido: " + new_filename);
  281.                     mapFiles.put(f.getName(), f);
  282.                     log.debug(">>>>>>>>>>>>>>>>>>Added file3: " + f.getName());
  283.                 }
  284.             }
  285.         }
  286.         if (mapFiles.size() == 0) {
  287.             log.trace("No se han encontrado archivos!");
  288.             SendSFTPCambioNombreException excepcio = new SendSFTPCambioNombreException("ERROR_FST_NO_FILE_RECEIVED");
  289.             excepcio.fillInStackTrace();
  290.             throw excepcio;
  291.         } else {
  292.             log.trace("Varios archivos encontrados!");
  293.             log.trace("files:");
  294.             for (String key : mapFiles.keySet()) {
  295.                 log.trace("- file: " + mapFiles.get(key).getAbsolutePath());
  296.                 log.trace("-- size: " + mapFiles.get(key).length() + " | " + (mapFiles.get(key).length() / (1024))
  297.                         + " (kB) | " + (mapFiles.get(key).length() / (1024 * 1024)) + " (MB)");
  298.             }
  299.         }
  300.         log.trace("<<<handleArgParameters");
  301.     }
  302.  
  303.     /**
  304.      * Muestra contenidos de variables y constantes para saber que necesitamos
  305.      * coger
  306.      *
  307.      * @param paramTransformerInstance
  308.      * @param fileList
  309.      */
  310.     private void showTrace(TransformerInstance paramTransformerInstance, List<File> fileList) {
  311.         if (log.isTraceEnabled()) {
  312.             log.trace(
  313.                     "====== Class Constants:===============================================================================");
  314.             log.trace("- VERSION: " + VERSION);
  315.             log.trace(
  316.                     "====== End of Class Constants ========================================================================");
  317.             log.trace(
  318.                     "====== Instance variables:============================================================================");
  319.             log.trace("- getValueMap:");
  320.             log.trace(
  321.                     "====== End of instance variables:=====================================================================");
  322.             log.trace(
  323.                     "====== Arguments received:============================================================================");
  324.             log.trace("- paramTransformerInstance:");
  325.             log.trace("-- getId: " + paramTransformerInstance.getId().asString());
  326.             log.trace("-- getTransformerId: " + paramTransformerInstance.getTransformerId());
  327.             log.trace("-- getName: " + paramTransformerInstance.getName());
  328.             log.trace("-- getDescription: " + paramTransformerInstance.getDescription());
  329.             log.trace("-- getAttributesValues:");
  330.             for (TransformerInstanceValue iValue : paramTransformerInstance.getAttributeValues()) {
  331.                 log.trace("--- getArgumentNumber: " + iValue.getArgumentNumber());
  332.                 log.trace("--- getValue: " + iValue.getValue());
  333.             }
  334.             log.trace("- fileList:");
  335.             for (File f : fileList) {
  336.                 log.trace("-- getAbsolutePath: " + f.getAbsolutePath());
  337.                 log.trace("-- getName: " + f.getName());
  338.                 log.trace("-- length: " + f.length() + " bytes");
  339.             }
  340.             log.trace(
  341.                     "====== End of arguments ==============================================================================");
  342.         }
  343.     }
  344.  
  345.     // private String parseResults(){
  346.     //
  347.     //
  348.     //
  349.     // return"";
  350.     // }
  351.  
  352.     /**
  353.      * Extracts extension from the file name. Dot is not included in the
  354.      * returned string.
  355.      *
  356.      * @param fileName
  357.      *            File name
  358.      * @return File extension
  359.      */
  360.     private String extractFileNameExtension(String fileName) {
  361.         int dotInd = fileName.lastIndexOf('.');
  362.         // if dot is in the first position,
  363.         // we are dealing with a hidden file rather than an extension
  364.         return (dotInd > 0 && dotInd < fileName.length()) ? fileName.substring(dotInd + 1) : null;
  365.     }
  366.  
  367.     private static String extractFilename(String fileName) {
  368.         int dotInd = fileName.lastIndexOf('.');
  369.         if (dotInd < 0) {
  370.             return fileName;
  371.         }
  372.         // if dot is in the first position,
  373.         // we are dealing with a hidden file rather than an extension
  374.         return (dotInd > 0 && dotInd < fileName.length()) ? fileName.substring(0, dotInd) : null;
  375.     }
  376.  
  377. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement