Advertisement
Guest User

fuente_plugin

a guest
Mar 18th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.50 KB | None | 0 0
  1. package eft.liquidaciones.process;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.io.Reader;
  8. import java.io.StringReader;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Calendar;
  11. import java.util.HashMap;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Map;
  15. import cl.eft.utilities.SshUtils;
  16.  
  17. import org.apache.commons.io.FileUtils;
  18. import org.apache.commons.net.ftp.FTPClient;
  19. import org.apache.log4j.Logger;
  20. import org.jdom.Document;
  21. import org.jdom.Element;
  22. import org.jdom.input.SAXBuilder;
  23. import org.jdom.xpath.XPath;
  24.  
  25. import com.zehon.exception.FileTransferException;
  26. import com.zehon.sftp.SFTPClient;
  27.  
  28. import eft.mybatis.MyBatisCall;
  29. import eft.scheduler.process.Processor;
  30.  
  31.  
  32. public class pluginNativaLiquidacion01 extends Processor{
  33.  
  34. static Logger log = Logger.getLogger(pluginNativaLiquidacion01.class);
  35. private String respuesta;
  36.  
  37.  
  38. @SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
  39. public String ejecutar(HashMap<String, String> paramHashMap) {
  40. log.info("INICIO PROCESO GENERACION DE ARCHIVO");
  41.  
  42. try {
  43.  
  44. String NOMBRE_ARCH = paramHashMap.get("NOMBRE_GENERACION");
  45. String FORMATO_FECHA_ARCH = paramHashMap.get("FORMATO_FECHA");
  46.  
  47. String SERVIDOR = paramHashMap.get("SERVIDOR");
  48. String CATALOGO = paramHashMap.get("CATALOGO");
  49. String JNDI_BDHUBEMP = paramHashMap.get("JNDI_BD_HUBEMP");
  50. String JNDI_BDCNV = paramHashMap.get("JNDI_BD_CNV");
  51. String MAPPER_LIQUIDACION = paramHashMap.get("MAPPER_LIQUIDACION"); //LiquidacionesNativaMapper
  52. String FUNCION_LIQUIDACION = paramHashMap.get("FUNCION_LIQUIDACION");
  53. String FUNCION_LIQUIDAR = paramHashMap.get("FUNCION_LIQUIDAR"); // UPDATE REGISTROS
  54. String DIAS_EJECUCION = (paramHashMap.containsKey("DIAS_EJECUCION")) ? paramHashMap.get("DIAS_EJECUCION") : "";
  55. //String credential = "hubempresas:hubempresas@10.10.60.170:/home/hubempresas/";
  56. String credential = paramHashMap.get("CONEXION_FTP");
  57.  
  58. Calendar fechaCalendar = Calendar.getInstance();
  59. String fechaHoraEjec = new SimpleDateFormat(FORMATO_FECHA_ARCH).format(fechaCalendar.getTime());
  60. log.info("Formato yyyyMMddHHmmss de FECHA EJECUCION del proceso:: " + fechaHoraEjec);
  61.  
  62. if(NOMBRE_ARCH.equals("")){
  63. NOMBRE_ARCH = "Defina_nombre_en_xml-"+FORMATO_FECHA_ARCH;
  64. }
  65. if(NOMBRE_ARCH.contains(FORMATO_FECHA_ARCH)){
  66. NOMBRE_ARCH = NOMBRE_ARCH.replace(FORMATO_FECHA_ARCH, fechaHoraEjec);
  67. }
  68.  
  69.  
  70. log.info("[NOMBRE_ARCHIVO: " + NOMBRE_ARCH + " ]");
  71. log.info("[SERVIDOR: " + SERVIDOR + " ]");
  72. log.info("[CATALOGO: " + CATALOGO + " ]");
  73. log.info("[JNDI_BD: " + JNDI_BDHUBEMP + " ]");
  74. log.info("[MAPPER_LIQUIDACION: " + MAPPER_LIQUIDACION + " ]");
  75. log.info("[FUNCION_LIQUIDACION: " + FUNCION_LIQUIDACION + " ]");
  76. log.info("[FUNCION_LIQUIDAR: " + FUNCION_LIQUIDAR + " ]");
  77. log.info("[CREDENTIALS FTP: " + credential + " ]");
  78.  
  79. MyBatisCall ex = new MyBatisCall(SERVIDOR, CATALOGO);
  80. Map<String, Object> parameters = new HashMap<String, Object>();
  81.  
  82. // boolean procesaServicio = tareaProgramadaParaHoy(fechaCalendar.get(Calendar.DAY_OF_WEEK), DIAS_EJECUCION);
  83. boolean procesaServicio = true;
  84. log.info("procesaServicio task scheduled :: " + procesaServicio);
  85.  
  86. if (procesaServicio) {
  87.  
  88. String registro = "";
  89. String data1 =paramHashMap.get("PARAM_FILTRO"); // escoge el tipo de query a resolver
  90. Integer id_recaudador = Integer.valueOf(paramHashMap.get("ID_RECAUDADOR"));
  91.  
  92. log.info("parameters LIQUIDACION :::::::::" + parameters);
  93. String USAR_BD = (paramHashMap.containsKey("USAR_BD"))? (String)paramHashMap.get("USAR_BD"):"";
  94. if(!USAR_BD.equals("")){
  95.  
  96. log.info("....HAGO QUERY. ");
  97. parameters.put("p_dataStr", data1);
  98. parameters.put("p_id_rec", id_recaudador);
  99.  
  100. ex.callList(JNDI_BDHUBEMP, CATALOGO + "/"+MAPPER_LIQUIDACION, FUNCION_LIQUIDACION, parameters);
  101.  
  102. List<HashMap<Object,Object>> queryResultado;
  103. List<HashMap<Object,Object>> queryResultadoHead;
  104. HashMap<Object,Object> respQueryHead = new HashMap<Object,Object>();
  105. HashMap<Object,Object> respQuery = new HashMap<Object,Object>();
  106.  
  107. if(parameters.containsKey("retornoHead")){
  108. queryResultadoHead = (List<HashMap<Object,Object>>) parameters.get("retornoHead");
  109. respQueryHead = (HashMap<Object,Object>)queryResultadoHead.get(0);
  110. log.info("HEAD VALUES:"+respQueryHead.toString());
  111. try{
  112. String header= (paramHashMap.containsKey("ADJUNTAR_HEADER")) ? paramHashMap.get("ADJUNTAR_HEADER"):""; // escoge el tipo de query a resolver
  113. if(!header.equals("")){
  114. String head = (respQueryHead.get("REGISTROHEAD")).toString();
  115. if(head != null && !head.equals(""))
  116. registro += head +"\n";
  117. }
  118. }catch(Exception e){
  119. log.info("Error en header: ",e);
  120. }
  121. }
  122.  
  123. if(parameters.containsKey("retornoDetalle")){
  124. queryResultado = (List<HashMap<Object,Object>>) parameters.get("retornoDetalle");
  125. }else{
  126. queryResultado = null;
  127. }
  128. // agrego los resultados de la query si existen.
  129. if(queryResultado != null){
  130. int size = queryResultado.size();
  131. for(int i=0;i<queryResultado.size();i++){
  132. respQuery = (HashMap<Object,Object>)queryResultado.get(i);
  133. registro += respQuery.get("REGISTROBODY").toString();
  134. if (i< size - 1 ) registro += "\n"; // para no agregar linea nueva al final.
  135. }
  136.  
  137. }
  138.  
  139. log.info("....QUERY REALIZADA.");
  140. }else{
  141. log.info("....NO HAGO QUERY. envio VALOR POR DEFECTO: ");
  142. registro = "esto voy a imprimir en este archivo.";
  143. }
  144. /*
  145. * ASDF
  146. */
  147. log.info("..........");
  148. //log.info("RESULTADO PLUGIN NATIVA::::: ");
  149. //log.info(registro);
  150.  
  151. //File file = new File(NOMBRE_ARCH);
  152. //FileUtils.writeStringToFile(file, registro, "UTF8");
  153. String localPathFile = paramHashMap.get("DIR_ARCHIVO_LOCAL"); // escoge el tipo de query a resolver
  154. if(!localPathFile.equals("")){
  155. String[] creds = credential.split(":");
  156. String path_local = System.getProperty("user.home") + localPathFile; ;
  157. log.info("Intentando Crear archivo..."+NOMBRE_ARCH);
  158. escribir(registro,path_local,NOMBRE_ARCH+"_local"+".txt");
  159. log.info("....ARCHIVO CREADO...");
  160. }else{
  161. log.info("... SIN ARCHIVO LOCAL ...");
  162. }
  163. byte [] fileCont = registro.getBytes(); //datos de la bd
  164. boolean createDir = true;
  165. //log.info("WHAT SHALL I WRITE?:: ");
  166. //log.info(registro);
  167. //String credential = "hubempresas:hubempresas@10.10.60.170:/home/hubempresas/"; //cadena de conexion para enviar por FTP
  168. String USAR_FTP = (paramHashMap.containsKey("ENVIAR_SFTP"))? (String)paramHashMap.get("ENVIAR_SFTP"):"";
  169. if(!USAR_FTP.equals("")){
  170. // log.info("ENVIANDO ARCHIVO VIA SFTP ...");
  171. SshUtils.saveRemoteFile(credential, NOMBRE_ARCH, fileCont, createDir);
  172. //sendFTP(credential, NOMBRE_ARCH,registro);
  173. //Usar otro FTP
  174.  
  175. log.info("OK SFTP!!");
  176.  
  177. }else{
  178. log.info("OK sin SFTP!!");
  179.  
  180. }
  181.  
  182. if(registro.length() > 0){
  183. log.info("ACTUALIZANDO REGISTROS...");
  184. parameters.put("p_dataStr", data1);
  185. parameters.put("p_id_rec", id_recaudador);
  186. ex.callList(JNDI_BDHUBEMP, CATALOGO + "/"+MAPPER_LIQUIDACION, FUNCION_LIQUIDAR, parameters);
  187. log.info("...REGISTROS ACTUALIZADOS...");
  188. }else{
  189. log.info("... NO HAY REGISTROS POR ACTUALIZAR ...");
  190. }
  191.  
  192. respuesta="OK";
  193.  
  194.  
  195. } else {
  196. log.info("Servicio no configurado para ser procesado hoy.");
  197. respuesta = "NK day";
  198. }
  199.  
  200. } catch (Exception e) {
  201. log.info("ERROR EN PROCESO DE GENERACION DE ARCHVO: " ,e);
  202. respuesta = "NK";
  203. log.info("Respuesta error PLUGIN:: "+respuesta);
  204. return "NK";
  205. }
  206. log.info("Respuesta PLUGIN:: "+respuesta);
  207.  
  208. return respuesta;
  209. }
  210.  
  211. // Obtiene si hoy se ejecuta la tarea
  212. public boolean tareaProgramadaParaHoy(int diaSemanaNum, String diasEjecucion) {
  213. String diaSemana;
  214.  
  215. // Si dias ejecucion vienen vacios
  216. if (diasEjecucion.isEmpty())
  217. return false;
  218.  
  219. // Convierte numero dia a los seteados en XML
  220. switch (diaSemanaNum) {
  221. case 1:
  222. diaSemana = "DOM";
  223. break;
  224. case 2:
  225. diaSemana = "LUN";
  226. break;
  227. case 3:
  228. diaSemana = "MAR";
  229. break;
  230. case 4:
  231. diaSemana = "MIE";
  232. break;
  233. case 5:
  234. diaSemana = "JUE";
  235. break;
  236. case 6:
  237. diaSemana = "VIE";
  238. break;
  239. case 7:
  240. diaSemana = "SAB";
  241. break;
  242. default:
  243. diaSemana = "LUN";
  244. }
  245.  
  246. // Consulta si esta en el listado
  247. boolean ejecutaTarea = diasEjecucion.contains(diaSemana);
  248.  
  249. return ejecutaTarea;
  250. }
  251.  
  252.  
  253. public void escribir(String data, String path, String filename_ext){
  254. File file = new File(path + "/" + filename_ext);
  255. // creates the file
  256. try {
  257. FileWriter writer;
  258. file.createNewFile();
  259. // creates a FileWriter Object
  260. writer = new FileWriter(file);
  261. writer.write(data);
  262. writer.flush();
  263. writer.close();
  264. } catch (IOException e) {
  265. // TODO Auto-generated catch block
  266. //e.printStackTrace();
  267. log.info("error file creation! :::",e);
  268. } finally{
  269. // Writes the content to the file
  270.  
  271.  
  272. }
  273. }
  274. /* no usado*/
  275. //type= 0 => add 0s to the left, 1 => add blank spaces to the right
  276. //total=total of digits or characters to be returned.
  277. //String value=value to be formated
  278. public String formatValue(String value, String type, String padding,String total, String decimales){
  279. String output="";
  280. int int_total = Integer.parseInt(total);
  281. int int_decimales = (decimales.equals(""))? 0:Integer.parseInt(decimales);
  282. int len_prev = value.length();
  283. if(len_prev < int_total && type.equals("0") && !value.equals("???")){ //caso especial de los numeros decimales
  284.  
  285. value = value.replace(",", "."); // if exists
  286. value = (value.equals("") || !isNumeric(value))?"0":value;
  287. //int valor = Integer.parseInt(value);
  288. Double valor = Double.valueOf(value);
  289. double power = Math.pow(10,int_decimales); //cantidad de decimales a agregar
  290. int result = (int)Math.floor(valor.doubleValue()*power); //trunca si hay mas.
  291. value = String.valueOf(result);
  292. }
  293.  
  294. int len = value.length();
  295. System.out.println(type+" -- "+ len + " " + int_total + " "+ value);
  296. String aux_padd = "";
  297. if(type.equals("1")){ //string excedededed max value
  298. if(len > int_total){
  299. value = value.substring(0,int_total); //trunco string a la derecha si excede tamaño total
  300. }
  301. }else{ //number excedededed max value
  302. if(len > int_total){
  303. value = value.substring(int_total,len);
  304. }
  305. }
  306. while((len++) < int_total)
  307. aux_padd += padding;
  308.  
  309. //agrego 0 a la izq si es numero, espacios si es 1 o distinto 0
  310. output = (type.equals("0"))?(aux_padd + value):(value + aux_padd );
  311.  
  312. return output;
  313.  
  314. }
  315. public boolean isNumeric(String value){
  316. try{
  317. Double d = Double.valueOf(value);
  318. return true;
  319. }catch(NumberFormatException e){
  320. return false;
  321. }
  322. }
  323. public boolean sendFTP(String conexion,String filename,String data){
  324. String [] cnx = conexion.split(":");
  325. if(cnx.length < 3) return false;
  326. String ip_servidor = cnx[1].split("@")[1];
  327. String usuario = cnx[0];
  328. String pass = cnx[1].split("@")[0];
  329. String pathremoto = cnx[2];
  330. log.info("user: "+usuario + ";pass: "+pass+";pathremoto: "+pathremoto);
  331. File file = new File(filename);
  332. try {
  333. FileUtils.writeStringToFile(file, data, "UTF8");
  334. log.info("cree archivo..");
  335. SFTPClient connection = new SFTPClient();
  336. log.info("creo conexion...");
  337. connection.setServerName(ip_servidor);
  338. connection.setUsername(usuario);
  339. connection.setPassword(pass);
  340.  
  341. try {
  342. log.info("envio...");
  343. connection.sendFile(file, pathremoto, file.getName());
  344. connection.closeCache();
  345. return true;
  346. } catch (FileTransferException e) {
  347. // TODO Auto-generated catch block
  348. log.info("Error Enviando el archivo:: ",e);
  349. return false;
  350. }
  351. } catch (IOException e) {
  352. e.printStackTrace();
  353. log.error("ERROR conexion FTP ::", e);
  354. return false;
  355. }
  356.  
  357. }
  358. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement