Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.eqtconsulting.dam.sftp.transformer;
- import java.io.File;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.commons.logging.Log;
- import com.artesia.common.exception.BaseTeamsException;
- import com.artesia.server.transformer.ExportJobTransformationResult;
- import com.artesia.server.transformer.impl.AbstractManagedDirectoryDeliveryTransformer;
- import com.artesia.transformer.TransformerInstance;
- import com.artesia.transformer.TransformerInstanceValue;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.SftpException;
- import com.jcraft.jsch.SftpProgressMonitor;
- import net.eqtconsulting.dam.sftp.utils.EQTSftpProgressMonitor;
- import net.eqtconsulting.dam.sftp.utils.FTPSUtils;
- import net.eqtconsulting.dam.sftp.utils.SFTPUtils;
- import net.eqtconsulting.log.EqtLogger;
- public class SendSFTPCambioNombre extends AbstractManagedDirectoryDeliveryTransformer {
- private static final String VERSION = "20161007-1200";
- private static final Log log = new EqtLogger(SendSFTPCambioNombre.class, VERSION);
- // private static final String PATH = System.getenv("TEAMS_HOME") +
- // "/deploy/";
- // private static final String CONFIG_FILE = PATH +
- // "sendSFTPTransformer.properties";
- private static final String TRANSFORMATION_SUCCESSFUL_ERROR_CODE = "FSWS_OK";
- /* PROPIEDADES DE LA CLASE */
- private String sftp_user = null;
- private String sftp_pass = null;
- private String sftp_host = null;
- private String sftp_port = null;
- private String sftp_protocol = null;
- private String sftp_destination_directory = null;
- private String send_file_xml = null;
- private String new_filename = null;
- private String sftp_send_exception_ok = null;
- private String defaultAssetPropertiesFileXML = "assetProperties.xml";
- private Map<String, File> mapFiles;
- private String results = null;
- public ExportJobTransformationResult performDelivery(TransformerInstance paramTransformerInstance,
- List<File> fileList, boolean bool) throws BaseTeamsException {
- return performDelivery(paramTransformerInstance, fileList);
- }
- @Override
- protected ExportJobTransformationResult performDelivery(TransformerInstance paramTransformerInstance,
- List<File> fileList) throws BaseTeamsException {
- log.debug("<<< performDelivery");
- String messageID = null;
- String message = null;
- Exception catchedException = null;
- this.results = null;
- this.mapFiles = new HashMap<String, File>();
- try {
- this.handleArgParameters(paramTransformerInstance, fileList);
- this.showTrace(paramTransformerInstance, fileList);
- for (String f : this.mapFiles.keySet()) {
- log.debug(">>>>>>>>>>>>>>>>File to send " + f + " - " + this.mapFiles.get(f));
- }
- this.sendFilesToSFTP();
- } catch (SendSFTPCambioNombreException e) {
- log.warn("Catched SendSFTPTransformerException: " + e.getMessage());
- messageID = "ERROR_ENVIANDO_ARCHIVOS";
- message = e.getMessage();
- catchedException = e;
- } catch (NumberFormatException e) {
- log.warn("Catched NumberFormatException: " + e.getMessage());
- messageID = "NUMBER_FORMAT_EXCEPTION";
- message = e.getMessage();
- catchedException = e;
- } catch (SftpException e) {
- log.warn("Catched SftpException: " + e.getMessage());
- messageID = "SFTP_EXCEPTION";
- message = e.getMessage();
- catchedException = e;
- } catch (JSchException e) {
- log.warn("Catched JSchException: " + e.getMessage());
- messageID = "JSCH_EXCEPTION";
- message = e.getMessage();
- catchedException = e;
- } finally {
- if (results != null) {
- messageID = TRANSFORMATION_SUCCESSFUL_ERROR_CODE;
- catchedException = null;
- // success = true;
- } else {
- // success = false;
- }
- }
- if (catchedException == null) {
- log.trace("<<<PerformDelivery OK");
- if (this.sftp_send_exception_ok.equals("TRUE")) {
- throw new BaseTeamsException(messageID, message);
- }
- } else {
- log.trace("<<<PerformDelivery with error");
- throw new BaseTeamsException(messageID, message, catchedException);
- }
- Boolean success;
- if (this.results.equals("OK")) {
- success = true;
- } else {
- success = false;
- }
- ExportJobTransformationResult transformResult = new ExportJobTransformationResult(success);
- transformResult.setTransformedFiles(fileList);
- for (File f : fileList) {
- log.debug("Sent File " + f.getName());
- }
- log.debug("<<< End result2: " + transformResult.toString() + " ------------ " + this.results + "|-"
- + fileList.size() + "|");
- return transformResult;
- }
- public void sendFilesToSFTP()
- throws NumberFormatException, SftpException, JSchException, SendSFTPCambioNombreException {
- log.debug("Inicio exportacion archivos");
- // String message = null;
- String messageError = null;
- try {
- if (this.sftp_protocol.equalsIgnoreCase("SSH")) {
- log.debug("Enviando archivos por SSH");
- SFTPUtils sftpUtils = new SFTPUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
- sftp_destination_directory);
- SftpProgressMonitor sftpProgressMonitor = new EQTSftpProgressMonitor();
- this.results = sftpUtils.uploadFilesToSFTP(mapFiles, sftpProgressMonitor);
- } else if (this.sftp_protocol.equalsIgnoreCase("SSL")) {
- log.debug("Enviando archivos por FTP sobre SSL");
- FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
- sftp_destination_directory, sftp_protocol);
- this.results = ftpsUtils.exportFilesToFTPS(mapFiles);
- } else if (this.sftp_protocol.equalsIgnoreCase("TLS")) {
- log.debug("Enviando archivos por FTP sobre TLS");
- FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
- sftp_destination_directory, sftp_protocol);
- this.results = ftpsUtils.exportFilesToFTPS(mapFiles);
- } else if (this.sftp_protocol.equalsIgnoreCase("FTP")) {
- log.debug("Enviando archivos por FTP");
- FTPSUtils ftpsUtils = new FTPSUtils(sftp_host, sftp_port, sftp_user, sftp_pass,
- sftp_destination_directory, sftp_protocol);
- this.results = ftpsUtils.exportFilesToFTP(mapFiles);
- } else {
- log.debug("Enviando archivos por " + this.sftp_protocol);
- messageError = "Protocolo no Reconocido";
- log.error(messageError);
- }
- } catch (NumberFormatException e) {
- log.error("NumberFormatException: " + e.getMessage());
- messageError = "NumberFormatException";
- throw e;
- } catch (SftpException e) {
- log.error("SftpException: " + e.getMessage());
- messageError = "SftpException";
- throw e;
- } catch (JSchException e) {
- log.error("JSchException: " + e.getMessage());
- messageError = "JSchException";
- throw e;
- }
- if (this.results == null) {
- log.error("Error enviando archivos : " + messageError);
- throw new SendSFTPCambioNombreException("Error enviando archivos : " + messageError);
- } else {
- this.results = "OK";
- }
- log.debug("<<< Results value >>> ------------ " + this.results + "|");
- }
- /**
- * Retrieves parameters from arguments for this export job execution
- *
- * @param paramTransformerInstance
- * @param fileList
- * @throws SendSFTPCambioNombreException
- */
- private void handleArgParameters(TransformerInstance paramTransformerInstance, List<File> fileList)
- throws SendSFTPCambioNombreException {
- log.trace(">>>handleArgParameters");
- /* SART OBTAINING DESIRED PARAMS */
- log.info("Obtaining execution arguments...");
- for (TransformerInstanceValue valor : paramTransformerInstance.getAttributeValues()) {
- if (paramTransformerInstance.getAttributeValues().size() > 0) {
- switch (valor.getArgumentNumber()) {
- case 1:
- this.sftp_host = valor.getValue();
- log.trace("Leido host: " + this.sftp_host);
- break;
- case 2:
- this.sftp_port = valor.getValue();
- log.trace("Leido puerto: " + this.sftp_port);
- break;
- case 3:
- this.sftp_user = valor.getValue();
- log.trace("Leido usuario: " + this.sftp_user);
- break;
- case 4:
- this.sftp_pass = valor.getValue();
- log.trace("Leido password: " + this.sftp_pass);
- break;
- case 5:
- this.sftp_destination_directory = valor.getValue();
- log.trace("Leido directorio de destino: " + this.sftp_destination_directory);
- break;
- case 6:
- this.sftp_protocol = valor.getValue();
- log.trace("Leido protocolo: " + this.sftp_protocol);
- break;
- case 7:
- this.send_file_xml = valor.getValue();
- log.trace("Leido envio xml S/N: " + this.send_file_xml);
- break;
- case 8:
- this.new_filename = valor.getValue();
- log.trace("Leido nuevo nombre de fichero: " + this.new_filename);
- break;
- case 9:
- this.sftp_send_exception_ok = valor.getValue();
- log.trace("Leido send Exception: " + this.sftp_send_exception_ok);
- break;
- default:
- log.warn("Unknown transformer instance value received and ignored: " + valor.getArgumentNumber()
- + " - " + valor.getValue());
- break;
- }
- } else {
- log.error("Unknown transformer instance values received.");
- }
- }
- int fileNameNum = 0;
- for (File f : fileList) {
- if (f.getName().equalsIgnoreCase(defaultAssetPropertiesFileXML)
- && extractFileNameExtension(f.getName()) != null
- && extractFileNameExtension(f.getName()).equalsIgnoreCase("xml")) {
- log.trace("EQT - Nombre fichero xml: " + f.getName());
- // Tratamos el fichero de propiedades xml
- if (send_file_xml != null && send_file_xml.equalsIgnoreCase("S")) {
- log.trace("EQT - send_file_xml: " + send_file_xml);
- if (new_filename != null && !new_filename.trim().equalsIgnoreCase("")) {
- log.trace("EQT - nuevo nombre XML: " + extractFilename(new_filename) + ".xml");
- mapFiles.put(extractFilename(new_filename) + ".xml", f);
- } else {
- log.trace("EQT - antiguo nombre XML: " + f.getName());
- mapFiles.put(f.getName(), f);
- }
- }
- } else {
- if (new_filename != null && !new_filename.trim().equalsIgnoreCase("")) {
- log.trace("EQT - nuevo nombre contenigo: " + new_filename);
- if (fileNameNum > 0) {
- String fileNameNoExt = extractFilename(new_filename);
- String fileNameExt = extractFileNameExtension(new_filename) != null
- ? extractFileNameExtension(new_filename) : "";
- mapFiles.put(fileNameNoExt + fileNameNum + "." + fileNameExt, f);
- log.debug(">>>>>>>>>>>>>>>>>>Added file1: " + fileNameNoExt);
- } else {
- mapFiles.put(new_filename, f);
- log.debug(">>>>>>>>>>>>>>>>>>Added file1: " + new_filename);
- }
- fileNameNum++;
- } else {
- log.trace("EQT - nuevo nombre contenido: " + new_filename);
- mapFiles.put(f.getName(), f);
- log.debug(">>>>>>>>>>>>>>>>>>Added file3: " + f.getName());
- }
- }
- }
- if (mapFiles.size() == 0) {
- log.trace("No se han encontrado archivos!");
- SendSFTPCambioNombreException excepcio = new SendSFTPCambioNombreException("ERROR_FST_NO_FILE_RECEIVED");
- excepcio.fillInStackTrace();
- throw excepcio;
- } else {
- log.trace("Varios archivos encontrados!");
- log.trace("files:");
- for (String key : mapFiles.keySet()) {
- log.trace("- file: " + mapFiles.get(key).getAbsolutePath());
- log.trace("-- size: " + mapFiles.get(key).length() + " | " + (mapFiles.get(key).length() / (1024))
- + " (kB) | " + (mapFiles.get(key).length() / (1024 * 1024)) + " (MB)");
- }
- }
- log.trace("<<<handleArgParameters");
- }
- /**
- * Muestra contenidos de variables y constantes para saber que necesitamos
- * coger
- *
- * @param paramTransformerInstance
- * @param fileList
- */
- private void showTrace(TransformerInstance paramTransformerInstance, List<File> fileList) {
- if (log.isTraceEnabled()) {
- log.trace(
- "====== Class Constants:===============================================================================");
- log.trace("- VERSION: " + VERSION);
- log.trace(
- "====== End of Class Constants ========================================================================");
- log.trace(
- "====== Instance variables:============================================================================");
- log.trace("- getValueMap:");
- log.trace(
- "====== End of instance variables:=====================================================================");
- log.trace(
- "====== Arguments received:============================================================================");
- log.trace("- paramTransformerInstance:");
- log.trace("-- getId: " + paramTransformerInstance.getId().asString());
- log.trace("-- getTransformerId: " + paramTransformerInstance.getTransformerId());
- log.trace("-- getName: " + paramTransformerInstance.getName());
- log.trace("-- getDescription: " + paramTransformerInstance.getDescription());
- log.trace("-- getAttributesValues:");
- for (TransformerInstanceValue iValue : paramTransformerInstance.getAttributeValues()) {
- log.trace("--- getArgumentNumber: " + iValue.getArgumentNumber());
- log.trace("--- getValue: " + iValue.getValue());
- }
- log.trace("- fileList:");
- for (File f : fileList) {
- log.trace("-- getAbsolutePath: " + f.getAbsolutePath());
- log.trace("-- getName: " + f.getName());
- log.trace("-- length: " + f.length() + " bytes");
- }
- log.trace(
- "====== End of arguments ==============================================================================");
- }
- }
- // private String parseResults(){
- //
- //
- //
- // return"";
- // }
- /**
- * Extracts extension from the file name. Dot is not included in the
- * returned string.
- *
- * @param fileName
- * File name
- * @return File extension
- */
- private String extractFileNameExtension(String fileName) {
- int dotInd = fileName.lastIndexOf('.');
- // if dot is in the first position,
- // we are dealing with a hidden file rather than an extension
- return (dotInd > 0 && dotInd < fileName.length()) ? fileName.substring(dotInd + 1) : null;
- }
- private static String extractFilename(String fileName) {
- int dotInd = fileName.lastIndexOf('.');
- if (dotInd < 0) {
- return fileName;
- }
- // if dot is in the first position,
- // we are dealing with a hidden file rather than an extension
- return (dotInd > 0 && dotInd < fileName.length()) ? fileName.substring(0, dotInd) : null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement