Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package eft.liquidaciones.process;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.Reader;
- import java.io.StringReader;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import cl.eft.utilities.SshUtils;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.log4j.Logger;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.input.SAXBuilder;
- import org.jdom.xpath.XPath;
- import com.zehon.exception.FileTransferException;
- import com.zehon.sftp.SFTPClient;
- import eft.mybatis.MyBatisCall;
- import eft.scheduler.process.Processor;
- public class pluginNativaLiquidacion01 extends Processor{
- static Logger log = Logger.getLogger(pluginNativaLiquidacion01.class);
- private String respuesta;
- @SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
- public String ejecutar(HashMap<String, String> paramHashMap) {
- log.info("INICIO PROCESO GENERACION DE ARCHIVO");
- try {
- String NOMBRE_ARCH = paramHashMap.get("NOMBRE_GENERACION");
- String FORMATO_FECHA_ARCH = paramHashMap.get("FORMATO_FECHA");
- String SERVIDOR = paramHashMap.get("SERVIDOR");
- String CATALOGO = paramHashMap.get("CATALOGO");
- String JNDI_BDHUBEMP = paramHashMap.get("JNDI_BD_HUBEMP");
- String JNDI_BDCNV = paramHashMap.get("JNDI_BD_CNV");
- String MAPPER_LIQUIDACION = paramHashMap.get("MAPPER_LIQUIDACION"); //LiquidacionesNativaMapper
- String FUNCION_LIQUIDACION = paramHashMap.get("FUNCION_LIQUIDACION");
- String FUNCION_LIQUIDAR = paramHashMap.get("FUNCION_LIQUIDAR"); // UPDATE REGISTROS
- String DIAS_EJECUCION = (paramHashMap.containsKey("DIAS_EJECUCION")) ? paramHashMap.get("DIAS_EJECUCION") : "";
- //String credential = "hubempresas:hubempresas@10.10.60.170:/home/hubempresas/";
- String credential = paramHashMap.get("CONEXION_FTP");
- Calendar fechaCalendar = Calendar.getInstance();
- String fechaHoraEjec = new SimpleDateFormat(FORMATO_FECHA_ARCH).format(fechaCalendar.getTime());
- log.info("Formato yyyyMMddHHmmss de FECHA EJECUCION del proceso:: " + fechaHoraEjec);
- if(NOMBRE_ARCH.equals("")){
- NOMBRE_ARCH = "Defina_nombre_en_xml-"+FORMATO_FECHA_ARCH;
- }
- if(NOMBRE_ARCH.contains(FORMATO_FECHA_ARCH)){
- NOMBRE_ARCH = NOMBRE_ARCH.replace(FORMATO_FECHA_ARCH, fechaHoraEjec);
- }
- log.info("[NOMBRE_ARCHIVO: " + NOMBRE_ARCH + " ]");
- log.info("[SERVIDOR: " + SERVIDOR + " ]");
- log.info("[CATALOGO: " + CATALOGO + " ]");
- log.info("[JNDI_BD: " + JNDI_BDHUBEMP + " ]");
- log.info("[MAPPER_LIQUIDACION: " + MAPPER_LIQUIDACION + " ]");
- log.info("[FUNCION_LIQUIDACION: " + FUNCION_LIQUIDACION + " ]");
- log.info("[FUNCION_LIQUIDAR: " + FUNCION_LIQUIDAR + " ]");
- log.info("[CREDENTIALS FTP: " + credential + " ]");
- MyBatisCall ex = new MyBatisCall(SERVIDOR, CATALOGO);
- Map<String, Object> parameters = new HashMap<String, Object>();
- // boolean procesaServicio = tareaProgramadaParaHoy(fechaCalendar.get(Calendar.DAY_OF_WEEK), DIAS_EJECUCION);
- boolean procesaServicio = true;
- log.info("procesaServicio task scheduled :: " + procesaServicio);
- if (procesaServicio) {
- String registro = "";
- String data1 =paramHashMap.get("PARAM_FILTRO"); // escoge el tipo de query a resolver
- Integer id_recaudador = Integer.valueOf(paramHashMap.get("ID_RECAUDADOR"));
- log.info("parameters LIQUIDACION :::::::::" + parameters);
- String USAR_BD = (paramHashMap.containsKey("USAR_BD"))? (String)paramHashMap.get("USAR_BD"):"";
- if(!USAR_BD.equals("")){
- log.info("....HAGO QUERY. ");
- parameters.put("p_dataStr", data1);
- parameters.put("p_id_rec", id_recaudador);
- ex.callList(JNDI_BDHUBEMP, CATALOGO + "/"+MAPPER_LIQUIDACION, FUNCION_LIQUIDACION, parameters);
- List<HashMap<Object,Object>> queryResultado;
- List<HashMap<Object,Object>> queryResultadoHead;
- HashMap<Object,Object> respQueryHead = new HashMap<Object,Object>();
- HashMap<Object,Object> respQuery = new HashMap<Object,Object>();
- if(parameters.containsKey("retornoHead")){
- queryResultadoHead = (List<HashMap<Object,Object>>) parameters.get("retornoHead");
- respQueryHead = (HashMap<Object,Object>)queryResultadoHead.get(0);
- log.info("HEAD VALUES:"+respQueryHead.toString());
- try{
- String header= (paramHashMap.containsKey("ADJUNTAR_HEADER")) ? paramHashMap.get("ADJUNTAR_HEADER"):""; // escoge el tipo de query a resolver
- if(!header.equals("")){
- String head = (respQueryHead.get("REGISTROHEAD")).toString();
- if(head != null && !head.equals(""))
- registro += head +"\n";
- }
- }catch(Exception e){
- log.info("Error en header: ",e);
- }
- }
- if(parameters.containsKey("retornoDetalle")){
- queryResultado = (List<HashMap<Object,Object>>) parameters.get("retornoDetalle");
- }else{
- queryResultado = null;
- }
- // agrego los resultados de la query si existen.
- if(queryResultado != null){
- int size = queryResultado.size();
- for(int i=0;i<queryResultado.size();i++){
- respQuery = (HashMap<Object,Object>)queryResultado.get(i);
- registro += respQuery.get("REGISTROBODY").toString();
- if (i< size - 1 ) registro += "\n"; // para no agregar linea nueva al final.
- }
- }
- log.info("....QUERY REALIZADA.");
- }else{
- log.info("....NO HAGO QUERY. envio VALOR POR DEFECTO: ");
- registro = "esto voy a imprimir en este archivo.";
- }
- /*
- * ASDF
- */
- log.info("..........");
- //log.info("RESULTADO PLUGIN NATIVA::::: ");
- //log.info(registro);
- //File file = new File(NOMBRE_ARCH);
- //FileUtils.writeStringToFile(file, registro, "UTF8");
- String localPathFile = paramHashMap.get("DIR_ARCHIVO_LOCAL"); // escoge el tipo de query a resolver
- if(!localPathFile.equals("")){
- String[] creds = credential.split(":");
- String path_local = System.getProperty("user.home") + localPathFile; ;
- log.info("Intentando Crear archivo..."+NOMBRE_ARCH);
- escribir(registro,path_local,NOMBRE_ARCH+"_local"+".txt");
- log.info("....ARCHIVO CREADO...");
- }else{
- log.info("... SIN ARCHIVO LOCAL ...");
- }
- byte [] fileCont = registro.getBytes(); //datos de la bd
- boolean createDir = true;
- //log.info("WHAT SHALL I WRITE?:: ");
- //log.info(registro);
- //String credential = "hubempresas:hubempresas@10.10.60.170:/home/hubempresas/"; //cadena de conexion para enviar por FTP
- String USAR_FTP = (paramHashMap.containsKey("ENVIAR_SFTP"))? (String)paramHashMap.get("ENVIAR_SFTP"):"";
- if(!USAR_FTP.equals("")){
- // log.info("ENVIANDO ARCHIVO VIA SFTP ...");
- SshUtils.saveRemoteFile(credential, NOMBRE_ARCH, fileCont, createDir);
- //sendFTP(credential, NOMBRE_ARCH,registro);
- //Usar otro FTP
- log.info("OK SFTP!!");
- }else{
- log.info("OK sin SFTP!!");
- }
- if(registro.length() > 0){
- log.info("ACTUALIZANDO REGISTROS...");
- parameters.put("p_dataStr", data1);
- parameters.put("p_id_rec", id_recaudador);
- ex.callList(JNDI_BDHUBEMP, CATALOGO + "/"+MAPPER_LIQUIDACION, FUNCION_LIQUIDAR, parameters);
- log.info("...REGISTROS ACTUALIZADOS...");
- }else{
- log.info("... NO HAY REGISTROS POR ACTUALIZAR ...");
- }
- respuesta="OK";
- } else {
- log.info("Servicio no configurado para ser procesado hoy.");
- respuesta = "NK day";
- }
- } catch (Exception e) {
- log.info("ERROR EN PROCESO DE GENERACION DE ARCHVO: " ,e);
- respuesta = "NK";
- log.info("Respuesta error PLUGIN:: "+respuesta);
- return "NK";
- }
- log.info("Respuesta PLUGIN:: "+respuesta);
- return respuesta;
- }
- // Obtiene si hoy se ejecuta la tarea
- public boolean tareaProgramadaParaHoy(int diaSemanaNum, String diasEjecucion) {
- String diaSemana;
- // Si dias ejecucion vienen vacios
- if (diasEjecucion.isEmpty())
- return false;
- // Convierte numero dia a los seteados en XML
- switch (diaSemanaNum) {
- case 1:
- diaSemana = "DOM";
- break;
- case 2:
- diaSemana = "LUN";
- break;
- case 3:
- diaSemana = "MAR";
- break;
- case 4:
- diaSemana = "MIE";
- break;
- case 5:
- diaSemana = "JUE";
- break;
- case 6:
- diaSemana = "VIE";
- break;
- case 7:
- diaSemana = "SAB";
- break;
- default:
- diaSemana = "LUN";
- }
- // Consulta si esta en el listado
- boolean ejecutaTarea = diasEjecucion.contains(diaSemana);
- return ejecutaTarea;
- }
- public void escribir(String data, String path, String filename_ext){
- File file = new File(path + "/" + filename_ext);
- // creates the file
- try {
- FileWriter writer;
- file.createNewFile();
- // creates a FileWriter Object
- writer = new FileWriter(file);
- writer.write(data);
- writer.flush();
- writer.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- log.info("error file creation! :::",e);
- } finally{
- // Writes the content to the file
- }
- }
- /* no usado*/
- //type= 0 => add 0s to the left, 1 => add blank spaces to the right
- //total=total of digits or characters to be returned.
- //String value=value to be formated
- public String formatValue(String value, String type, String padding,String total, String decimales){
- String output="";
- int int_total = Integer.parseInt(total);
- int int_decimales = (decimales.equals(""))? 0:Integer.parseInt(decimales);
- int len_prev = value.length();
- if(len_prev < int_total && type.equals("0") && !value.equals("???")){ //caso especial de los numeros decimales
- value = value.replace(",", "."); // if exists
- value = (value.equals("") || !isNumeric(value))?"0":value;
- //int valor = Integer.parseInt(value);
- Double valor = Double.valueOf(value);
- double power = Math.pow(10,int_decimales); //cantidad de decimales a agregar
- int result = (int)Math.floor(valor.doubleValue()*power); //trunca si hay mas.
- value = String.valueOf(result);
- }
- int len = value.length();
- System.out.println(type+" -- "+ len + " " + int_total + " "+ value);
- String aux_padd = "";
- if(type.equals("1")){ //string excedededed max value
- if(len > int_total){
- value = value.substring(0,int_total); //trunco string a la derecha si excede tamaño total
- }
- }else{ //number excedededed max value
- if(len > int_total){
- value = value.substring(int_total,len);
- }
- }
- while((len++) < int_total)
- aux_padd += padding;
- //agrego 0 a la izq si es numero, espacios si es 1 o distinto 0
- output = (type.equals("0"))?(aux_padd + value):(value + aux_padd );
- return output;
- }
- public boolean isNumeric(String value){
- try{
- Double d = Double.valueOf(value);
- return true;
- }catch(NumberFormatException e){
- return false;
- }
- }
- public boolean sendFTP(String conexion,String filename,String data){
- String [] cnx = conexion.split(":");
- if(cnx.length < 3) return false;
- String ip_servidor = cnx[1].split("@")[1];
- String usuario = cnx[0];
- String pass = cnx[1].split("@")[0];
- String pathremoto = cnx[2];
- log.info("user: "+usuario + ";pass: "+pass+";pathremoto: "+pathremoto);
- File file = new File(filename);
- try {
- FileUtils.writeStringToFile(file, data, "UTF8");
- log.info("cree archivo..");
- SFTPClient connection = new SFTPClient();
- log.info("creo conexion...");
- connection.setServerName(ip_servidor);
- connection.setUsername(usuario);
- connection.setPassword(pass);
- try {
- log.info("envio...");
- connection.sendFile(file, pathremoto, file.getName());
- connection.closeCache();
- return true;
- } catch (FileTransferException e) {
- // TODO Auto-generated catch block
- log.info("Error Enviando el archivo:: ",e);
- return false;
- }
- } catch (IOException e) {
- e.printStackTrace();
- log.error("ERROR conexion FTP ::", e);
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement