First Commit from Source Code Reply

This commit is contained in:
vincenzofariello
2024-05-09 17:40:24 +02:00
parent 11e3b57c5b
commit 107a016cb9
35225 changed files with 1111346 additions and 1 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,354 @@
package it.valueteam.gnpsim.base;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.obj.CausaliRifiutoOloDTO;
import it.valueteam.gnpsim.obj.OloReplyDto;
import it.valueteam.gnpsim.utility.*;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Giovanni
*/
public class SimGenerator {
public SimGenerator() {
dao = new SimDAO();
}
protected Random rand = new Random();
protected static Properties propGeneral = SimConfFile.getInstance().ReadSection("General");
protected static Properties propUpdating = SimConfFile.getInstance().ReadSection("Updating");
protected String prefisso = propUpdating.getProperty("PREFISSO");
// protected int telefono = Integer.parseInt(propUpdating.getProperty("SEED_TEL"));
private static String DEFAULT_OLO = "AMB";
private static String DEFAULT_COS = "001";
private static String DEFAULT_MARCAGGIO = "01";
private static String DEFAULT_CANALE_VENDITA = "VB78";
protected static final int DEFAULT_KO = -1;
protected SimDAO dao;
protected String listaNomi[] = {
"ANDREA", "GIOVANNI", "AMBRA", "CLAUDIO", "IVAN", "SARA", "ELENA",
"GIORGIO", "DIEGO", "ANTONELLA"};
protected String listaCognomi[] = {
"UNGARO", "AMICI", "PARATI", "GARBELLI", "PIZZOLANTE", "SCARPELLINI",
"FIORE", "TAGLIENTE", "NUNNERI", "RENDE"};
protected String[] listaCodiciErroriXdsl = {"C07", "C10", "C11", "C15"};
/**
* Aggiunge tanti zeri come prefisso fino a maxLen
*
* @param number String
* @param maxLen int
* @return String
*/
protected String addZero(String number, int maxLen) {
int len = number.length();
while (len < maxLen) {
number = "0" + number;
len++;
}
return number;
}
protected String removeZero(String number) {
String result = null;
result = number.replaceAll("[0]", "");
return result;
}
/**
* Aggiunge tanti spazi fino a maxLen
*
* @param text String
* @param maxLen int
* @return String
*/
protected String addBlank(String text, int maxLen) {
int len = text.length();
while (len < maxLen) {
text = " " + text;
len++;
}
return text;
}
/**
* Resituisce un canale di provenienza tra quelli permessi
*
* @return String
*/
protected String randomCanaleProvenienzaDBSS() {
String[] canaliProvenienza = {"CCARE", "DMS", "CC", "IVR", "WEB", "SALES WEB", "SMS CARING", "SALES APP", "AS", "TS", "FV"};
int i = rand.nextInt(11);
return canaliProvenienza[i];
}
/**
* Resituisce un canale di provenienza tra quelli permessi
*
* @return String
*/
protected String randomCanaleProvenienzaCRM() {
String[] canaliProvenienza = {"CCARE", "DMS"};
int i = rand.nextInt(2);
return canaliProvenienza[i];
}
/**
* Resituisce il valore random di un flag nel dominio [Y,N]
*
* @return String
*/
protected String getRandomFlag() {
Random random = new Random();
return random.nextBoolean() ? "Y" : "N";
}
protected String getTelefono(int length) {
int numeroNum = (Integer.parseInt(SimConfFile.getInstance().ReadSection("Updating").getProperty("SEED_TEL"))) + 1;
saveSeedTel(numeroNum + "");
String numero = prefisso + numeroNum;
return addZero(numero, length);
}
protected String getCodiceFiscalePartitaIVA() {
return "SRTMCC75C52A345Q";
}
protected String getIdEsigenzaSolution() {
int idEsigenzaSolution = Integer.parseInt(SimConfFile.getInstance().ReadSection("Updating").getProperty("ID_ESIGENZA_SOLUTION")) + 1;
String result = addZero(Integer.toString(idEsigenzaSolution), 11);
saveIdEsigenzaSolution(idEsigenzaSolution + "");
return result;
}
protected String randomNomeCliente() {
int i = rand.nextInt(10);
return listaNomi[i];
}
protected String randomCognomeCliente() {
int i = rand.nextInt(10);
return listaCognomi[i];
}
protected String randomCodiceErroreXdsl() {
int i = rand.nextInt(3);
return listaCodiciErroriXdsl[i];
}
protected String getCodiceSessione() {
return propGeneral.getProperty("CODICE_SESSIONE");
}
public void saveSeedTel(String telefono) {
SimConfFile.getInstance().WriteString("Updating", "SEED_TEL", telefono);
SimConfFile.getInstance().UpdateFile();
}
public void saveIdEsigenzaSolution(String idEsigenza) {
SimConfFile.getInstance().WriteString("Updating", "ID_ESIGENZA_SOLUTION", idEsigenza);
SimConfFile.getInstance().UpdateFile();
}
public void saveIdEsigenzaManuale(String idEsigenzaManu) {
SimConfFile.getInstance().WriteString("Updating", "ID_ESIGENZA_MANUALE", idEsigenzaManu);
SimConfFile.getInstance().UpdateFile();
}
public void saveIdFileOLO(String idFileOLO) {
SimConfFile.getInstance().WriteString("Updating", "ID_FILE_OLO", idFileOLO);
SimConfFile.getInstance().UpdateFile();
}
protected String getWait() {
return propGeneral.getProperty("WAIT");
}
protected String getSla() {
return propGeneral.getProperty("SLA");
}
protected String getDacCrm() throws Exception {
int calc_dac = Integer.parseInt(propGeneral.getProperty("CALC_DAC"));
String dac = DateUtils.aggiungiGiorniLavorativiCrm(new Date(), calc_dac, propGeneral.getProperty("PATTERN_DATE_DAC"));
return dac;
}
protected String getDetCrm() throws Exception {
int calc_det = Integer.parseInt(propGeneral.getProperty("CALC_DET"));
String det = DateUtils.aggiungiGiorniLavorativiCrm(new Date(), calc_det, propGeneral.getProperty("PATTERN_DATE_DET"));
return det;
}
protected String getIdEsigenzaManuale() {
int idEsigenzaSolution = Integer.parseInt(SimConfFile.getInstance().ReadSection("Updating").getProperty("ID_ESIGENZA_MANUALE"));
String result = addZero(Integer.toString(idEsigenzaSolution), 15);
saveIdEsigenzaManuale((idEsigenzaSolution + 1) + "");
return result;
}
public String getIdFileOLO() {
int idFileOLO = Integer.parseInt(SimConfFile.getInstance().ReadSection("Updating").getProperty("ID_FILE_OLO"));
String result = addZero(Integer.toString(idFileOLO), 5);
saveIdFileOLO((idFileOLO + 1) + "");
return result;
}
public String randomCodiceOlo() {
String result = null;
try {
String[] olo = dao.getAllOlo();
int i = rand.nextInt(olo.length);
result = olo[i];
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
System.out.println("Errore durante la select per gli OLO. Verr<72> inserito l'OLO di default AMB ");
result = DEFAULT_OLO;
}
return result;
}
protected Date toDate(String date, String pattern) {
Date data = null;
try {
data = DateUtils.toDate(date, pattern);
} catch (Exception ex) {
// Nothing to do
}
return data;
}
protected OloReplyDto[] getRequestToReply(String olo, int stato, int tipoRichieste) throws Exception {
return dao.getRequestToReply(olo, stato, tipoRichieste);
}
protected String toString(Date date, String pattern) {
return DateUtils.toString(date, pattern);
}
protected String getXmlFromCastorObject(Object bean, boolean validate) throws Exception {
return XmlUtility.getXmlStringFromCastorXmlObject(bean, validate);
}
protected CausaliRifiutoOloDTO getInfoOloKO(int tipoComunicazione, int tipoKO) {
CausaliRifiutoOloDTO result = null;
try {
CausaliRifiutoOloDTO[] causali = dao.getCausaliRifiutoOloByTipoComunicazione(tipoComunicazione);
if (tipoKO == DEFAULT_KO) {
result = causali[rand.nextInt(causali.length)];
} else {
int i = 0;
while (!causali[i].getCodiceMotivo_rifiuto().equals("" + tipoKO) && i < causali.length - 1) {
i++;
}
result = causali[i];
if (result == null) {
result = causali[rand.nextInt(causali.length)];
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
return result;
}
protected String getRandomCos() {
String result;
try {
String[] cos = dao.getValidCos();
int i = rand.nextInt(cos.length);
result = cos[i];
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("Errore durante la select per gli COS. Verrà inserito il COS di default 001 ");
result = DEFAULT_COS;
}
return result;
}
protected boolean isNull(String string) {
return string == null || string.trim().length() == 0;
}
protected void populateBeanWithUnicValue(Object o, String value) throws Exception {
Method[] methods = null;
if (o == null)
throw new Exception("l'oggetto da popolare risulta nullo");
methods = o.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String name = method.getName();
try {
if (name.startsWith("set")) {
Object[] argument = {value};
method.invoke(o, argument);
}
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
}
protected String getCodiceCorrelazioneCRM() throws Exception {
return propGeneral.getProperty("COD_CORRELAZIONE");
}
protected String getRandomMarcaggio() {
String result = null;
try {
String[] marcaggio = dao.getValidMarcaggio();
int i = rand.nextInt(marcaggio.length);
result = marcaggio[i];
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("Errore durante la select per i marcaggi. Verrà inserito il marcaggio di default 01 ");
result = DEFAULT_MARCAGGIO;
}
return result;
}
protected String getRandomCanaleVendita() {
String result = null;
try {
String[] canaleVendita = dao.getValidCanaleVendita();
int i = rand.nextInt(canaleVendita.length);
result = canaleVendita[i];
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println("Errore durante la select per i canaleVendita. Verrà inserito il canaleVendita di default VB78 ");
result = DEFAULT_CANALE_VENDITA;
}
return result;
}
/**
* Restituisce una stringa casuale di 18 caratteri alfanumerici
*
* @return la stringa da usare come codice progetto
*/
protected String getRandomCodiceProgetto() {
int length = 18;
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random rng = new Random();
String st = "";
for (int i = 0; i < length; i++)
{
st += chars.charAt(rng.nextInt(chars.length()));
}
return st;
}
}

View File

@@ -0,0 +1,47 @@
package it.valueteam.gnpsim.client;
import java.util.Date;
import it.valueteam.gnpsim.obj.SystemMap;
public abstract class BaseClient {
public BaseClient() {
}
protected static int getTipoSistema(String sis){
int sistema = -1;
if(sis.equals("CRMR") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_CRMR)
sistema= SystemMap.SISTEMA_CRMR;
else
if(sis.equals("CRMB") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_CRMB)
sistema= SystemMap.SISTEMA_CRMB;
else
if(sis.equals("PITAG_XDSL") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_PITAGORA_XDSL)
sistema= SystemMap.SISTEMA_PITAGORA_XDSL;
else
if(sis.equals("PITAG_REG") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_PITAGORA)
sistema= SystemMap.SISTEMA_PITAGORA;
else if (sis.equals("CRMR_HZ") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_CRMR_HZ) {
sistema = SystemMap.SISTEMA_CRMR_HZ;
}
else if (sis.equals("DBC") || Integer.valueOf(sis).intValue()==SystemMap.SISTEMA_DBC) {
sistema = SystemMap.SISTEMA_DBC;
}
return sistema;
}
protected static void printInfo(String name, String[] args)
{
System.out.println("-------------------------------------------------------------------------");
System.out.println(new Date());
System.out.print(name + ": ");
for(int i = 0; i < args.length; ++i)
System.out.print(args[i] + " ");
System.out.println("");
System.out.println("-------------------------------------------------------------------------");
}
}

View File

@@ -0,0 +1,47 @@
package it.valueteam.gnpsim.client;
import it.valueteam.gnpsim.generator.flat.*;
import it.valueteam.gnpsim.obj.SystemMap;
public class ClientFlatGenerator extends BaseClient{
private static FlatGeneratorIF generator;
public ClientFlatGenerator(){
}
public static final void main(String[] args) {
printInfo("ClientFlatGenerator", args);
if(args.length<1)
throw new IllegalArgumentException("Numero parametri insufficienti!");
try{
int tipoSistema = getTipoSistema(args[0]);
String[] argument = new String[args.length-1];
System.arraycopy(args,1,argument,0,args.length-1);
switch(tipoSistema){
case SystemMap.SISTEMA_PITAGORA_XDSL:
generator = new FlatPitagoraXdslGenerator();
generator.generateFlat(argument);
break;
case SystemMap.SISTEMA_PITAGORA:
generator = new FlatPitagoraRegolatorioGenerator();
generator.generateFlat(argument);
break;
default:
throw new IllegalArgumentException("sistema sconociuto!\n Sistema inserito : " +args[0]);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}

View File

@@ -0,0 +1,111 @@
package it.valueteam.gnpsim.client;
import it.valueteam.gnpsim.generator.ib.*;
import it.valueteam.gnpsim.obj.SystemMap;
import it.valueteam.gnpsim.sender.IBSender;
import it.valueteam.gnpsim.utility.IOUtility;
import it.valueteam.gnpsim.utility.SimConfFile;
import java.util.Properties;
public class ClientIBGenerator extends BaseClient {
private static XMLGeneratorIF generator;
private static Properties propIB = SimConfFile.getInstance().ReadSection("InfobusIN");
// Numero minimo di parametri
private static int MIN_PARAM_NUMBER = 3;
// Indice del parametro per l'invio automatico
private static int IDX_INVIO_AUTOMATICO = 0;
// Indice del parametro Tipo Sistema
private static int IDX_TIPO_SISTEMA = 1;
// Indice del parametro Numero Richieste
private static int IDX_NUMERO_RICHIESTE = 2;
// Indice del parametro Infobus service name
private static int IDX_IB_SERVICE_NAME = 3;
public ClientIBGenerator() {
}
/**
* tipi sistema:
* CRMR,1
* CRMB,2
*/
public static final void main(String[] args) {
printInfo("ClientIBGenerator", args);
if (args.length < MIN_PARAM_NUMBER)
throw new IllegalArgumentException("Numero parametri insufficienti!");
try {
int invioAutomatico = Integer.parseInt(args[IDX_INVIO_AUTOMATICO]);
int tipoSistema = getTipoSistema(args[IDX_TIPO_SISTEMA]);
String[] argument = new String[args.length - MIN_PARAM_NUMBER];
System.arraycopy(args, MIN_PARAM_NUMBER, argument, 0, args.length - MIN_PARAM_NUMBER);
int numeroRichieste = Integer.parseInt(args[IDX_NUMERO_RICHIESTE]);
IBSender ibSender = new IBSender();
String ibServiceName = args[IDX_IB_SERVICE_NAME];
System.out.println("Invio Automatico = " + invioAutomatico);
System.out.println("Tipo Sistema = " + tipoSistema);
System.out.println("Numero Richieste = " + numeroRichieste);
System.out.println("Infobus Service Name = " + ibServiceName);
switch (tipoSistema) {
case SystemMap.SISTEMA_CRMR: {
for (int i = 0; i < numeroRichieste; i++) {
generator = new XMLCrmGenerator();
String xml = generator.generateXml(argument, SystemMap.SISTEMA_CRMR);
if (invioAutomatico == 1) {
System.out.println(xml);
ibSender.sendRequest(xml, SystemMap.SISTEMA_CRMR);
} else {
String[] content = {xml};
String file = propIB.getProperty("GEN_PATH_CRMR") + "NOTIFICA_CRMR_" + i + ".xml";
IOUtility.writeFile(file, content);
}
}
}
break;
case SystemMap.SISTEMA_CRMB: {
for (int i = 0; i < numeroRichieste; i++) {
generator = new XMLCrmGenerator();
String xml = generator.generateXml(argument, SystemMap.SISTEMA_CRMB);
if (invioAutomatico == 1) {
System.out.println(xml);
ibSender.sendRequest(xml, SystemMap.SISTEMA_CRMB);
} else {
String[] content = {xml};
String file = propIB.getProperty("GEN_PATH_CRMB") + "NOTIFICA_CRMB_" + i + ".xml";
IOUtility.writeFile(file, content);
}
}
}
break;
case SystemMap.SISTEMA_CRMR_HZ:
generator = new XMLHZCrmrGenerator();
for (int i = 0; i < numeroRichieste; i++) {
String xml = generator.generateXml(argument, SystemMap.SISTEMA_CRMR_HZ);
if (invioAutomatico == 1) {
System.out.println(xml);
ibSender.sendHZRequest(xml, SystemMap.SISTEMA_CRMR_HZ);
} else {
String[] content = {xml};
String file = propIB.getProperty("GEN_PATH_CRMB_HZ") + "NOTIFICA_CRMR_HZ_" + i + ".xml";
IOUtility.writeFile(file, content);
}
}
break;
default:
throw new IllegalArgumentException("sistema sconociuto!\n Sistema inserito : " + args[IDX_TIPO_SISTEMA]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@@ -0,0 +1,93 @@
package it.valueteam.gnpsim.client;
public class ClientIBSim extends BaseClient {
//args[0] values
private static int INTEGRAZIONE = 1;
//args[1] values
@SuppressWarnings("unused")
private static int ATTIVAZIONE = 1;
/**
* Usage:
* args[0] = 1 indica l'attivazione\disattivazione dell'integrazione con un sistema
* Se args[0]=1 mi aspetto un totale di 3 parametri:
* args[1] = nome sistema
* args[2] = attivazione (1) \ disattivazione (qualsiasi valore intero)
* @param args
*/
public static void main(String[] args) {
try {
printInfo("ClientIBSim", args);
int tipoOperazione = Integer.parseInt(args[0]);
if (tipoOperazione==INTEGRAZIONE) {
if (args.length!=3) {
throw new IllegalArgumentException("Numero parametri errati!");
}
/*if (getTipoSistema(args[1]) == SystemMap.SISTEMA_DBC) {
boolean attivazione = ATTIVAZIONE == Integer.parseInt(args[2])?true:false;
ClientIBSim clientIB = new ClientIBSim();
clientIB.setIntegrazioneDBC(attivazione);
}*/
}
}
catch (Exception ex) {
System.out.println("Problem: " + ex);
ex.printStackTrace();
}
}
/*
private void setIntegrazioneDBC(boolean attivazione) throws Exception {
InfoBUSConnector connector = getIBConnector();
for(int i=0; i<connector.getClass().getMethods().length; i++) {
System.out.println(connector.getClass().getMethods()[i].getName());
Class[] classes = connector.getClass().getMethods()[i].getParameterTypes();
for (int j=0; j<classes.length; j++) {
System.out.println(classes[j].getName());
}
}
//connector.setSimIntegration("DBC", SimConfFile.getInstance().ReadSection("dbcProperties"));
//connector.setSim();
}
*/
/*
private InfoBUSConnector getIBConnector() throws Exception {
InfoBUSConnector connector = null;
Properties propIB = SimConfFile.getInstance().ReadSection("InfobusIN");
Properties properties = new Properties();
Context ctx = null;
properties.put(Context.INITIAL_CONTEXT_FACTORY, propIB
.getProperty("initialContextFactory"));
properties.put(Context.SECURITY_PRINCIPAL, propIB.getProperty("user"));
properties.put(Context.SECURITY_CREDENTIALS, propIB
.getProperty("password"));
properties.put(Context.PROVIDER_URL, propIB.getProperty("url"));
String bindingName = propIB.getProperty("jndiname_infobusConnector");
try {
ctx = new InitialContext(properties);
System.out.println("lookup: " + bindingName + " at "
+ properties.getProperty(Context.PROVIDER_URL));
Object home1 = ctx.lookup(bindingName);
InfoBUSConnectorHome ibHome1 = (InfoBUSConnectorHome) PortableRemoteObject
.narrow(home1, InfoBUSConnectorHome.class);
connector = ibHome1.create();
return connector;
} catch (Exception ex) {
System.out.println("Problem: " + ex);
ex.printStackTrace();
throw ex;
} finally {
if (ctx != null)
ctx.close();
}
}
*/
}

View File

@@ -0,0 +1,77 @@
package it.valueteam.gnpsim.client;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.generator.olo.OLOGenerator;
import it.valueteam.gnpsim.generator.olo.OLOGeneratorIF;
import it.valueteam.gnpsim.utility.DateUtils;
import it.valueteam.gnpsim.utility.IOUtility;
import it.valueteam.gnpsim.utility.SimConfFile;
import java.util.Date;
import java.util.Properties;
public class ClientOloGenerator extends BaseClient{
private static final int NUM_MIN_PARAM=3; // Numero minimo di parametri
private static final int IDX_TIPO_FILE=0; // Indice del tipo file
private static final int IDX_TIPO_RICH=1; // Indice della tipologia richieste (1 = Standard, 2 = Doppio Donating)
private static final int IDX_COD_OLO=2; // Indice del codice OLO (oppure ALL)
private static OLOGeneratorIF generator;
private static final String PATTERN_FILE_NAME_DATE = "yyyyMMdd";
private static Properties propOlo= SimConfFile.getInstance().ReadSection("Olo");
public ClientOloGenerator() {
}
public static final void main(String[] args) {
printInfo("ClientOloGenerator", args);
if (args.length < NUM_MIN_PARAM)
throw new IllegalArgumentException("Numero di parametri insufficienti");
int tipoFile = Integer.parseInt(args[IDX_TIPO_FILE]);
int tipoRichieste = Integer.parseInt(args[IDX_TIPO_RICH]);
String[] argument = new String[args.length-NUM_MIN_PARAM];
System.arraycopy(args,NUM_MIN_PARAM,argument,0,args.length-NUM_MIN_PARAM);
String generationPath = propOlo.getProperty("GEN_PATH");
try {
String[] oloAttivi =null;
if(args[IDX_COD_OLO].equals("ALL"))
oloAttivi = getOloAttivi();
else{
oloAttivi = new String[1];
oloAttivi[0]=args[IDX_COD_OLO];
}
for (int i = 0; i < oloAttivi.length; i++) {
generator = new OLOGenerator(tipoRichieste);
String xml = generator.generate(argument, oloAttivi[i], tipoFile);
if(xml!=null){
String[] content = {xml};
String data = DateUtils.toString(new Date(), PATTERN_FILE_NAME_DATE);
String nomeFile = "R_" + oloAttivi[i] + "_TLC_" + data + "_"+new SimGenerator().getIdFileOLO()+".xml";
IOUtility.writeFile(generationPath+nomeFile,content);
}else
System.out.println("Nessuna richiesta per l'OLO : "+oloAttivi[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private static String[] getOloAttivi() throws Exception {
SimDAO dao = new SimDAO();
return dao.getAllOlo();
}
}

View File

@@ -0,0 +1,102 @@
package it.valueteam.gnpsim.client;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.generator.ws.WSCRMAGenerator;
import it.valueteam.gnpsim.generator.ws.WSGeneratorIF;
import it.valueteam.gnpsim.generator.ws.WSPitagoraEsitoGenerator;
import it.valueteam.gnpsim.utility.IOUtility;
import it.valueteam.gnpsim.utility.SimConfFile;
import java.util.Properties;
public class ClientWSGenerator extends BaseClient {
private static final int MIN_PARAM_NUM=2;
private static final int IDX_PARAM_TIPO_WS = 0; // Indice del parametro Tipo Web Service
private static final int IDX_PARAM_MAX_NUM_RICH = 1; // Indice del parametro Numero Massimo di richieste
private static final int WSTYPE_PITAGORA = 1; // Tipo WS Pitagora
private static final int WSTYPE_CRMA = 2; // Tipo WS CRM-A
public static void main(String args[])
{
try
{
printInfo("ClientWSGenerator", args);
if (args.length < MIN_PARAM_NUM)
throw new IllegalArgumentException("Numero di parametri insufficienti");
int WSType = Integer.parseInt(args[IDX_PARAM_TIPO_WS]);
String[] argument = new String[args.length - MIN_PARAM_NUM];
System.arraycopy(args, MIN_PARAM_NUM, argument, 0, args.length - MIN_PARAM_NUM);
WSGeneratorIF generator;
switch(WSType)
{
case WSTYPE_PITAGORA:
generator = new WSPitagoraEsitoGenerator(argument);
executeWSPITAGORA(generator, args);
break;
case WSTYPE_CRMA:
generator = new WSCRMAGenerator(argument);
executeWSCRMA(generator, args);
break;
default:
throw new Exception("Tipo WS non riconosciuto");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
// WS Pitagora
private static void executeWSPITAGORA(WSGeneratorIF generator, String args[]) throws Exception
{
Properties propWS = SimConfFile.getInstance().ReadSection("WS_Pitagora");
String generationPath = propWS.getProperty("GEN_PATH");
int numMax = Integer.parseInt(args[IDX_PARAM_MAX_NUM_RICH]);
GnpRichiesteRec[] richieste = getAllRequest(numMax);
for(int i = 0; i < richieste.length; ++i)
{
String content = generator.generateSOAPMessage(richieste[i]);
String nomeFile = generator.getFileName(richieste[i]);
IOUtility.writeFile(generationPath+nomeFile, new String[] {content});
}
}
private static GnpRichiesteRec[] getAllRequest(int maxNum) throws Exception {
SimDAO dao = new SimDAO();
return dao.getAll_ATTESA_ESITO_A375(maxNum);
}
// WS CRM-A
private static void executeWSCRMA(WSGeneratorIF generator, String[] args) throws Exception
{
Properties propWS = SimConfFile.getInstance().ReadSection("WS_CRMA");
String generationPath = propWS.getProperty("GEN_PATH");
int num = Integer.parseInt(args[IDX_PARAM_MAX_NUM_RICH]);
for(int i = 0; i < num; ++i)
{
String content = generator.generateSOAPMessage(null);
String nomeFile = generator.getFileName(null);
IOUtility.writeFile(generationPath+nomeFile, new String[] {content});
}
}
}

View File

@@ -0,0 +1,164 @@
package it.valueteam.gnpsim.client;
import dbcfx.soa.esitofrodimgmt.x20160229.EsitoFrodiRequest;
import dbcfx.soa.wirelinenumberportabilitymgmt.x20160229.RichiestaAttivazioneRequest;
import it.telecomitalia.soa.soap.soapheader.HeaderType;
import it.telecomitalia.soa.soap.soapheader.InteractionDateType;
import it.valueteam.dbcfx.ws.dbss.client.WirelineNumberPortabilityMgmt10_Impl;
import it.valueteam.dbcfx.ws.dbss.client.WirelineNumberPortabilityMgmtPortType;
import it.valueteam.dbcfx.ws.dbss.esitofrodi.client.EsitoFrodiMgmt10_Impl;
import it.valueteam.dbcfx.ws.dbss.esitofrodi.client.EsitoFrodiMgmtPortType;
import it.valueteam.gnpsim.generator.ws.WSDBSSGenerator;
import it.valueteam.gnpsim.utility.SimConfFile;
import javax.xml.rpc.Stub;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
public class DBSSCOMClient extends BaseClient {
private static final String SOURCE_SYSTEM = "DBSS-COM";
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "HH:mm:ss";
private static final String RICHIESTA_ATTIVAZIONE = "ATTIVAZIONE";
private static final String ESITO_FRODI = "FRODI";
private static final int MIN_PARAM_NUM_ATTIVAZIONE = 0;
private static final int MIN_PARAM_NUM_FRODI = 2;
private static Properties prop = SimConfFile.getInstance().ReadSection("WS_DBSS");
public static void main(String args[]) {
printInfo("ClientDBSSCom", args);
System.out.println("client dbss");
String serv = args[0];
if (RICHIESTA_ATTIVAZIONE.equals(serv)) {
attivazione(args);
} else if (ESITO_FRODI.equals(serv)) {
esitoFrodi(args);
} else {
throw new IllegalArgumentException("Parametro relativo al servizio non corretto");
}
}
private static void attivazione(String[] args) {
System.out.println("attivazione inizio");
try {
int numRich = Integer.valueOf(args[1]);
if (args.length < MIN_PARAM_NUM_ATTIVAZIONE) {
throw new IllegalArgumentException("Numero di parametri insufficienti");
}
WirelineNumberPortabilityMgmt10_Impl service = new WirelineNumberPortabilityMgmt10_Impl();
HeaderType header = new HeaderType();
header.setTransactionID(calcRandomID(4));
header.setBusinessID(calcRandomID(4));
InteractionDateType interactionDate = new InteractionDateType();
header.setMessageID(calcRandomID(4));
header.setSourceSystem(SOURCE_SYSTEM);
WSDBSSGenerator generator = new WSDBSSGenerator(args);
RichiestaAttivazioneRequest[] bodyArr = generator.generateRichiestaAttivazioneRequest(numRich, args);
String url = prop.getProperty("WS_URL");
String timeoutStr = prop.getProperty("WS_TIMEOUT");
System.out.println("url: " + url);
System.out.println("timeout: " + timeoutStr);
int timeout = timeoutStr != null && !timeoutStr.equals("") ? Integer.parseInt(timeoutStr) : null;
WirelineNumberPortabilityMgmtPortType port = service.getWirelineNumberPortabilityMgmt();
((Stub) port)._setProperty("javax.xml.rpc.service.endpoint.address", url);
((Stub) port)._setProperty("weblogic.wsee.transport.connection.timeout", timeout);
for (int i = 0; bodyArr != null && i < bodyArr.length; i++) {
Date date = new Date();
String d = new SimpleDateFormat(DATE_FORMAT).format(date);
String t = new SimpleDateFormat(TIME_FORMAT).format(date);
interactionDate.setDate(d);
interactionDate.setTime(t);
port.richiestaAttivazione(header, bodyArr[i]);
}
} catch (NumberFormatException e) {
System.out.println("il parametro numero richieste deve avere valore numerico");
e.printStackTrace();
} catch (Exception e) {
System.out.println("eccezione in attivazione ");
e.printStackTrace();
}
}
private static void esitoFrodi(String[] args) {
try {
if (args.length < MIN_PARAM_NUM_FRODI) {
throw new IllegalArgumentException("Numero di parametri insufficienti");
}
//EsitoFrodiMgmtPortTypeImpl service = new EsitoFrodiMgmtPortTypeImpl();
EsitoFrodiMgmt10_Impl service = new EsitoFrodiMgmt10_Impl();
HeaderType header = new HeaderType();
header.setTransactionID(calcRandomID(4));
header.setBusinessID(calcRandomID(4));
InteractionDateType interactionDate = new InteractionDateType();
Date date = new Date();
String d = new SimpleDateFormat(DATE_FORMAT).format(date);
String t = new SimpleDateFormat(TIME_FORMAT).format(date);
interactionDate.setDate(d);
interactionDate.setTime(t);
header.setInteractionDate(interactionDate);
header.setMessageID(calcRandomID(4));
header.setSourceSystem(SOURCE_SYSTEM);
WSDBSSGenerator generator = new WSDBSSGenerator(args);
EsitoFrodiRequest body = generator.generateEsitoFrodiRequest(args);
String url = prop.getProperty("WS_FRODI_URL");
String timeoutStr = prop.getProperty("WS_TIMEOUT");
System.out.println("url: " + url);
System.out.println("timeout: " + timeoutStr);
int timeout = timeoutStr != null && !timeoutStr.equals("") ? Integer.parseInt(timeoutStr) : null;
EsitoFrodiMgmtPortType port = service.getEsitoFrodiMgmt();
((Stub) port)._setProperty("javax.xml.rpc.service.endpoint.address", url);
((Stub) port)._setProperty("weblogic.wsee.transport.connection.timeout", timeout);
port.esitoFrodi(header, body);
} catch (Exception e) {
System.out.println("eccezione in esito frodi ");
e.printStackTrace();
}
}
private static String calcRandomID(int len) {
Random random = new Random();
int num = (int) Math.ceil(Math.pow(2, 63) / len);
return Long.toString(Math.abs(random.nextLong()), num);
}
}

View File

@@ -0,0 +1,110 @@
package it.valueteam.gnpsim.client;
import dbcfx.soa.checkretailplatform.x20160704.CheckRetailPlatformRequest;
import it.telecomitalia.soa.soap.soapheader.InteractionDateType;
import it.telecomitalia.soa.soap.soapheader.holders.HeaderTypeHolder;
import it.valueteam.dbcfx.ws.now.checkretailclient.CheckRetailPlatform10_Impl;
import it.valueteam.dbcfx.ws.now.checkretailclient.CheckRetailPlatformPortType;
import it.valueteam.gnpsim.utility.SimConfFile;
import javax.xml.rpc.Stub;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NowClient extends BaseClient{
//TODO corretto?
private static final String SOURCE_SYSTEM = "NOW";
//TODO aggiungere
private static Properties prop = SimConfFile.getInstance().ReadSection("WS_NOW");
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "HH:mm:ss";
private static final String inputRegEx = "\\d{1,50}";
public static void main(String args[]) {
printInfo("NowClient", args);
System.out.println("client NowClient");
if (!isValidInput(args)) {
throw new IllegalArgumentException("Parametro non corretto");
}
checkDN(args[0]);
}
private static void checkDN(String dn) {
System.out.println("check dn inizio");
try {
CheckRetailPlatform10_Impl service = new CheckRetailPlatform10_Impl();
HeaderTypeHolder header = new HeaderTypeHolder();
//TODO verificare value
//TODO verificare formati date
header.value.setTransactionID(calcRandomID(4));
header.value.setBusinessID(calcRandomID(4));
InteractionDateType interactionDate = new InteractionDateType();
header.value.setMessageID(calcRandomID(4));
header.value.setSourceSystem(SOURCE_SYSTEM);
String url = prop.getProperty("WS_URL");
String timeoutStr = prop.getProperty("WS_TIMEOUT");
System.out.println("url: " + url);
System.out.println("timeout: " + timeoutStr);
int timeout = timeoutStr != null && !timeoutStr.equals("") ? Integer.parseInt(timeoutStr) : null;
CheckRetailPlatformPortType port = service.getCheckRetailPlatform();
((Stub) port)._setProperty("javax.xml.rpc.service.endpoint.address", url);
((Stub)port)._setProperty("weblogic.wsee.transport.connection.timeout",timeout);
Date date = new Date();
String d = new SimpleDateFormat(DATE_FORMAT).format(date);
String t = new SimpleDateFormat(TIME_FORMAT).format(date);
interactionDate.setDate(d);
interactionDate.setTime(t);
CheckRetailPlatformRequest body = new CheckRetailPlatformRequest();
body.setDN(dn);
port.checkDN(header, body);
} catch (Exception e) {
System.out.println("eccezione in checkDN " );
e.printStackTrace();
}
}
//TODO e' duplcato da DBSSCOMClient. Mettere in BaseClient?
private static String calcRandomID(int len) {
Random random = new Random();
int num = (int)Math.ceil(Math.pow(2, 63)/len);
return Long.toString(Math.abs(random.nextLong()), num);
}
private static boolean isValidInput(String[] args) {
if (args == null) return false;
if (args.length != 1) return false;
String dn = args[0];
Pattern p = Pattern.compile(inputRegEx);
Matcher m = p.matcher(dn);
return m.matches();
}
}

View File

@@ -0,0 +1,166 @@
package it.valueteam.gnpsim.database;
/*
* Created on Feb 23, 2005
*
* MNP [project sim]
* Copyright (c) 2005
*
* @author Giovanni Amici
* @version 1.0
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import it.valueteam.gnpsim.utility.SimConfFile;
/**
* @author Giovanni
*
*/
public abstract class BaseDAO {
protected DataSource ds;
protected InitialContext ctx;
//private Connection conn;
/**
* Inizializza il data source
* @throws Exception
*/
protected void initDB() throws Exception{
try
{
Properties properties = SimConfFile.getInstance().ReadSection("JNDI");
System.out.println("java.naming.factory.initial: " + properties.getProperty("java.naming.factory.initial"));
System.out.println("java.naming.provider.url: " + properties.getProperty("java.naming.provider.url"));
System.out.println("java.naming.security.principal: " + properties.getProperty("java.naming.security.principal"));
System.out.println("java.naming.security.credentials: " + properties.getProperty("java.naming.security.credentials"));
System.out.println("datasource.name: " + properties.getProperty("datasource.name"));
System.out.println("Getting initial context.. ");
ctx = new InitialContext(properties);
System.out.println("Getting initial context.. OK");
String dsName = properties.getProperty("datasource.name");
System.out.println("Getting datasource name: " + dsName + " ..");
ds = (DataSource) ctx.lookup(properties.getProperty("datasource.name"));
System.out.println("Getting datasource name: " + dsName + " .. OK");
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
ctx.close();
}
catch (Exception ex) {}
}
}
/**
* Metodo per ottenere le connessioni dal DB
* Se non è disponibile una connessione ritorna null
*/
public Connection getConnection() throws Exception{
Connection conn = null;
try
{
if (ds==null) initDB();
conn = ds.getConnection();
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
if( conn != null ) conn.setAutoCommit(false);
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
}
// se non riesce ad ottenere una connessione per tre volte torna null
return conn;
}
/**
* Metodo per la chiusura del ResultSet,dello Statement e della Connection
* tale metodo non lancia eccezzioni
* @param rs
* @param stmt
* @param c
*/
public void closeAll(ResultSet rs, Statement stmt, Connection c) {
try
{
if(rs!=null) rs.close();
}
catch (Throwable ex) {}
try
{
if(stmt!=null) stmt.close();
}
catch (Throwable ex) {}
try
{
if(c!=null)
c.close();
}
catch (Throwable ex) {}
}
// ******************************************************
// *****UTILITA' PER PAGINAZIONE ************************
// ******************************************************
protected int getRow_page_limit(int page, int row_per_page) throws Exception {
if(page<=0) page=1;
int skipRecords = row_per_page*(page-1);
int row_page_limit = skipRecords + row_per_page;
return row_page_limit;
}
/*
protected int getMaxPage(int totRow, int rows_per_page) {
int pages = -1;
try {
pages = totRow/rows_per_page;
int resto = totRow%rows_per_page;
if(resto!=0) pages++;
if(pages==0) pages = 1;
}
catch (Exception ex) {
}
finally {
return pages;
}
}
*/
public static void main(String[] args) {
//BaseDAO baseDAO1 = new BaseDAO();
}
}

View File

@@ -0,0 +1,536 @@
package it.valueteam.gnpsim.database;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRecExt;
import it.valueteam.gnp.obj.ProcessMapper;
import it.valueteam.gnp.obj.StatoRichiestaRec;
import it.valueteam.gnpsim.obj.CausaliRifiutoOloDTO;
import it.valueteam.gnpsim.obj.OloReplyDto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class SimDAO extends BaseDAO{
// private static final int TIPO_RICH_STANDARD=1;
private static final int TIPO_RICH_DOPPIO_DONATING=2;
public static int ALL_STATES_PITAGORA_XDSL = -1;
private static String sqlGetAllOlo="select * from GNP_ANAG_OLO where FLAG_ATTIVO=1";
private static String sqlGetRequestToReply = "select OLO.CODICE_ORDINE_RECIPIENT AS CODICE_ORDINE_RECIPIENT,REC.COR AS COR, REC.COR2 AS COR2 from GNP_RICHIESTE_REC REC, " +
"GNP_OLO_RICHIESTE_OUT OLO WHERE REC.COW=? AND REC.PROCESSO IN ('"+ProcessMapper.proc_RIENTRO_ADSL+"','"+ProcessMapper.proc_RIENTRO_FONIA+"','"+ProcessMapper.proc_RIENTRO_NAKED+"') " +
"AND OLO.ID_RICHIESTA=REC.ID_RICHIESTA AND REC.STATO=? AND ROWNUM<100 AND DATA_CREAZIONE=(select MAX(DATA_CREAZIONE) from GNP_OLO_RICHIESTE_OUT WHERE ID_RICHIESTA = OLO.ID_RICHIESTA)";
private static String sqlGetRequestToReplyDoppioDonating =
"SELECT OLO.CODICE_ORDINE_RECIPIENT AS CODICE_ORDINE_RECIPIENT," +
"REC.COR AS COR, REC.COR AS COR2 " +
"FROM GNP_OLO_RICHIESTE_OUT OLO, GNP_DOPPIO_DONATING_OLO_BRIDGE REC " +
"WHERE REC.COW = ? " +
"AND OLO.id_richiesta_dd = REC.unique_id " +
"AND REC.STATO = ? " +
"AND ROWNUM < 100 " +
"AND OLO.CODICE_ORDINE_RECIPIENT = (SELECT MAX(CODICE_ORDINE_RECIPIENT) " +
" FROM GNP_OLO_RICHIESTE_OUT " +
" WHERE ID_RICHIESTA_DD = OLO.ID_RICHIESTA_DD)";
private static String sqlGetRequestToReplyFromAllStates = "select OLO.CODICE_ORDINE_RECIPIENT AS CODICE_ORDINE_RECIPIENT,REC.COR AS COR, REC.COR2 AS COR2 from GNP_RICHIESTE_REC REC, " +
"GNP_OLO_RICHIESTE_OUT OLO WHERE REC.COW=? AND REC.PROCESSO IN ('"+ProcessMapper.proc_RIENTRO_ADSL+"','"+ProcessMapper.proc_RIENTRO_FONIA+"','"+ProcessMapper.proc_RIENTRO_NAKED+"') " +
"AND OLO.ID_RICHIESTA=REC.ID_RICHIESTA AND REC.STATO IN (13,2) AND ROWNUM<100 AND DATA_CREAZIONE=(select MAX(DATA_CREAZIONE) from GNP_OLO_RICHIESTE_OUT WHERE ID_RICHIESTA = OLO.ID_RICHIESTA)";
private static String sqlGetRequestToReplyFromAllStatesDoppioDonating =
"SELECT OLO.CODICE_ORDINE_RECIPIENT AS CODICE_ORDINE_RECIPIENT," +
"REC.COR AS COR, REC.COR AS COR2 " +
"FROM GNP_OLO_RICHIESTE_OUT OLO, GNP_DOPPIO_DONATING_OLO_BRIDGE REC " +
"WHERE REC.COW = ? " +
"AND OLO.id_richiesta_dd = REC.unique_id " +
"AND REC.STATO IN(2, 3, 5) " +
"AND ROWNUM < 100 " +
"AND OLO.CODICE_ORDINE_RECIPIENT = (SELECT MAX(CODICE_ORDINE_RECIPIENT) " +
" FROM GNP_OLO_RICHIESTE_OUT " +
" WHERE ID_RICHIESTA_DD = OLO.ID_RICHIESTA_DD)";
private static String sqlGetAll_TO_SEND_PITAGORA_XDSL = "select * from GNP_RICHIESTE_REC where stato in (6,15) and processo IN ('"+ProcessMapper.proc_RIENTRO_ADSL+"','"+ProcessMapper.proc_RIENTRO_ADSL_BKL+"','"+ProcessMapper.proc_RIENTRO_NAKED+"','"+ProcessMapper.proc_RIENTRO_NAKED_BKL+"') and da_inviare=0 and ROWNUM<100";
private static String sqlGetByStato_TO_SEND_PITAGORA_XDSL = "select * from GNP_RICHIESTE_REC where (STATO=? OR STATO=6) and processo IN ('"+ProcessMapper.proc_RIENTRO_ADSL+"','"+ProcessMapper.proc_RIENTRO_ADSL_BKL+"','"+ProcessMapper.proc_RIENTRO_NAKED+"','"+ProcessMapper.proc_RIENTRO_NAKED_BKL+"') and da_inviare=0 and ROWNUM<100";
private static String sqlGetAll_TO_SEND_PITAGORA = "select * from GNP_RICHIESTE_REC where stato="+StatoRichiestaRec.INVIATAPITAGORA+" and processo IN ('"+ProcessMapper.proc_RIENTRO_FONIA+"','"+ProcessMapper.proc_RIENTRO_FONIA_BKL+"','"+ProcessMapper.proc_RIENTRO_NPg+"') and da_inviare=0 and ROWNUM<100";
private static String sqlGetAll_ATTESA_ESITO_A375 = "SELECT * FROM GNP_RICHIESTE_REC WHERE stato IN (" + StatoRichiestaRec.ATTESAVERIFICA + "," + StatoRichiestaRec.ATTESAVERIFICA_FONIA + "," + StatoRichiestaRec.ATTESAVERIFICA_DATI +")";
private static String sqlGetCausaliOloByTipoComunicazione = "select TC.CODICE AS TIPO_COMUNICAZIONE," +
" CF.CODICE AS CAUSALE_RIFIUTO, MR.CODICE AS CODICE_MOTIVO_RIFIUTO," +
" MR.DESCRIZIONE AS MOTIVO_RIFIUTO" +
" from GNP_ANAG_OLO_TIPO_COM TC," +
" GNP_ANAG_OLO_COD_MOTIVO_RIF MR," +
" GNP_ANAG_OLO_CAUSALE_RIFIUTO CF," +
" GNP_ANAG_OLO_CAUSALE_MOT_RIF CMR" +
" WHERE TC.CODICE = ?" +
" AND TC.CODICE=CF.CODICE_TIPO_COM" +
" AND CF.CODICE = CMR.CODICE_RIFIUTO" +
" AND CMR.ID_MOTIVO_RIFIUTO = MR.PROG_ID";
private static String sqlGetRichiestaByIdEsigenza = "SELECT * FROM GNP_RICHIESTE_REC WHERE ID_ESIGENZA = ?";
private static String sqlGetRichiestaExtById = "SELECT * FROM GNP_RICHIESTE_REC_EXT WHERE ID_RICHIESTA = ?";
private static String sqlGetValidCos="select COS from GNP_ANAGRAFICA_COS";
private static String sqlGetValidMarcaggio="select CODICE from GNP_ANAG_MARCAGGIO";
private static String sqlGetValidCnalaeVendita="select CODICE from GNP_ANAG_CANALE_VENDITA";
public SimDAO() {
}
@SuppressWarnings("unchecked")
public String[] getAllOlo() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String[] result = null;
Vector _res = new Vector();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetAllOlo);
rs = pstmt.executeQuery();
while (rs.next())
_res.add(rs.getString("COD_OLO"));
if (! (_res == null || _res.size() == 0)) {
result = new String[_res.size()];
result = (String[]) _res.toArray(result);
}
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public OloReplyDto[] getRequestToReply(String olo, int stato, int tipoRichieste) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
OloReplyDto[] result = null;
Vector _res = new Vector();
try {
conn = getConnection();
if(stato==-1){
if(tipoRichieste == TIPO_RICH_DOPPIO_DONATING)
pstmt = conn.prepareStatement(sqlGetRequestToReplyFromAllStatesDoppioDonating);
else
pstmt = conn.prepareStatement(sqlGetRequestToReplyFromAllStates);
pstmt.setString(1,olo);
}else{
if(tipoRichieste == TIPO_RICH_DOPPIO_DONATING)
pstmt = conn.prepareStatement(sqlGetRequestToReplyDoppioDonating);
else
pstmt = conn.prepareStatement(sqlGetRequestToReply);
pstmt.setString(1,olo);
pstmt.setInt(2, stato);
}
rs = pstmt.executeQuery();
while (rs.next()){
OloReplyDto rec = new OloReplyDto();
rec.setIdEsigenza(rs.getString("CODICE_ORDINE_RECIPIENT"));
rec.setCor(rs.getString("COR"));
rec.setCor2(rs.getString("COR2"));
_res.add(rec);
}
if (! (_res == null || _res.size() == 0)) {
result = new OloReplyDto[_res.size()];
result = (OloReplyDto[]) _res.toArray(result);
}
}
catch (Exception ex) {
throw ex;
}
finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public GnpRichiesteRec[] getAll_TO_SEND_PITAGORA_XDSL(int stato) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
GnpRichiesteRec[] result = null;
List resultList = new ArrayList();
try {
conn = getConnection();
if(stato==ALL_STATES_PITAGORA_XDSL){
pstmt = conn.prepareStatement(sqlGetAll_TO_SEND_PITAGORA_XDSL);
}else{
pstmt = conn.prepareStatement(sqlGetByStato_TO_SEND_PITAGORA_XDSL);
pstmt.setInt(1, stato);
}
rs = pstmt.executeQuery();
while (rs.next()) {
resultList.add(createRichiesteRec(rs));
}
result = new GnpRichiesteRec[resultList.size()];
if (resultList.size() > 0) {
result = (GnpRichiesteRec[]) resultList.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public GnpRichiesteRec[] getAll_ATTESA_ESITO_A375(int maxNum) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
GnpRichiesteRec[] result = null;
List resultList = new ArrayList();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetAll_ATTESA_ESITO_A375);
rs = pstmt.executeQuery();
int num = 0;
while (rs.next() && (maxNum == -1 || maxNum > num++)) {
resultList.add(createRichiesteRec(rs));
}
result = new GnpRichiesteRec[resultList.size()];
if (resultList.size() > 0) {
result = (GnpRichiesteRec[]) resultList.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public CausaliRifiutoOloDTO[] getCausaliRifiutoOloByTipoComunicazione(int tipoComunicazione) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
CausaliRifiutoOloDTO[] result = null;
Vector _res = new Vector();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetCausaliOloByTipoComunicazione);
pstmt.setInt(1, tipoComunicazione);
rs = pstmt.executeQuery();
while (rs.next()){
CausaliRifiutoOloDTO causaliRifiutoOlo = new CausaliRifiutoOloDTO();
causaliRifiutoOlo.setTipoComunicazione(String.valueOf(rs.getLong("TIPO_COMUNICAZIONE")));
causaliRifiutoOlo.setCodiceMotivo_rifiuto(String.valueOf(rs.getLong("CODICE_MOTIVO_RIFIUTO")));
causaliRifiutoOlo.setCausaleRifiuto(String.valueOf(rs.getLong("CAUSALE_RIFIUTO")));
causaliRifiutoOlo.setMotivoRifiuto(rs.getString("MOTIVO_RIFIUTO"));
_res.add(causaliRifiutoOlo);
}
if (! (_res == null || _res.size() == 0)) {
result = new CausaliRifiutoOloDTO[_res.size()];
result = (CausaliRifiutoOloDTO[]) _res.toArray(result);
}
}
catch (Exception ex) {
throw ex;
}
finally {
closeAll(rs, pstmt, conn);
}
return result;
}
public GnpRichiesteRec getByIdEsigenza(String idEsigenza)
throws Exception
{
GnpRichiesteRec richiesta = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetRichiestaByIdEsigenza);
pstmt.setString(1, idEsigenza);
rs = pstmt.executeQuery();
if (rs.next()){
richiesta = createRichiesteRec(rs);
}
}
catch (Exception ex) {
throw ex;
}
finally {
closeAll(rs, pstmt, conn);
}
return richiesta;
}
public GnpRichiesteRecExt getRichiestaExtById(Long idRichiesta)
throws Exception
{
GnpRichiesteRecExt richiestaExt = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetRichiestaExtById);
pstmt.setLong(1, idRichiesta);
rs = pstmt.executeQuery();
if (rs.next()){
richiestaExt = createRichiestaRecExt(rs);
}
}
catch (Exception ex) {
throw ex;
}
finally {
closeAll(rs, pstmt, conn);
}
return richiestaExt;
}
@SuppressWarnings("unchecked")
public String[] getValidCos() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String[] result = null;
Vector _res = new Vector();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetValidCos);
rs = pstmt.executeQuery();
while (rs.next())
_res.add(rs.getString("COS"));
if (!(_res == null || _res.size() == 0)) {
result = new String[_res.size()];
result = (String[]) _res.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
private GnpRichiesteRec createRichiesteRec(ResultSet rs) throws Exception{
GnpRichiesteRec richiestaRec = new GnpRichiesteRec();
richiestaRec.setIdEsigenza(rs.getString("ID_ESIGENZA"));
richiestaRec.setIdRichiesta(rs.getLong("ID_RICHIESTA"));
richiestaRec.setDaInviare(new Long(rs.getInt("DA_INVIARE")));
richiestaRec.setDataRicezioneRichiesta(rs.getDate("DATA_RICEZIONE_RICHIESTA"));
richiestaRec.setProcesso(rs.getString("PROCESSO"));
richiestaRec.setPiattaformaProvenienza(rs.getString("PIATTAFORMA_PROVENIENZA"));
richiestaRec.setCanaleProvenienza(rs.getString("CANALE_PROVENIENZA"));
richiestaRec.setDac(rs.getDate("DAC"));
richiestaRec.setDfw(rs.getDate("DFW"));
richiestaRec.setCos(rs.getString("COS"));
richiestaRec.setStato(new Long(rs.getInt(3)));
richiestaRec.setSla(new Long(rs.getInt("SLA")));
richiestaRec.setDet(rs.getDate("DET"));
richiestaRec.setCodiceOperatoreRecipient(rs.getString("CODICE_OPERATORE_RECIPIENT"));
richiestaRec.setCodiceSessioneOlo(rs.getString("CODICE_SESSIONE_OLO"));
richiestaRec.setCow(rs.getString("COW"));
richiestaRec.setNumeroTelefono(rs.getString("NUMERO_TELEFONO"));
richiestaRec.setRecapitoAlternativo(rs.getString("RECAPITO_ALTERNATIVO"));
richiestaRec.setCodiceFiscalePartitaIva(rs.getString("CODICE_FISCALE_PARTITA_IVA"));
richiestaRec.setNominativoCliente(rs.getString("NOMINATIVO_CLIENTE"));
richiestaRec.setCor(rs.getString("COR"));
richiestaRec.setCos2(rs.getString("COS2"));
richiestaRec.setCor2(rs.getString("COR2"));
richiestaRec.setDn1(rs.getString("DN1"));
richiestaRec.setDn2(rs.getString("DN2"));
richiestaRec.setDn3(rs.getString("DN3"));
richiestaRec.setDn4(rs.getString("DN4"));
richiestaRec.setDn5(rs.getString("DN5"));
richiestaRec.setDn6(rs.getString("DN6"));
richiestaRec.setDn7(rs.getString("DN7"));
richiestaRec.setDn8(rs.getString("DN8"));
richiestaRec.setDn9(rs.getString("DN9"));
richiestaRec.setDn10(rs.getString("DN10"));
richiestaRec.setMutataVolonta(new Long(rs.getInt("MUTATA_VOLONTA")));
richiestaRec.setAtterraggio(rs.getString("ATTERRAGGIO"));
richiestaRec.setDataCheck(rs.getDate("DATA_CHECK"));
return richiestaRec;
}
private GnpRichiesteRecExt createRichiestaRecExt(ResultSet rs)
throws Exception
{
GnpRichiesteRecExt richiestaExt = new GnpRichiesteRecExt();
richiestaExt.setCanaleVendita(rs.getString("CANALE_VENDITA"));
richiestaExt.setCodiceRifiutoOlo(rs.getLong("CODICE_RIFIUTO_OLO"));
richiestaExt.setDataInvioOlo(rs.getDate("DATA_INVIO_OLO"));
richiestaExt.setDataInvioPitagora(rs.getDate("DATA_INVIO_PITAGORA"));
richiestaExt.setDataRicezioneKoOlo(rs.getDate("DATA_RICEZIONE_KO_OLO"));
richiestaExt.setDataRicezioneKoPitagora(rs.getDate("DATA_RICEZIONE_KO_PITAGORA"));
richiestaExt.setDataRicezionePic(rs.getDate("DATA_RICEZIONE_PIC"));
richiestaExt.setDataVariazioneStato(rs.getDate("DATA_VARIAZIONE_STATO"));
richiestaExt.setIdRichiesta(rs.getLong("ID_RICHIESTA"));
richiestaExt.setMarcaggio(rs.getString("MARCAGGIO"));
richiestaExt.setMotivoRifiutoOlo(rs.getString("MOTIVO_RIFIUTO_OLO"));
richiestaExt.setMotivoRifiutoPitagora(rs.getString("MOTIVO_RIFIUTO_PITAGORA"));
richiestaExt.setNomeFileOlo(rs.getString("NOME_FILE_OLO"));
richiestaExt.setNomeFilePitagora(rs.getString("NOME_FILE_PITAGORA"));
richiestaExt.setNroInviiPitagora(rs.getLong("NRO_INVII_PITAGORA"));
return richiestaExt;
}
@SuppressWarnings("unchecked")
public String[] getValidCanaleVendita() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String[] result = null;
List _res = new ArrayList();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetValidCnalaeVendita);
rs = pstmt.executeQuery();
while (rs.next())
_res.add(rs.getString("CODICE"));
if (!(_res == null || _res.size() == 0)) {
result = new String[_res.size()];
result = (String[])_res.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public String[] getValidMarcaggio() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String[] result = null;
List _res = new ArrayList();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetValidMarcaggio);
rs = pstmt.executeQuery();
while (rs.next())
_res.add(rs.getString("CODICE"));
if (!(_res == null || _res.size() == 0)) {
result = new String[_res.size()];
result = (String[])_res.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
@SuppressWarnings("unchecked")
public GnpRichiesteRec[] getAll_TO_SEND_PITAGORA_REGOLATORIO() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
GnpRichiesteRec[] result = null;
List resultList = new ArrayList();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sqlGetAll_TO_SEND_PITAGORA);
rs = pstmt.executeQuery();
while (rs.next()) {
resultList.add(createRichiesteRec(rs));
}
result = new GnpRichiesteRec[resultList.size()];
if (resultList.size() > 0) {
result = (GnpRichiesteRec[]) resultList.toArray(result);
}
} catch (Exception ex) {
throw ex;
} finally {
closeAll(rs, pstmt, conn);
}
return result;
}
}

View File

@@ -0,0 +1,14 @@
package it.valueteam.gnpsim.generator.flat;
public interface FlatGeneratorIF {
public static final int NO_DAC = 0;
public static final String ESITO_OK= "OK";
public static final String ESITO_KO= "KO";
public static final String TIPO_COM_PIC="5";
public static final String TIPO_COM_VALIDAZIONE="6";
public static final String CAUSALE_RIF_FORMALE="1";
public static final String CAUSALE_RIF_GESTIONALE="2";
public static final String CAUSALE_RIF_COD_SESS="3";
public void generateFlat(String[] args) throws Exception;
}

View File

@@ -0,0 +1,248 @@
/**
*
*/
package it.valueteam.gnpsim.generator.flat;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.utility.DateUtils;
import it.valueteam.gnpsim.utility.IOUtility;
import it.valueteam.gnpsim.utility.SimConfFile;
import it.valueteam.infotracciati.FlowMaker;
import it.valueteam.infotracciati.exception.BadFieldFormatException;
import it.valueteam.infotracciati.exception.BadFlowException;
import it.valueteam.infotracciati.exception.BadPositionException;
import it.valueteam.infotracciati.exception.FillPositionException;
import it.valueteam.infotracciati.exception.GenericException;
import it.valueteam.infotracciati.exception.NotValidXMLException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
/**
* @author Carmelo
*
*/
public class FlatPitagoraRegolatorioGenerator extends SimGenerator implements FlatGeneratorIF {
private static Properties propReg = SimConfFile.getInstance().ReadSection("pitagoraregolatorio");
private static String TIPO_COM = "TIPO_COM";
private static String COW = "COW";
private static String COD_ORD_REC = "COD_ORD_REC";
private static String COR1 = "COR1";
private static String COD_SESS_1 = "COD_SESS_1";
private static String COR2 = "COR2";
private static String COD_SESS_2 = "COD_SESS_2";
private static String DN1 = "DN1";
private static String DN2 = "DN2";
private static String DN3 = "DN3";
private static String DN4 = "DN4";
private static String DN5 = "DN5";
private static String DN6 = "DN6";
private static String DN7 = "DN7";
private static String DN8 = "DN8";
private static String DN9 = "DN9";
private static String DN10 = "DN10";
private static String STATO_RICHIESTA = "STATO_RICHIESTA";
private static String CAUSALE_RIFIUTO = "CAUSALE_RIFIUTO";
private static String COD_MOT_RIF = "COD_MOT_RIF";
private static String MOTIVO_RIF = "MOTIVO_RIF";
private static String DATA_ESPL = "DATA_ESPL";
private static String DAC = "DAC";
private static String DATA_NOTIFICA = "DATA_NOTIFICA";
private static String DRO = "DRO";
private static final String DATE_PATTERN = "dd/MM/yyyy";
private static final String FLOW_TYPE = "NOTIFICA_IN";
/* (non-Javadoc)
* @see it.valueteam.gnpsim.generator.flat.FlatGeneratorIF#generateFlat(java.lang.String[])
*/
public void generateFlat(String[] args) throws Exception {
if(args.length<4)
throw new IllegalArgumentException("Numero di parametri insufficienti");
try{
String tipoFlusso=args[0]; //5, 6, ALL
String esito = args[1]; //OK,KO
int aggiungiADac = NO_DAC;
String fileNameCSV = null;
String fileNameCTR = null;
GnpRichiesteRec[] richieste = null;
String[] records = null;
String codModRif = null;
SimDAO dao = new SimDAO();
if(!args[2].equals("NULL"))
aggiungiADac = Integer.parseInt(args[2]);
if(!args[3].equals("NULL"))
codModRif = args[3];
String dateFileName = toString(new Date(),
propReg.getProperty("FORMAT_DATE_FILE_NAME_REG"));
fileNameCSV = propReg.getProperty("PREFIX_FILE_VALIDAZIONE_REG")+dateFileName+propReg.getProperty("SUFFIX_FILE_VALIDAZIONE_REG")+propReg.getProperty("EXTENSION_FILE_VALIDAZIONE_REG");
fileNameCTR = propReg.getProperty("PREFIX_FILE_VALIDAZIONE_REG")+dateFileName+propReg.getProperty("SUFFIX_FILE_VALIDAZIONE_REG")+propReg.getProperty("EXTENSION_FILE_CTR_REG");
richieste=dao.getAll_TO_SEND_PITAGORA_REGOLATORIO();
if(richieste!=null && richieste.length>0){
records = createRecords(richieste, esito, aggiungiADac,codModRif, tipoFlusso);
IOUtility.writeFile(propReg.getProperty("GEN_PATH_REG") +fileNameCSV,records);
System.out.println("Creato File " + fileNameCSV);
IOUtility.writeFile(propReg.getProperty("GEN_PATH_REG") +fileNameCTR,null);
System.out.println("Creato File " + fileNameCTR);
}else{
System.out.println("NESSUN FILE DA CREARE");
}
}catch(Exception ex){
System.out.println("ERRORE DURANTE LA GENERAZIONE DEL FILE PER PITAGORA XDSL");
ex.printStackTrace();
}
}
/**
* @param richieste
* @param esito
* @param fileNameCSV
* @param aggiungiADac
* @param codModRif
* @return
* @throws Exception
*/
private String[] createRecords(GnpRichiesteRec[] richieste, String esito, int aggiungiADac, String codModRif, String tipoCom) throws Exception {
String[] records = new String[richieste.length];
System.out.println("NEW FLOWMAKER: PATH FILE - " + propReg.getProperty("PATH_INFOTRACCIATI_REG"));
FlowMaker flowMaker = null;
try {
flowMaker = new FlowMaker(propReg.getProperty("PATH_INFOTRACCIATI_REG"), FLOW_TYPE);
for (int i = 0; i < richieste.length; i++) {
String record = null;
try {
System.out.print("GENERATE FORMATTED RECORD " + i + "\n");
record = flowMaker.generateFormattedRecord(getMap(richieste[i],
esito, tipoCom, codModRif, aggiungiADac), true);
}
catch (BadPositionException ex1) {
ex1.printStackTrace();
throw new Exception();
}
catch (FillPositionException ex1) {
ex1.printStackTrace();
throw new Exception();
}
catch (BadFieldFormatException ex1) {
ex1.printStackTrace();
throw new Exception();
}
records[i] = record;
}
return records;
}
catch (NotValidXMLException ex) {
ex.printStackTrace();
throw new Exception();
}
catch (BadFlowException ex) {
ex.printStackTrace();
throw new Exception();
}
catch (ValidationException ex) {
ex.printStackTrace();
throw new Exception();
}
catch (IOException ex) {
ex.printStackTrace();
throw new Exception();
}
catch (MarshalException ex) {
ex.printStackTrace();
throw new Exception();
}
catch (GenericException ex) {
ex.printStackTrace();
throw new Exception();
}
}
/**
* @param rec
* @param esito
* @return
* @throws Exception
*/
private Map getMap(GnpRichiesteRec rec, String esito, String tipoCom, String codiceMotRif, int AggDac) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
result.put(TIPO_COM, tipoCom);
result.put(COW, rec.getCow());
result.put(COD_ORD_REC, rec.getIdEsigenza());
result.put(COR1, rec.getCor());
if(rec.getProcesso().equals("NPg") || rec.getProcesso().equals("FONIA_BKL")){
result.put(COD_SESS_1, "codiceSessionOLO");
}else{
result.put(COD_SESS_1, rec.getCodiceSessioneOlo());
}
result.put(COR2, rec.getCor2());
result.put(COD_SESS_2, "");
result.put(DN1, rec.getDn1());
result.put(DN2, rec.getDn2());
result.put(DN3, rec.getDn3());
result.put(DN4, rec.getDn4());
result.put(DN5, rec.getDn5());
result.put(DN6, rec.getDn6());
result.put(DN7, rec.getDn7());
result.put(DN8, rec.getDn8());
result.put(DN9, rec.getDn9());
result.put(DN10, rec.getDn10());
if(ESITO_KO.equals(esito)){
result.put(STATO_RICHIESTA, "1");
if(TIPO_COM_PIC.equals(tipoCom)){
result.put(CAUSALE_RIFIUTO, CAUSALE_RIF_FORMALE);
}else{
result.put(CAUSALE_RIFIUTO, CAUSALE_RIF_GESTIONALE);
}
result.put(COD_MOT_RIF, codiceMotRif);
result.put(MOTIVO_RIF, "descrizione motivo del rifiuto");
}else{
result.put(STATO_RICHIESTA, "0");
result.put(COD_MOT_RIF, "");
result.put(MOTIVO_RIF, "");
result.put(CAUSALE_RIFIUTO, "");
}
result.put(DATA_ESPL, DateUtils.toDate(toString(new Date(), DATE_PATTERN), DATE_PATTERN));
result.put(DAC, AggDac>0? DateUtils.aggiungiGiorniLavorativiTodate(rec.getDacCalcolata(), AggDac):rec.getDac());
result.put(DATA_NOTIFICA, DateUtils.toDate(toString(new Date(), DATE_PATTERN), DATE_PATTERN));
result.put(DRO, DateUtils.toDate(toString(new Date(), DATE_PATTERN), DATE_PATTERN));
return result;
}
}

View File

@@ -0,0 +1,291 @@
package it.valueteam.gnpsim.generator.flat;
import it.telecomitalia.xsd.crm.xdsl.order.DatiPrequalifica;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.INTESTAZIONE;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIACCESSO;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIMIGRAZIONI;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIPrequalifica;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIREFERENTE;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIUserVlan;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIVC;
import it.telecomitalia.xsd.crm.xdsl.order.NOTIFICAOLOBITSTREAMDocument.NOTIFICAOLOBITSTREAM.RICHIESTA.DATIVLAN;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.DATI_ACCESSO;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.DATI_MIGRAZIONI;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.DATI_VC;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.INTESTAZIONE;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.NOTIFICA_OLO_BITSTREAM;
//import it.valueteam.gnp.dao.xml.pitagoraxdsl.pitagoraxdsltodbcfx.RICHIESTA;
import it.valueteam.gnp.obj.StatoRichiestaRec;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.utility.DateUtils;
import it.valueteam.gnpsim.utility.IOUtility;
import it.valueteam.gnpsim.utility.SimConfFile;
import it.valueteam.gnpsim.utility.XmlUtility;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
public class FlatPitagoraXdslGenerator extends SimGenerator implements FlatGeneratorIF{
private static Properties propXdsl = SimConfFile.getInstance().ReadSection("pitagoraxdsl");
//campi fissi del tracciato
private static final String DATE_10_FORMAT= "dd/MM/yyyy";
private static final String DATE_8_FORMAT= "ddMMyyyy";
private static final String DATE_16_FORMAT= "dd/MM/yyyy HH:mm";
private static final String INTEST_SISTEMA= "PITAGORA";
private static final String INTEST_COD_ISP= "002";
private static final String EMPTY= "";
private static final String COD_ISP_TELECOM= "002";
private static final String TIPO_RICHIESTA_MIG="MIG";
private static final String TIPO_SERVIZIO_I="I";
@SuppressWarnings("unused")
private static final String STATO_ACQUISIZIONE="AQ";
@SuppressWarnings("unused")
private static final String STATO_VER_TECNICHE="VT";
@SuppressWarnings("unused")
private static final String STATO_ACCETTAZIONE="AC";
private static final String COD_OPERATORE_REC= "TLC";
public FlatPitagoraXdslGenerator() {
}
/**
* generateFlat
*
* @param args String[]
* @return String
*/
public void generateFlat(String[] args) throws Exception{
if(args.length<5)
throw new IllegalArgumentException("Numero di parametri insufficienti");
try{
String tipoFlusso=args[0]; //5, 6, ALL
String esito = args[1]; //OK,KO
String stato = args[2]; //AQ|AC|CS|VT
int aggiungiADac = NO_DAC;
String fileNameXML = null;
String fileNameCTR = null;
GnpRichiesteRec[] richieste = null;
String xml = null;
String codModRif = null;
if(!args[3].equals("NULL"))
aggiungiADac = Integer.parseInt(args[3]);
if(!args[4].equals("NULL"))
codModRif = args[4];
String dateFileName = toString(new Date(),
propXdsl.getProperty("FORMAT_DATE_FILE_NAME"));
fileNameXML = propXdsl.getProperty("PREFIX_FILE_VALIDAZIONE")+dateFileName+propXdsl.getProperty("SUFFIX_FILE_VALIDAZIONE")+propXdsl.getProperty("EXTENSION_FILE_VALIDAZIONE");
fileNameCTR = propXdsl.getProperty("PREFIX_FILE_VALIDAZIONE")+dateFileName+propXdsl.getProperty("SUFFIX_FILE_VALIDAZIONE")+propXdsl.getProperty("EXTENSION_FILE_CTR");
richieste=getRequestToSend(tipoFlusso);
if(richieste!=null && richieste.length>0){
xml = createXml(richieste, esito, fileNameXML, aggiungiADac,codModRif, tipoFlusso.equals("ALL")?true:false, stato);
String[] records= {xml};
IOUtility.writeFile(propXdsl.getProperty("GEN_PATH_XDSL") +fileNameXML,records);
System.out.println("Creato File " + fileNameXML);
IOUtility.writeFile(propXdsl.getProperty("GEN_PATH_XDSL") +fileNameCTR,null);
System.out.println("Creato File " + fileNameCTR);
}else{
System.out.println("NESSUN FILE DA CREARE");
}
}catch(Exception ex){
System.out.println("ERRORE DURANTE LA GENERAZIONE DEL FILE PER PITAGORA XDSL");
ex.printStackTrace();
}
}
private GnpRichiesteRec[] getRequestToSend(String tipoFlusso) throws Exception {
SimDAO dao = new SimDAO();
GnpRichiesteRec[] richieste = null;
int stato = SimDAO.ALL_STATES_PITAGORA_XDSL;
if(tipoFlusso.equals("ALL")){
richieste = dao.getAll_TO_SEND_PITAGORA_XDSL(SimDAO.ALL_STATES_PITAGORA_XDSL);
}else{
if(tipoFlusso.equals(TIPO_COM_PIC)){
stato = StatoRichiestaRec.INVIATAPITAGORA;
}else if (tipoFlusso.equals(TIPO_COM_VALIDAZIONE)){
stato = StatoRichiestaRec.ACQUISITAPITAGORA;
}else{
throw new Exception("TIPO FLUSSO SCONOSCIUTO");
}
richieste = dao.getAll_TO_SEND_PITAGORA_XDSL(stato);
}
System.out.println("TROVATE " + richieste.length + " RICHIESTE DA GENERARE");
return richieste;
}
private String createXml(GnpRichiesteRec[] list, String esito, String nomeFile, int aggiungiADac, String codMotRif, boolean all, String stato) throws Exception{
//componenti del file xml
NOTIFICAOLOBITSTREAMDocument doc = NOTIFICAOLOBITSTREAMDocument.Factory.newInstance();
NOTIFICAOLOBITSTREAM notifica =doc.addNewNOTIFICAOLOBITSTREAM();
RICHIESTA richiesta = null;
INTESTAZIONE intest = null;
//creo l'intestazione
intest = createIntestazione(nomeFile);
ArrayList<RICHIESTA> app = new ArrayList<RICHIESTA>();
for(int i=0; i<list.length; i++){
notifica.setINTESTAZIONE(intest);
richiesta = createRichiesta(createDatiAccesso(list[i], getTipoCom(list[i].getStato()), esito, stato),
createDatiMigrazione(list[i], getTipoCom(list[i].getStato()), esito, aggiungiADac, codMotRif));
app.add(richiesta);
if (all&&list[i].getStato()==StatoRichiestaRec.INVIATAPITAGORA) {
notifica.setINTESTAZIONE(intest);
richiesta = createRichiesta(createDatiAccesso(list[i], TIPO_COM_VALIDAZIONE, esito, stato),
createDatiMigrazione(list[i], TIPO_COM_VALIDAZIONE, esito, aggiungiADac, codMotRif));
app.add(richiesta);
}
}
RICHIESTA[] rics = new RICHIESTA[app.size()];
for(int h=0;h<app.size();h++){
rics[h]=app.get(h);
}
notifica.setRICHIESTAArray(rics);
return doc.xmlText();
}
private RICHIESTA createRichiesta(DATIACCESSO accesso, DATIMIGRAZIONI migrazione) {
RICHIESTA richiesta = RICHIESTA.Factory.newInstance();
richiesta.setDATIACCESSO(accesso);
richiesta.setDATIMIGRAZIONI(migrazione);
richiesta.setDATIVC(DATIVC.Factory.newInstance());
richiesta.setDATIPrequalifica(DATIPrequalifica.Factory.newInstance());
richiesta.setDATIREFERENTE(DATIREFERENTE.Factory.newInstance());
richiesta.setDATIUserVlan(DATIUserVlan.Factory.newInstance());
richiesta.setDATIVLAN(DATIVLAN.Factory.newInstance());
return richiesta;
}
private String getTipoCom(Long stato) throws Exception {
if (StatoRichiestaRec.INVIATAPITAGORA==stato.intValue()) {
return TIPO_COM_PIC;
}
else if (StatoRichiestaRec.ACQUISITAPITAGORA==stato.intValue()){
return TIPO_COM_VALIDAZIONE;
}
else {
throw new Exception("Impossibile determinare il tipo di comunicazione per lo stato: " +stato);
}
}
private DATIACCESSO createDatiAccesso(GnpRichiesteRec rec, String tipoCom, String esito, String stato) throws Exception {
DATIACCESSO datiAccesso = DATIACCESSO.Factory.newInstance();
// populateBeanWithUnicValue(datiAccesso, EMPTY);
datiAccesso.setCODICEISP(COD_ISP_TELECOM);
datiAccesso.setCODICEORDINEISP(rec.getIdEsigenza());
datiAccesso.setTIPORICHIESTA(TIPO_RICHIESTA_MIG);
datiAccesso.setTIPOSERVIZIO(TIPO_SERVIZIO_I);
datiAccesso.setDATANOTIFICA(DateUtils.toString(new Date(),DATE_8_FORMAT));
datiAccesso.setSTATO(stato);
// if (TIPO_COM_PIC.equals(tipoCom)) {
// datiAccesso.setSTATO(STATO_ACQUISIZIONE);
// }
// else if (TIPO_COM_VALIDAZIONE.equals(tipoCom)) {
// if(esito.equals(ESITO_KO)){
// datiAccesso.setSTATO(STATO_VER_TECNICHE);
// }else{
// datiAccesso.setSTATO(STATO_ACCETTAZIONE);
// }
// }
// else {
// throw new Exception("Tipo Comunicazione Errato");
// }
return datiAccesso;
}
private DATIMIGRAZIONI createDatiMigrazione(GnpRichiesteRec rec,String tipoCom, String esito, int aggiungiADac, String codMotRif) throws Exception {
DATIMIGRAZIONI datiMig = DATIMIGRAZIONI.Factory.newInstance();
Date dataRif = new Date();
// populateBeanWithUnicValue(datiMig, EMPTY);
datiMig.setCODICEOPERATORERECIPIENT(COD_OPERATORE_REC);
datiMig.setCODICEORDINERECIPIENT(rec.getIdEsigenza());
datiMig.setCODICERISORSA1(rec.getCor());
datiMig.setDATAESPLETAMENTOORDINE(DateUtils.toString(dataRif, DATE_10_FORMAT));
datiMig.setDATANOTIFICA(DateUtils.toString(dataRif, DATE_10_FORMAT));
datiMig.setDATARICEZIONEORDINE(DateUtils.toString(dataRif, DATE_10_FORMAT));
datiMig.setSTATO(esito);
datiMig.setDAC(DateUtils.toString(rec.getDac(), DATE_10_FORMAT));
datiMig.setCODICEOPERATOREDONATING(rec.getCow());
datiMig.setCODICEORDINEPITAGORA(rec.getIdEsigenza());
datiMig.setCODICESESSIONE1(rec.getCodiceSessioneOlo());
if(rec.getDacCalcolata() != null)
datiMig.setDAC(DateUtils.aggiungiGiorniLavorativi(DateUtils.toString(rec.getDacCalcolata(), DATE_10_FORMAT), aggiungiADac));
if (TIPO_COM_PIC.equals(tipoCom)) {
datiMig.setTIPOCOMUNICAZIONE(TIPO_COM_PIC);
if(esito.equals(ESITO_KO)){
datiMig.setCAUSALERIFIUTO("1");
datiMig.setCODICEMOTIVORIFIUTO(codMotRif);
datiMig.setMOTIVORIFIUTO("motivo rifiuto");
}
}
else if (TIPO_COM_VALIDAZIONE.equals(tipoCom)) {
datiMig.setTIPOCOMUNICAZIONE(TIPO_COM_VALIDAZIONE);
if(esito.equals(ESITO_KO)){
datiMig.setCAUSALERIFIUTO("1");
datiMig.setCODICEMOTIVORIFIUTO(codMotRif);
datiMig.setMOTIVORIFIUTO("motivo rifiuto");
}else{
datiMig.setCAUSALERIFIUTO("");
datiMig.setCODICEMOTIVORIFIUTO("");
datiMig.setMOTIVORIFIUTO("");
}
}
else {
throw new Exception("Tipo Comunicazione Errato");
}
return datiMig;
}
private INTESTAZIONE createIntestazione(String nomeFile) throws Exception {
INTESTAZIONE intest = INTESTAZIONE.Factory.newInstance();
//populateBeanWithUnicValue(intest, EMPTY);
Date dataRif = new Date();
intest.setCODICEISP(INTEST_COD_ISP);
intest.setNOMEFILE(nomeFile);
intest.setSISTEMA(INTEST_SISTEMA);
intest.setDATACREAZIONEFILE(DateUtils.toString(dataRif, DATE_16_FORMAT));
intest.setNUMEROPRATICHE("000000");
intest.setNUMEROPRATICHECHIUSEOK("000000");
intest.setNUMEROPRATICHECHIUSEKO("000000");
intest.setNUMERONOTIFICHEINTERMEDIE("000000");
return intest;
}
}

View File

@@ -0,0 +1,548 @@
package it.valueteam.gnpsim.generator.ib;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRecExt;
import it.valueteam.gnp.dao.xml.crm.crmtodbcfx.NotificaFromCRM;
import it.valueteam.gnp.dao.xml.crm.crmtodbcfx.voip35.DN;
import it.valueteam.gnp.dao.xml.crm.crmtodbcfx.voip35.NotificaVOIPFromCRM;
import it.valueteam.gnp.obj.CRMMap;
import it.valueteam.gnp.obj.ProcessMapper;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.obj.SystemMap;
import it.valueteam.gnpsim.utility.DateUtils;
import java.util.Date;
public class XMLCrmGenerator extends SimGenerator implements XMLGeneratorIF {
private static int MIN_PARAMS_NUMBER = 2; // Numero minimo di parametri
private static int MIN_PARAMS_NUMBER_RIENTRO = 7; // Numero minimo di parametri per Rientro
private static int MIN_PARAMS_NUMBER_RIENTRO_DD = 12; // Numero minimo di parametri se Rientro Doppio Donating
private static int IDX_TIPO_CHIAMATA = 0; // Indice del parametro Tipo Chiamata
private static int IDX_TIPO_EVENTO = 1; // Indice del parametro Tipo Evento
private static int IDX_PIATT_PROV = 2; // Indice del parametro Piattaforma di Provenienza
private static int IDX_COW = 3; // Indice del parametro COW
private static int IDX_NUM_TOT_RICH = 4; // Indice del parametro Numero Totale di Richieste
private static int IDX_COS = 5; // Indice del parametro COS
private static int IDX_FLAG_DICHIARAZIONE=6; // Indice del parametro Flag Dichiarazione
private static int IDX_ID_PADRE=7; // Indice del parametro Id-esigenza padre
private static int IDX_COW2=8; // Indice del parametro COW2 se Doppio Donating
private static int IDX_COS2 = 9; // Indice del parametro COS2 se Doppio Donating
private static int IDX_FLAG_NAKED=10; // Indice del parametro FLAG_NAKED se Doppio Donating
private static int IDX_FLAG_GNR=11; // Indice del parametro FLAG_GNR se Doppio Donating
private static int IDX_FLAG_CONSIP=12; // Indice del parametro FLAG_CONSIP se Doppio Donating
private static int IDX_CODICE_PROGETTO=13; // Indice del parametro CODICE_PROGETTO
private static int IDX_FLAG_SKY = 14; // Indice del parametro FLAG_SKY
private static int IDX_FLAG_VERTICALIZZATO = 15;// Indice del parametro FLAG_VERTICALIZZATO
private static int IDX_RN = 16;// Indice del parametro FLAG_VERTICALIZZATO
private static int IDX_SECOND_DONOR = 17;// Indice del parametro SECOND DONOR
private static String NULL_VALUE_STRING = "NULL"; // Stringa che rappresenta il valore nullo
public XMLCrmGenerator() {
}
/**
* generateXml
*
* @param args String[]
* @return String
*/
public String generateXml(String[] args, int tipoSistema) throws Exception {
if(args.length<MIN_PARAMS_NUMBER)
throw new IllegalArgumentException("Numero di parametri insufficienti");
boolean isDoppioDonating = args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_DOPPIO_DONATING);
if(isDoppioDonating)
return generateXmlDD(args, tipoSistema);
boolean isRientro = args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO) || args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO_NATIVIOLO);
if(isRientro && args.length < MIN_PARAMS_NUMBER_RIENTRO)
throw new IllegalArgumentException("Numero di parametri insufficienti per RIENTRO");
String idEsigenzaSolution = null;
NotificaFromCRM notifica = new NotificaFromCRM();
notifica.setTIPO_CHIAMATA(args[IDX_TIPO_CHIAMATA]);
notifica.setTIPO_EVENTO(args[IDX_TIPO_EVENTO]);
//se l'evento e' di rientro allora creo un nuovo id
if(isRientro)
{
idEsigenzaSolution = getIdEsigenzaSolution();
notifica.setID_ESIGENZA(idEsigenzaSolution);
notifica.setID_SOLUTION(idEsigenzaSolution);
notifica.setCANALE_PROVENIENZA(randomCanaleProvenienzaCRM());
String numeroTelefono = getTelefono(10);
notifica.setNUMERO_TELEFONO(numeroTelefono);
notifica.setFLAG_DICHIARAZIONE(args[IDX_FLAG_DICHIARAZIONE]);
notifica.setPIATTAFORMA_PROVENIENZA(args[IDX_PIATT_PROV]);
if("ALL".equals(args[IDX_COW]))
notifica.setCOW(randomCodiceOlo());
else
notifica.setCOW(args[IDX_COW]);
String numTotRichieste = args[IDX_NUM_TOT_RICH];
String cos = null;
if(NULL_VALUE_STRING.equals(args[IDX_COS]))
cos = getRandomCos();
else
cos = args[IDX_COS];
/*
* ATTENZIONE: l'XSD aggiornato prevede che se COS = 007,
* TIPO_CHIAMATA deve valere NAKED
*/
String cor = getTelefono(12);
notifica.setCOS(cos);
notifica.setCOS2(cos);
notifica.setCOR(cor);
notifica.setCODICE_FISCALE_PARTIVA_IVA(getCodiceFiscalePartitaIVA());
notifica.setRECAPITO_ALTERNATIVO(getTelefono(15));
notifica.setNOMINATIVO_CLIENTE(randomNomeCliente()+" "+ randomCognomeCliente());
notifica.setSLA(getSla());
notifica.setDAC(getDacCrm());
notifica.setCOR2(cor);
//String dn = getTelefono(10);
int numToRichiesteInt = 0;
if(!numTotRichieste.equals(NULL_VALUE_STRING)) {
numToRichiesteInt = Integer.parseInt(numTotRichieste);
}
notifica.setDN1(numeroTelefono);
if( numToRichiesteInt >= 2 ){
notifica.setDN2(getTelefono(10));
notifica.setSTATO_DN2("OK");
}
if( numToRichiesteInt >= 3 ){
notifica.setDN3(getTelefono(10));
notifica.setSTATO_DN3("OK");
}
if( numToRichiesteInt >= 4 ){
notifica.setDN4(getTelefono(10));
notifica.setSTATO_DN4("OK");
}
if( numToRichiesteInt >= 5 ){
notifica.setDN5(getTelefono(10));
notifica.setSTATO_DN5("OK");
}
if( numToRichiesteInt >= 6 ){
notifica.setDN6(getTelefono(10));
notifica.setSTATO_DN6("OK");
}
if( numToRichiesteInt >= 7 ){
notifica.setDN7(getTelefono(10));
notifica.setSTATO_DN7("OK");
}
if( numToRichiesteInt >= 8 ){
notifica.setDN8(getTelefono(10));
notifica.setSTATO_DN8("OK");
}
if( numToRichiesteInt >= 9 ){
notifica.setDN9(getTelefono(10));
notifica.setSTATO_DN9("OK");
}
if( numToRichiesteInt >= 10 ){
notifica.setDN10(getTelefono(10));
notifica.setSTATO_DN10("OK");
}
notifica.setCOD_CANALE_VENDITA(getRandomCanaleVendita());
notifica.setCOD_MARCAGGIO_CLIENTE(getRandomMarcaggio());
if(!numTotRichieste.equals(NULL_VALUE_STRING)){
//notifica.setCOD_CORRELAZIONE(getCodiceCorrelazioneCRM());
notifica.setNUM_TOT_RICHIESTE(numTotRichieste);
}
notifica.setFLAG_GNR("N");
notifica.setID_OL("G-ID0000");
notifica.setCODICE_OL("000");
notifica.setFLAG_CONSIP("N");
// aggiunta cristiano X6 2013
notifica.setMODULO_CC("modulo_cc");
notifica.setMODULO_PARTNER("modulo_partner");
notifica.setPROTOCOLLO_DMS("protocollo_DMS");
notifica.setDATA_CREAZIONE_SR("12-12-2012 12:12:12");
notifica.setDATA_CHIUSURA_CRM("12-12-2012 12:12:12");
notifica.setCAUSALE_KO("Non si accomoda piu'");
if (args[IDX_ID_PADRE]!= null && !NULL_VALUE_STRING.equals(args[IDX_ID_PADRE]) ) notifica.setID_PADRE(args[IDX_ID_PADRE]);
if (args.length > IDX_CODICE_PROGETTO && !NULL_VALUE_STRING.equals(args[IDX_CODICE_PROGETTO]) ) {
notifica.setCODICE_PROGETTO(args[IDX_CODICE_PROGETTO]);
}
else {
notifica.setCODICE_PROGETTO(getRandomCodiceProgetto());
}
// MULTI_DONOR
if(2 == numToRichiesteInt) {
if (((args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NATIVIOLO) ||
(args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NATIVIOLO103))) &&
args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO_NATIVIOLO)) ||
((args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NPg35) ||
(args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NPg103))) &&
args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO))) {
if("ALL".equals(args[IDX_SECOND_DONOR])) {
notifica.setTI_COW_DN2(randomCodiceOlo());
} else {
notifica.setTI_COW_DN2(args[IDX_SECOND_DONOR]);
}
}
}
// TIPO_CHIAMATA=OLO35 e TIPO_EVENTO=NATIVIOLO
if ((args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NATIVIOLO) ||
(args[IDX_TIPO_CHIAMATA].equals(CRMMap.CHIAMATA_NATIVIOLO103))) &&
args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO_NATIVIOLO)) {
// Imposta COW e COW2
if ("ALL".equals(args[IDX_COW2]))
notifica.setCOW2(randomCodiceOlo());
else
notifica.setCOW2(args[IDX_COW2]);
if (NULL_VALUE_STRING.equals(args[IDX_COS2]))
notifica.setCOS2(getRandomCos());
else
notifica.setCOS2(args[IDX_COS2]);
}
if (tipoSistema == SystemMap.SISTEMA_CRMR) {
if (args.length > IDX_FLAG_SKY && !NULL_VALUE_STRING.equals(args[IDX_FLAG_SKY])) {
notifica.setFLAG_SKY(args[IDX_FLAG_SKY]);
} else {
notifica.setFLAG_SKY(getRandomFlag());
}
}
}
else //altrimenti prendo quello settato nel properties come ID_ESIGENZA_MANUALE
{
idEsigenzaSolution = getIdEsigenzaManuale();
setValuesFromDB(notifica, idEsigenzaSolution);
notifica.setFLAG_GNR("N");
notifica.setFLAG_CONSIP("N");
}
if (args.length > IDX_FLAG_VERTICALIZZATO && !NULL_VALUE_STRING.equals(args[IDX_FLAG_VERTICALIZZATO])) {
notifica.setFLAG_VERTICALIZZATO(args[IDX_FLAG_VERTICALIZZATO]);
} else {
notifica.setFLAG_VERTICALIZZATO("N");
}
if (args.length > IDX_RN && !NULL_VALUE_STRING.equals(args[IDX_RN])) {
notifica.setRN(args[IDX_RN]);
}
if(args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_ESPLETAMENTO) && args[IDX_TIPO_CHIAMATA].equals(ProcessMapper.proc_RIENTRO_ADSL)){
notifica.setDET(getDetCrm());
}
if(args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_KO_PITAGORA) && args[IDX_TIPO_CHIAMATA].equals(ProcessMapper.proc_RIENTRO_FONIA)){
notifica.setCAUSALE_RIFIUTO("1:CAUSALE DA PITAGORA");
}
notifica.setDATA_OPERAZIONE(DateUtils.toString(new Date(),"dd-MM-yyyy HH:mm:ss"));
return getXmlFromCastorObject(notifica,true);
}
// Generazione per Doppio Donating
private String generateXmlDD(String[] args, int tipoSistema) throws Exception {
if(args.length < MIN_PARAMS_NUMBER)
throw new IllegalArgumentException("Numero di parametri insufficienti (Doppio Donating)");
boolean isRientro = args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO);
if(isRientro && args.length < MIN_PARAMS_NUMBER_RIENTRO_DD)
throw new IllegalArgumentException("Numero di parametri insufficienti per RIENTRO Doppio Donating");
String idEsigenzaSolution = null;
String tipoChiamata = args[IDX_TIPO_CHIAMATA];
NotificaFromCRM notifica = new NotificaFromCRM();
notifica.setTIPO_CHIAMATA(tipoChiamata);
notifica.setTIPO_EVENTO(args[IDX_TIPO_EVENTO]);
if(isRientro)
{
idEsigenzaSolution = getIdEsigenzaSolution();
notifica.setPIATTAFORMA_PROVENIENZA(args[IDX_PIATT_PROV]);
notifica.setID_ESIGENZA(idEsigenzaSolution);
notifica.setID_SOLUTION(idEsigenzaSolution);
notifica.setCANALE_PROVENIENZA(randomCanaleProvenienzaCRM());
notifica.setNUMERO_TELEFONO(getTelefono(10));
notifica.setFLAG_DICHIARAZIONE(args[IDX_FLAG_DICHIARAZIONE]);
// Imposta COW e COW2
if("ALL".equals(args[IDX_COW]))
notifica.setCOW(randomCodiceOlo());
else
notifica.setCOW(args[IDX_COW]);
// Imposta COW e COW2
if("ALL".equals(args[IDX_COW2]))
notifica.setCOW2(randomCodiceOlo());
else
notifica.setCOW2(args[IDX_COW2]);
String numTotRichieste = args[IDX_NUM_TOT_RICH];
// Imposta COS e COS2
String cos = null;
if(NULL_VALUE_STRING.equals(args[IDX_COS])){
cos = getRandomCos();
// se cos='007' tipochiamata DEVE essere Naked
while( !"NAKED".equals(tipoChiamata) && "007".equals(cos) )
cos = getRandomCos();
}
else
cos = args[IDX_COS];
String cos2 = null;
if(NULL_VALUE_STRING.equals(args[IDX_COS2]))
cos2 = getRandomCos();
else
cos2 = args[IDX_COS2];
String cor = getTelefono(12);
String cor2 = getTelefono(12);
notifica.setCOS(cos);
notifica.setCOS2(cos2);
notifica.setCOR(cor);
notifica.setCODICE_FISCALE_PARTIVA_IVA(getCodiceFiscalePartitaIVA());
notifica.setRECAPITO_ALTERNATIVO(getTelefono(15));
notifica.setNOMINATIVO_CLIENTE(randomNomeCliente()+" "+ randomCognomeCliente());
notifica.setSLA(getSla());
notifica.setDAC(getDacCrm());
notifica.setCOR2(cor2);
String dn = getTelefono(12);
notifica.setDN1(dn);
notifica.setDN2(dn);
notifica.setDN3(dn);
notifica.setDN4(dn);
notifica.setDN5(dn);
notifica.setDN6(dn);
notifica.setDN7(dn);
notifica.setDN8(dn);
notifica.setDN9(dn);
notifica.setDN10(dn);
notifica.setDATA_OPERAZIONE(DateUtils.toString(new Date(),"dd-MM-yyyy HH:mm:ss"));
if(!numTotRichieste.equals(NULL_VALUE_STRING)){
// codice correlazione va settato solo se la richiesta viene da CRM-Business
// if("B".equals(args[IDX_PIATT_PROV]))
// notifica.setCOD_CORRELAZIONE(getCodiceCorrelazioneCRM());
notifica.setNUM_TOT_RICHIESTE(numTotRichieste);
}
notifica.setCOD_CANALE_VENDITA(getRandomCanaleVendita());
notifica.setCOD_MARCAGGIO_CLIENTE(getRandomMarcaggio());
if(NULL_VALUE_STRING.equals(args[IDX_FLAG_NAKED]))
notifica.setFLAG_NAKED("");
else
notifica.setFLAG_NAKED(args[IDX_FLAG_NAKED]);
if(NULL_VALUE_STRING.equals(args[IDX_FLAG_GNR]))
notifica.setFLAG_GNR("");
else
notifica.setFLAG_GNR(args[IDX_FLAG_GNR]);
if(NULL_VALUE_STRING.equals(args[IDX_FLAG_CONSIP]))
notifica.setFLAG_CONSIP("");
else
notifica.setFLAG_CONSIP(args[IDX_FLAG_CONSIP]);
if (tipoSistema == SystemMap.SISTEMA_CRMR) {
if (args.length > IDX_FLAG_SKY && !NULL_VALUE_STRING.equals(args[IDX_FLAG_SKY])) {
notifica.setFLAG_SKY(args[IDX_FLAG_SKY]);
} else {
notifica.setFLAG_SKY(getRandomFlag());
}
}
}
else //altrimenti prendo quello settato nel properties come ID_ESIGENZA_MANUALE
{
idEsigenzaSolution = getIdEsigenzaManuale();
setValuesFromDB(notifica, idEsigenzaSolution);
}
return getXmlFromCastorObject(notifica,true);
}
protected void setValuesFromDB(NotificaFromCRM notifica, String idEsigenza)
throws Exception
{
SimDAO simDao = new SimDAO();
GnpRichiesteRec richiesta = simDao.getByIdEsigenza(idEsigenza);
if(richiesta == null)
throw new Exception("Richiesta non trovata per ID_ESIGENZA " + idEsigenza);
notifica.setID_ESIGENZA(idEsigenza);
notifica.setID_SOLUTION(idEsigenza);
notifica.setCANALE_PROVENIENZA(richiesta.getCanaleProvenienza());
notifica.setNUMERO_TELEFONO(richiesta.getNumeroTelefono());
notifica.setPIATTAFORMA_PROVENIENZA(richiesta.getPiattaformaProvenienza());
notifica.setCOW(richiesta.getCow());
if(richiesta.getCow2() != null)
notifica.setCOW2(richiesta.getCow2());
if(richiesta.getFlagDichiarazione() != null)
notifica.setFLAG_DICHIARAZIONE(richiesta.getFlagDichiarazione());
else
notifica.setFLAG_DICHIARAZIONE("1");
if(richiesta.getCos() != null)
notifica.setCOS(richiesta.getCos());
if(richiesta.getCos2() != null)
notifica.setCOS2(richiesta.getCos2());
if(richiesta.getCor() != null)
notifica.setCOR(richiesta.getCor());
if(richiesta.getCor2() != null)
notifica.setCOR2(richiesta.getCor2());
if(richiesta.getCodiceFiscalePartitaIva() != null)
notifica.setCODICE_FISCALE_PARTIVA_IVA(richiesta.getCodiceFiscalePartitaIva());
if(richiesta.getRecapitoAlternativo() != null)
notifica.setRECAPITO_ALTERNATIVO(richiesta.getRecapitoAlternativo());
if(richiesta.getNominativoCliente() != null)
notifica.setNOMINATIVO_CLIENTE(richiesta.getNominativoCliente());
// Questi vanno comunque letti da property
notifica.setSLA(getSla());
notifica.setDAC(getDacCrm());
if(richiesta.getDn1() != null)
notifica.setDN1(richiesta.getDn1());
if(richiesta.getDn2() != null)
notifica.setDN2(richiesta.getDn2());
if(richiesta.getDn3() != null)
notifica.setDN3(richiesta.getDn3());
if(richiesta.getDn4() != null)
notifica.setDN4(richiesta.getDn4());
if(richiesta.getDn5() != null)
notifica.setDN5(richiesta.getDn5());
if(richiesta.getDn6() != null)
notifica.setDN6(richiesta.getDn6());
if(richiesta.getDn7() != null)
notifica.setDN7(richiesta.getDn7());
if(richiesta.getDn8() != null)
notifica.setDN8(richiesta.getDn8());
if(richiesta.getDn9() != null)
notifica.setDN9(richiesta.getDn9());
if(richiesta.getDn10() != null)
notifica.setDN10(richiesta.getDn10());
GnpRichiesteRecExt richiestaExt = simDao.getRichiestaExtById(richiesta.getIdRichiesta());
if(richiestaExt != null && richiestaExt.getCanaleVendita() != null)
notifica.setCOD_CANALE_VENDITA(richiestaExt.getCanaleVendita());
if(richiestaExt != null && richiestaExt.getMarcaggio() != null)
notifica.setCOD_MARCAGGIO_CLIENTE(richiestaExt.getMarcaggio());
if(richiesta.getFlagNaked() != null)
notifica.setFLAG_NAKED(richiesta.getFlagNaked().toString());
}
/**
* generateXml
*
* @param args String[]
* @return String
*/
public String generateXmlVoip(String[] args) throws Exception {
if (args.length < MIN_PARAMS_NUMBER)
throw new IllegalArgumentException("Numero di parametri insufficienti");
boolean isRientro = args[IDX_TIPO_EVENTO].equals(CRMMap.EVENTO_RIENTRO);
if (isRientro && args.length < MIN_PARAMS_NUMBER_RIENTRO)
throw new IllegalArgumentException("Numero di parametri insufficienti per RIENTRO");
NotificaVOIPFromCRM notifica = new NotificaVOIPFromCRM();
String idEsigenzaSolution = null;
//se l'evento e' di rientro allora creo un nuovo id
if (isRientro) {
idEsigenzaSolution = getIdEsigenzaSolution();
notifica.setTIPO_CHIAMATA(args[IDX_TIPO_CHIAMATA]);
notifica.setTIPO_EVENTO(args[IDX_TIPO_EVENTO]);
notifica.setID_ESIGENZA(idEsigenzaSolution);
notifica.setPIATTAFORMA_PROVENIENZA(args[IDX_PIATT_PROV]);
if ("ALL".equals(args[IDX_COW]))
notifica.setCOW(randomCodiceOlo());
else
notifica.setCOW(args[IDX_COW]);
//String numTotRichieste = args[IDX_NUM_TOT_RICH];
notifica.setNOMINATIVO_CLIENTE(randomNomeCliente() + " " + randomCognomeCliente());
notifica.setCODICE_FISCALE_PARTIVA_IVA(getCodiceFiscalePartitaIVA());
notifica.setRECAPITO_ALTERNATIVO(getTelefono(15));
notifica.setDAC(getDacCrm());
notifica.setRNB("");
notifica.setDATA_OPERAZIONE(DateUtils.toString(new Date(), "dd-MM-yyyy HH:mm:ss"));
notifica.setCOD_CANALE_VENDITA(getRandomCanaleVendita());
notifica.setCOD_MARCAGGIO_CLIENTE(getRandomMarcaggio());
notifica.setID_OL_FITTIZIO("G-ID0000");
notifica.setFLAG_CONSIP("N");
notifica.setCODICE_PROGETTO("COD_PROGETTO");
notifica.setMODULO_CC("modulo_cc");
notifica.setMODULO_PARTNER("modulo_partner");
notifica.setPROTOCOLLO_DMS("protocollo_DMS");
notifica.setDATA_CREAZIONE_SR("12-12-2013 15:16:17");
notifica.setDATA_CHIUSURA_SR("12-12-2013 15:16:17");
notifica.setCAUSALE_KO_PDC("Non si accomoda piu'");
if (args[IDX_ID_PADRE] != null && !NULL_VALUE_STRING.equals(args[IDX_ID_PADRE])) {
notifica.setID_PADRE(args[IDX_ID_PADRE]);
}
String numeroTelefono = getTelefono(12);
DN dn = new DN();
dn.setNUM_TEL(numeroTelefono);
dn.setDONOR(randomCodiceOlo());
dn.setPRIMARIO(null);
dn.setRADICALE("");
dn.setCLASSIFICAZIONE("");
} else { //altrimenti prendo quello settato nel properties come ID_ESIGENZA_MANUALE
idEsigenzaSolution = getIdEsigenzaManuale();
//setValuesFromDB(notifica, idEsigenzaSolution);
notifica.setFLAG_CONSIP("N");
}
return getXmlFromCastorObject(notifica, true);
}
}

View File

@@ -0,0 +1,6 @@
package it.valueteam.gnpsim.generator.ib;
public interface XMLGeneratorIF {
public String generateXml(String[] args, int tipoSistema) throws Exception;
}

View File

@@ -0,0 +1,27 @@
package it.valueteam.gnpsim.generator.ib;
import java.util.Date;
import it.valueteam.gnp.dao.xml.crm.crmtodbcfx.NotificaHZFromCRM;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.utility.DateUtils;
public class XMLHZCrmrGenerator extends SimGenerator implements XMLGeneratorIF {
private static final String NIP_N_TIM = "NIP N TIM";
private static final String ESPLETAMENTO = "ESPLETAMENTO";
public String generateXml(String[] args, int tipoSistema) throws Exception {
NotificaHZFromCRM notifica = new NotificaHZFromCRM();
notifica.setID_SOLUTION(getIdEsigenzaSolution());
notifica.setNUMERO_TELEFONO(getTelefono(10));
notifica.setTIPO_CHIAMATA(NIP_N_TIM);
notifica.setTIPO_EVENTO(ESPLETAMENTO);
notifica.setDET(DateUtils.toString(new Date(),"dd-MM-yyyy HH:mm:ss"));
notifica.setDATA_OPERAZIONE(DateUtils.toString(new Date(),"dd-MM-yyyy HH:mm:ss"));
return getXmlFromCastorObject(notifica,true);
}
}

View File

@@ -0,0 +1,163 @@
package it.valueteam.gnpsim.generator.olo;
import it.valueteam.gnp.dao.xml.olo.gnpolo.response.Parametri;
import it.valueteam.gnp.dao.xml.olo.gnpolo.response.Response;
import it.valueteam.gnp.dao.xml.olo.gnpolo.response.Xml2;
import it.valueteam.gnp.dao.xml.olo.gnpolo.response.types.Type_causaleRifiuto;
import it.valueteam.gnp.dao.xml.olo.gnpolo.response.types.Type_statoRichiesta;
import it.valueteam.gnp.obj.ApplicationCostants;
import it.valueteam.gnp.obj.StatoRichiestaDoppioDonating;
import it.valueteam.gnp.obj.StatoRichiestaRec;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.obj.CausaliRifiutoOloDTO;
import it.valueteam.gnpsim.obj.OloReplyDto;
public class OLOGenerator extends SimGenerator implements OLOGeneratorIF {
private static final int PARAM_MIN=1; // Numero minimo di parametri
private static final int IDX_TIPO_ESITO=0; // Indice del parametro del tipo di esito da OLO
private static final int IDX_TIPO_KO=1; // Indice del parametro che tipo KO (opzionale)
private static final int TIPO_RICH_STANDARD=1;
// private static final int TIPO_RICH_DOPPIO_DONATING=2;
private int tipoRichieste;
// TIPI DI FLUSSO DA GENERARE
private static final int FILE_ACCETTAZIONE = 1;
private static final int FILE_VALIDAZIONE = 2;
private static final int FILE_MUTATA_VOLONTA = 3;
// TIPI DI COMUNICAZIONE
private static final int TIPO_COMUNICAZIONE_FORMALE = 2;
private static final int TIPO_COMUNICAZIONE_GESTIONALE = 3;
private static final int TIPO_COMUNICAZIONE_MUT_VOL = 5;
public OLOGenerator(int tipoRichieste) {
this.tipoRichieste = tipoRichieste;
}
/**
* generate
*
* @param args
* String[]
* @return String
*/
public String generate(String[] args, String olo, int tipoFile) throws Exception {
if (args.length < PARAM_MIN)
throw new Exception("Numero di parametri insufficienti!");
String esito = args[IDX_TIPO_ESITO];
int tipoKO=DEFAULT_KO;
if(args.length > PARAM_MIN)
try{
tipoKO = Integer.parseInt(args[IDX_TIPO_KO]);
}catch(Exception ex){
System.out.println("Parametro tipoKO non numerico, in tipoKO randomico, forse avrai fortuna...");
}
switch (tipoFile) {
case FILE_ACCETTAZIONE: {
return generaXML(olo, esito,TIPO_COMUNICAZIONE_FORMALE, tipoKO);
}
case FILE_VALIDAZIONE: {
return generaXML(olo, esito, TIPO_COMUNICAZIONE_GESTIONALE, tipoKO);
}
case FILE_MUTATA_VOLONTA: {
return generaXML(olo, esito, TIPO_COMUNICAZIONE_MUT_VOL, tipoKO);
}
default:
throw new Exception("Tipo flusso sconosciuto!");
}
}
private String generaXML(String codOlo, String esito, int tipoComunicazione, int tipoKO) throws Exception {
String xmlResult = null;
OloReplyDto[] request= getRequestToReply(codOlo, getStatoByTipoComunicazione(tipoComunicazione), tipoRichieste);
if (request != null && request.length > 0) {
Xml2 listaRisposte = new Xml2();
for (int i = 0; i < request.length; i++) {
Response response = new Response();
Parametri parametri = new Parametri();
parametri.setTipoComunicazione(String.valueOf(tipoComunicazione));
parametri.setCodiceOperatoreRecipient(ApplicationCostants.COD_OLO_TELECOM);
parametri.setCodiceOrdineRecipient(request[i].getIdEsigenza());
parametri.setCodiceOLODonating(codOlo);
parametri.setCodiceRisorsa1(request[i].getCor());
parametri.setCodiceRisorsa2(!isNull(request[i].getCor2())?request[i].getCor():"");
if(esito.equals("OK")){
// value 0
parametri.setStatoRichiesta(Type_statoRichiesta.VALUE_1);
//value ""
parametri.setCausaleRifiuto(Type_causaleRifiuto.VALUE_0);
parametri.setCodiceMotivoRifiuto("");
parametri.setMotivoRifiuto("");
}else{
CausaliRifiutoOloDTO causali = getInfoOloKO(tipoComunicazione, tipoKO);
// value 0
parametri.setStatoRichiesta(Type_statoRichiesta.VALUE_2);
//value causali.getCausaleRifiuto()
parametri.setCausaleRifiuto(Type_causaleRifiuto.valueOf(causali.getCausaleRifiuto()));
//parametri.setStatoRichiesta(String.valueOf(ESITO_KO));
//parametri.setCausaleRifiuto(Type_causaleRifiuto(causali.getCausaleRifiuto().toString()));
parametri.setCodiceMotivoRifiuto(causali.getCodiceMotivo_rifiuto().toString());
parametri.setMotivoRifiuto(causali.getMotivoRifiuto());
}
parametri.setNumerazioneErrata("");
response.setParametri(parametri);
response.setCodiceOrdineRecipient(request[i].getIdEsigenza());
parametri.setCodiceSessione(getCodiceSessione());
listaRisposte.addResponse(response);
}
xmlResult = getXmlFromCastorObject(listaRisposte, true);
}
return xmlResult;
}
private int getStatoByTipoComunicazione(int tipoComunicazione) throws Exception{
switch(tipoComunicazione){
case TIPO_COMUNICAZIONE_FORMALE:
if(tipoRichieste == TIPO_RICH_STANDARD)
return StatoRichiestaRec.INVIATA;
else
return StatoRichiestaDoppioDonating.INVIATA;
case TIPO_COMUNICAZIONE_GESTIONALE:
if(tipoRichieste == TIPO_RICH_STANDARD)
return StatoRichiestaRec.ACCETTATA;
else
return StatoRichiestaDoppioDonating.ACCETTATA;
case TIPO_COMUNICAZIONE_MUT_VOL:
return -1;
default:
throw new Exception("Tipo comunicazione sconosciuto: " + tipoComunicazione);
}
}
}

View File

@@ -0,0 +1,8 @@
package it.valueteam.gnpsim.generator.olo;
public interface OLOGeneratorIF {
public String generate(String[] args, String olo, int tipoFile) throws Exception;
}

View File

@@ -0,0 +1,322 @@
package it.valueteam.gnpsim.generator.ws;
import it.telecomitalia.crmaffari.dbcfx.acqservicev1.NotificaFromCRM;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRecExt;
import it.valueteam.gnp.obj.CRMMap;
import it.valueteam.gnp.obj.ProcessMapper;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.utility.DateUtils;
import java.util.Date;
import java.util.Random;
public class WSCRMAGenerator extends WSGeneratorIF {
private final static String soapHeaderOpen = "<soapenv:Header><head:SOAPHeader>";
private final static String soapHeaderClose = "</head:SOAPHeader></soapenv:Header>";
private static int MIN_PARAMS_NUMBER = 2; // Numero minimo di parametri
private static int MIN_PARAMS_NUMBER_RIENTRO = 6; // Numero minimo di parametri per Rientro
private static int IDX_TIPO_CHIAMATA = 0; // Indice del parametro Tipo Chiamata
private static int IDX_TIPO_EVENTO = 1; // Indice del parametro Tipo Evento
private static int IDX_COW = 2; // Indice del parametro COW
private static int IDX_NUM_TOT_RICH = 3; // Indice del parametro Numero Totale di Richieste
private static int IDX_COS = 4; // Indice del parametro COS
private static int IDX_FLAG_DICHIARAZIONE=5;// Indice del parametro Flag Dichiarazione
private static String NULL_VALUE_STRING = "NULL"; // Stringa che rappresenta il valore nullo
private String tipoChiamata;
private String tipoEvento;
private String cow;
private String numTotRichieste;
private String cos;
private String flagDichiarazione;
private String idEsigenzaSolution = null;
public WSCRMAGenerator(String args[])
{
if(args.length<MIN_PARAMS_NUMBER)
throw new IllegalArgumentException("Numero di parametri insufficienti");
tipoChiamata = args[IDX_TIPO_CHIAMATA];
tipoEvento = args[IDX_TIPO_EVENTO];
// Questa parte solo in caso di RIENTRO
if(tipoEvento.equals(CRMMap.EVENTO_RIENTRO))
{
if(args.length < MIN_PARAMS_NUMBER_RIENTRO)
throw new IllegalArgumentException("Numero di parametri insufficienti per RIENTRO");
cow = args[IDX_COW];
numTotRichieste = args[IDX_NUM_TOT_RICH];
cos = args[IDX_COS];
flagDichiarazione = args[IDX_FLAG_DICHIARAZIONE];
idEsigenzaSolution = getIdEsigenzaSolution();
}
else
{
idEsigenzaSolution = getIdEsigenzaManuale();
}
}
@Override
public String getSOAPEpilogue() {
return "</soapenv:Envelope>";
}
@Override
public String getSOAPHeader(Object obj) {
StringBuffer buffer = new StringBuffer();
buffer.append(soapHeaderOpen);
buffer.append("<head:IDMsg>");
buffer.append(calcRandomID(30));
buffer.append("</head:IDMsg>");
buffer.append("<head:SRC>");
buffer.append("CRM_A");
buffer.append("</head:SRC>");
buffer.append("<head:SIDMsgType>");
buffer.append("NOTIFICA_RIENTRO");
buffer.append("</head:SIDMsgType>");
buffer.append("<head:SIDMsgCode>");
buffer.append(tipoEvento);
buffer.append("</head:SIDMsgCode>");
buffer.append(soapHeaderClose);
return buffer.toString();
}
@Override
public String getSOAPPrologue() {
return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:head=\"http://www.ESB/SOAP/Header\" " +
"xmlns:acq=\"http://telecomitalia.it/crmaffari/dbcfx/acqservice-v1\">";
}
public String getSoapBodyOpen()
{
return "<soapenv:Body>";
}
public String getSoapBodyClose()
{
return "</soapenv:Body>";
}
private NotificaFromCRM getNotificaFromCRM()
throws Exception
{
NotificaFromCRM notificaFromCRMA = new NotificaFromCRM();
notificaFromCRMA.setTIPO_CHIAMATA(tipoChiamata);
notificaFromCRMA.setTIPO_EVENTO(tipoEvento);
notificaFromCRMA.setSLA(getSla());
notificaFromCRMA.setDAC(getDacCrm());
notificaFromCRMA.setDATA_OPERAZIONE(DateUtils.toString(new Date(),"dd-MM-yyyy HH:mm:ss"));
if(tipoEvento.equals(CRMMap.EVENTO_RIENTRO))
newNotificaFromCRM(notificaFromCRMA);
else
setValuesFromDB(notificaFromCRMA);
return notificaFromCRMA;
}
private void newNotificaFromCRM(NotificaFromCRM notificaFromCRMA)
throws Exception
{
notificaFromCRMA.setID_ESIGENZA(idEsigenzaSolution);
notificaFromCRMA.setID_SOLUTION(idEsigenzaSolution);
notificaFromCRMA.setPIATTAFORMA_PROVENIENZA("A");
if("ALL".equals(cow))
notificaFromCRMA.setCOW(randomCodiceOlo());
else
notificaFromCRMA.setCOW(cow);
notificaFromCRMA.setCANALE_PROVENIENZA(randomCanaleProvenienzaCRM());
notificaFromCRMA.setNUMERO_TELEFONO(getTelefono(10));
notificaFromCRMA.setFLAG_DICHIARAZIONE(flagDichiarazione);
if(NULL_VALUE_STRING.equals(cos))
notificaFromCRMA.setCOS(getRandomCos());
else
notificaFromCRMA.setCOS(cos);
notificaFromCRMA.setCOR(getTelefono(12));
notificaFromCRMA.setCODICE_FISCALE_PARTIVA_IVA(getCodiceFiscalePartitaIVA());
notificaFromCRMA.setRECAPITO_ALTERNATIVO(getTelefono(15));
notificaFromCRMA.setNOMINATIVO_CLIENTE(randomNomeCliente()+" "+ randomCognomeCliente());
notificaFromCRMA.setDN1(getTelefono(12));
if(numTotRichieste != null && !numTotRichieste.equals(NULL_VALUE_STRING)){
notificaFromCRMA.setCOD_CORRELAZIONE(getCodiceCorrelazioneCRM());
notificaFromCRMA.setNUM_TOT_RICHIESTE(numTotRichieste);
}
notificaFromCRMA.setCOD_CANALE_VENDITA(getRandomCanaleVendita());
notificaFromCRMA.setCOD_MARCAGGIO_CLIENTE(getRandomMarcaggio());
}
private void setValuesFromDB(NotificaFromCRM notificaFromCRMA)
throws Exception
{
SimDAO simDao = new SimDAO();
GnpRichiesteRec richiesta = simDao.getByIdEsigenza(idEsigenzaSolution);
if(richiesta == null)
throw new Exception("Richiesta non trovata");
if(tipoEvento.equals(CRMMap.EVENTO_MIGRAZIONE)) {
if(!richiesta.getPiattaformaProvenienza().equals(CRMMap.PIATTAFORMA_B))
throw new Exception("Evento MIGRAZIONE incompatibile con ID_ESIGENZA " + idEsigenzaSolution);
}
notificaFromCRMA.setID_ESIGENZA(idEsigenzaSolution);
notificaFromCRMA.setPIATTAFORMA_PROVENIENZA(richiesta.getPiattaformaProvenienza());
notificaFromCRMA.setCOW(richiesta.getCow());
notificaFromCRMA.setCANALE_PROVENIENZA(richiesta.getCanaleProvenienza());
notificaFromCRMA.setNUMERO_TELEFONO(richiesta.getNumeroTelefono());
if(richiesta.getFlagDichiarazione() != null )
notificaFromCRMA.setFLAG_DICHIARAZIONE(richiesta.getFlagDichiarazione());
else
notificaFromCRMA.setFLAG_DICHIARAZIONE("1");
notificaFromCRMA.setCOS(richiesta.getCos());
notificaFromCRMA.setCOR(richiesta.getCor());
notificaFromCRMA.setCODICE_FISCALE_PARTIVA_IVA(richiesta.getCodiceFiscalePartitaIva());
notificaFromCRMA.setRECAPITO_ALTERNATIVO(richiesta.getRecapitoAlternativo());
notificaFromCRMA.setNOMINATIVO_CLIENTE(richiesta.getNominativoCliente());
notificaFromCRMA.setDN1(richiesta.getDn1());
GnpRichiesteRecExt richiestaExt = simDao.getRichiestaExtById(richiesta.getIdRichiesta());
if(richiestaExt != null && richiestaExt.getCanaleVendita() != null)
notificaFromCRMA.setCOD_CANALE_VENDITA(richiestaExt.getCanaleVendita());
else
notificaFromCRMA.setCOD_CANALE_VENDITA("");
if(richiestaExt != null && richiestaExt.getMarcaggio() != null)
notificaFromCRMA.setCOD_MARCAGGIO_CLIENTE(richiestaExt.getMarcaggio());
else
notificaFromCRMA.setCOD_MARCAGGIO_CLIENTE("");
if(tipoEvento.equals(CRMMap.EVENTO_ESPLETAMENTO) && tipoChiamata.equals(ProcessMapper.proc_RIENTRO_ADSL)){
notificaFromCRMA.setDET(getDetCrm());
}
if(tipoEvento.equals(CRMMap.EVENTO_KO_PITAGORA) && tipoChiamata.equals(ProcessMapper.proc_RIENTRO_FONIA)){
notificaFromCRMA.setCAUSALE_RIFIUTO("1:CAUSALE DA PITAGORA");
}
if(tipoEvento.equals(CRMMap.EVENTO_MIGRAZIONE)) {
notificaFromCRMA.setID_SOLUTION(getIdEsigenzaSolution());
notificaFromCRMA.setPIATTAFORMA_PROVENIENZA("A");
}
}
@Override
public String getData(Object obj) throws Exception {
StringBuffer buffer = new StringBuffer();
NotificaFromCRM notificaFromCRMA = getNotificaFromCRM();
buffer.append("<acq:NotificaFromCRM>");
buffer.append("<ID_ESIGENZA>");
buffer.append(notificaFromCRMA.getID_ESIGENZA());
buffer.append("</ID_ESIGENZA>");
buffer.append("<ID_SOLUTION>");
buffer.append(notificaFromCRMA.getID_SOLUTION());
buffer.append("</ID_SOLUTION>");
buffer.append("<TIPO_CHIAMATA>");
buffer.append(notificaFromCRMA.getTIPO_CHIAMATA());
buffer.append("</TIPO_CHIAMATA>");
buffer.append("<TIPO_EVENTO>");
buffer.append(notificaFromCRMA.getTIPO_EVENTO());
buffer.append("</TIPO_EVENTO>");
buffer.append("<PIATTAFORMA_PROVENIENZA>");
buffer.append(notificaFromCRMA.getPIATTAFORMA_PROVENIENZA());
buffer.append("</PIATTAFORMA_PROVENIENZA>");
buffer.append("<COW>");
buffer.append(notificaFromCRMA.getCOW());
buffer.append("</COW>");
buffer.append("<CANALE_PROVENIENZA>");
buffer.append(notificaFromCRMA.getCANALE_PROVENIENZA());
buffer.append("</CANALE_PROVENIENZA>");
buffer.append("<NUMERO_TELEFONO>");
buffer.append(notificaFromCRMA.getNUMERO_TELEFONO());
buffer.append("</NUMERO_TELEFONO>");
buffer.append("<FLAG_DICHIARAZIONE>");
buffer.append(notificaFromCRMA.getFLAG_DICHIARAZIONE());
buffer.append("</FLAG_DICHIARAZIONE>");
buffer.append("<COS>");
buffer.append(notificaFromCRMA.getCOS());
buffer.append("</COS>");
buffer.append("<COR>");
buffer.append(notificaFromCRMA.getCOR());
buffer.append("</COR>");
buffer.append("<CODICE_FISCALE_PARTIVA_IVA>");
buffer.append(notificaFromCRMA.getCODICE_FISCALE_PARTIVA_IVA());
buffer.append("</CODICE_FISCALE_PARTIVA_IVA>");
buffer.append("<RECAPITO_ALTERNATIVO>");
buffer.append(notificaFromCRMA.getRECAPITO_ALTERNATIVO());
buffer.append("</RECAPITO_ALTERNATIVO>");
buffer.append("<NOMINATIVO_CLIENTE>");
buffer.append(notificaFromCRMA.getNOMINATIVO_CLIENTE());
buffer.append("</NOMINATIVO_CLIENTE>");
buffer.append("<SLA>");
buffer.append(notificaFromCRMA.getSLA());
buffer.append("</SLA>");
buffer.append("<DAC>");
buffer.append(notificaFromCRMA.getDAC());
buffer.append("</DAC>");
if(notificaFromCRMA.getDET() != null){
buffer.append("<DET>");
buffer.append(notificaFromCRMA.getDET());
buffer.append("</DET>");
}
buffer.append("<DN1>");
buffer.append(getTelefono(12));
buffer.append("</DN1>");
if(notificaFromCRMA.getCAUSALE_RIFIUTO() != null){
buffer.append("<CAUSALE_RIFIUTO>");
buffer.append(notificaFromCRMA.getCAUSALE_RIFIUTO());
buffer.append("</CAUSALE_RIFIUTO>");
}
buffer.append("<DATA_OPERAZIONE>");
buffer.append(notificaFromCRMA.getDATA_OPERAZIONE());
buffer.append("</DATA_OPERAZIONE>");
if(notificaFromCRMA.getCOD_CORRELAZIONE() != null){
buffer.append("<COD_CORRELAZIONE>");
buffer.append(notificaFromCRMA.getCOD_CORRELAZIONE());
buffer.append("</COD_CORRELAZIONE>");
buffer.append("<NUM_TOT_RICHIESTE>");
buffer.append(notificaFromCRMA.getNUM_TOT_RICHIESTE());
buffer.append("</NUM_TOT_RICHIESTE>");
}
buffer.append("<COD_CANALE_VENDITA>");
buffer.append(notificaFromCRMA.getCOD_CANALE_VENDITA());
buffer.append("</COD_CANALE_VENDITA>");
buffer.append("<COD_MARCAGGIO_CLIENTE>");
buffer.append(notificaFromCRMA.getCOD_MARCAGGIO_CLIENTE());
buffer.append("</COD_MARCAGGIO_CLIENTE>");
buffer.append("</acq:NotificaFromCRM>");
return buffer.toString();
}
private String calcRandomID(int len) {
Random random = new Random();
int num = (int)Math.ceil(Math.pow(2, 63)/len);
return Long.toString(Math.abs(random.nextLong()), num);
}
@Override
public String getFileName(Object obj) {
return "CRMA_" + tipoEvento + "_" + idEsigenzaSolution + ".xml";
}
}

View File

@@ -0,0 +1,147 @@
package it.valueteam.gnpsim.generator.ws;
import dbcfx.soa.esitofrodimgmt.x20160229.EsitoFrodiRequest;
import dbcfx.soa.wirelinenumberportabilitymgmt.x20160229.RichiestaAttivazioneRequest;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnp.obj.CRMMap;
import it.valueteam.gnpsim.base.SimGenerator;
import it.valueteam.gnpsim.database.SimDAO;
import it.valueteam.gnpsim.utility.DateUtils;
import java.util.Date;
import java.util.Random;
public class WSDBSSGenerator extends SimGenerator {
private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss";
private String idEsigenzaSolution;
public WSDBSSGenerator(String args[])
{
String tipoEvento = args[2];
//solo in caso di RIENTRO
if(tipoEvento.equals(CRMMap.EVENTO_RIENTRO))
{
idEsigenzaSolution = getIdEsigenzaSolution();
}
else
{
idEsigenzaSolution = getIdEsigenzaManuale();
}
}
public RichiestaAttivazioneRequest[] generateRichiestaAttivazioneRequest(int n, String[] args) {
RichiestaAttivazioneRequest[] reqs = new RichiestaAttivazioneRequest[n];
//RichiestaAttivazioneRequest req = null;
try {
for (int i = 0; i < n; i++) {
if (!CRMMap.EVENTO_RIENTRO.equals(args[2])) {
reqs[i] = getDataFromDb(args);
} else {
reqs[i] = new RichiestaAttivazioneRequest();
reqs[i].setID_ESIGENZA(getIdEsigenzaSolution());
}
reqs[i].setORDER_ITEM_ID(getRandomString(30, false));
reqs[i].setID_SOLUTION(getIdEsigenzaSolution());
reqs[i].setTIPO_EVENTO(args[2]);
reqs[i].setTIPO_CHIAMATA(args[3]);
reqs[i].setPIATTAFORMA_PROVENIENZA("D");
if (!args[4].equalsIgnoreCase("NULL")) {
reqs[i].setCANALE_PROVENIENZA(args[4]);
} else {
reqs[i].setCANALE_PROVENIENZA(randomCanaleProvenienzaDBSS());
}
reqs[i].setNUMERO_TELEFONO(args[5]);
reqs[i].setCOR(getTelefono(12));
reqs[i].setCOW(args[6]);
if (!args[7].equalsIgnoreCase("NULL")) reqs[i].setCOS(args[7]);
reqs[i].setNOMINATIVO_CLIENTE(randomNomeCliente() + " " + randomCognomeCliente());
reqs[i].setCODICE_FISCALE_PARTIVA_IVA(getCodiceFiscalePartitaIVA());
reqs[i].setRECAPITO_ALTERNATIVO(getTelefono(15));
reqs[i].setSLA(getSla());
reqs[i].setDAC(getDacCrm());
reqs[i].setDET(getDetCrm());
reqs[i].setCOR2(getTelefono(12));
if (!args[8].equalsIgnoreCase("NULL")) reqs[i].setCOS2(args[8]);
reqs[i].setDN1(getTelefono(12));
reqs[i].setDATA_OPERAZIONE(DateUtils.toString(new Date(), DATE_FORMAT));
reqs[i].setCOD_MARCAGGIO_CLIENTE(getRandomMarcaggio());
reqs[i].setCOD_CANALE_VENDITA(getRandomCanaleVendita());
reqs[i].setFLAG_DICHIARAZIONE(args[9]);
reqs[i].setFLAG_GNR(args[10]);
reqs[i].setFLAG_CONSIP(args[11]);
reqs[i].setCODICE_OL("000");
reqs[i].setID_OL("G-ID0000");
reqs[i].setCOW2(new SimGenerator().randomCodiceOlo());
}
}
catch (Exception e) {
System.out.println("errore nella generazione della request");
e.printStackTrace();
}
return reqs;
}
public EsitoFrodiRequest generateEsitoFrodiRequest(String[] args) {
String orderItem = args[1];
String codiceEsito = args[2];
String descrizioneEsito = args.length > 3 && args[3] != null && !args[3].equals("NULL") ? args[3] : null;
EsitoFrodiRequest req = new EsitoFrodiRequest();
req.setORDER_ITEM_ID(orderItem);
req.setCODICE_ESITO(codiceEsito);
if (descrizioneEsito != null) {
req.setDESCRIZIONE_ESITO(descrizioneEsito);
}
return req;
}
private String getRandomString(int length, boolean lowerCase){
Random rand = new Random();
StringBuffer tempStr = new StringBuffer();
tempStr.append("");
for (int i = 0; i < length; i++) {
int c = rand.nextInt(122 - 48) + 48;
if((c >= 58 && c <= 64) || (c >= 91 && c <= 96)){
i--;
continue;
}
tempStr.append((char)c);
}
String toRet = tempStr.toString();
if (lowerCase) {
return toRet.toLowerCase();
}
return toRet;
}
private RichiestaAttivazioneRequest getDataFromDb(String[] args) throws Exception{
RichiestaAttivazioneRequest req = new RichiestaAttivazioneRequest();
SimDAO simDao = new SimDAO();
GnpRichiesteRec richiesta = null;
try {
richiesta = simDao.getByIdEsigenza(idEsigenzaSolution);
}
catch (Exception e) {
System.out.println("errore in get data from db " );
e.printStackTrace();
}
String tipoEvento = args[2];
if(tipoEvento.equals(CRMMap.EVENTO_MIGRAZIONE)) {
if(richiesta != null && !richiesta.getPiattaformaProvenienza().equals(CRMMap.PIATTAFORMA_B))
throw new Exception("Evento MIGRAZIONE incompatibile con ID_ESIGENZA " + idEsigenzaSolution);
}
req.setID_ESIGENZA(idEsigenzaSolution);
return req;
}
}

View File

@@ -0,0 +1,27 @@
package it.valueteam.gnpsim.generator.ws;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnpsim.base.SimGenerator;
public abstract class WSGeneratorIF extends SimGenerator {
public String getSoapBody(Object obj) throws Exception
{
GnpRichiesteRec rec = (GnpRichiesteRec)obj;
return getSoapBodyOpen() + getData(rec) + getSoapBodyClose();
}
public abstract String getSoapBodyOpen();
public abstract String getSoapBodyClose();
public abstract String getData(Object obj) throws Exception;
public abstract String getSOAPPrologue();
public abstract String getSOAPHeader(Object obj);
public abstract String getSOAPEpilogue();
public abstract String getFileName(Object obj);
public String generateSOAPMessage(Object obj) throws Exception {
String soapMessage = getSOAPPrologue() + getSOAPHeader(obj) + getSoapBody(obj) + getSOAPEpilogue();
return soapMessage;
}
}

View File

@@ -0,0 +1,131 @@
package it.valueteam.gnpsim.generator.ws;
import it.valueteam.gnp.dao.db.hb.GnpRichiesteRec;
import it.valueteam.gnp.obj.ProcessMapper;
import it.valueteam.gnp.obj.StatoRichiestaRec;
import it.valueteam.gnpsim.utility.DateUtils;
public class WSPitagoraEsitoGenerator extends WSGeneratorIF {
private static final String soapDataOpen = "<dbc:getEsito><dbc:esito>";
private static final String soapDataClose = "</dbc:esito></dbc:getEsito>";
private static final int MIN_ARGS_LEN=1;
private static final int IDX_STATO_RICHIESTA=0;
private static final int IDX_COD_KO=1;
private static final int IDX_DESC_KO=2;
private static final String PATTERN_CHECK_DATE = "yyyyMMdd";
private String statoRichiesta;
private String codiceKO;
private String descKO;
public WSPitagoraEsitoGenerator(String args[]) throws Exception
{
if(args.length < MIN_ARGS_LEN)
throw new Exception("Parametri non sufficienti");
statoRichiesta = args[IDX_STATO_RICHIESTA];
if(args.length > IDX_COD_KO)
codiceKO = args[IDX_COD_KO];
if(args.length > IDX_DESC_KO)
descKO = args[IDX_DESC_KO];
}
public String getSOAPPrologue()
{
return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:dbc=\"http://dbcfx.org\" xmlns:j=\"java:it.valueteam.gnp.obj.wsPitagora\">";
}
public String getSOAPHeader(Object obj)
{
return "<soapenv:Header/>";
}
public String getSoapBodyOpen()
{
return "<soapenv:Body>";
}
public String getSoapBodyClose()
{
return "</soapenv:Body>";
}
public String getData(Object obj) throws Exception
{
GnpRichiesteRec rec = (GnpRichiesteRec)obj;
StringBuffer buffer = new StringBuffer();
buffer.append(soapDataOpen);
buffer.append("<j:TipoComunicazione>RV</j:TipoComunicazione>");
buffer.append("<j:CodiceOrdine>");
buffer.append(rec.getIdEsigenza());
buffer.append("</j:CodiceOrdine>");
buffer.append("<j:TipoProcesso>");
if(rec.getProcesso().equals(ProcessMapper.proc_RIENTRO_ADSL) || rec.getProcesso().equals(ProcessMapper.proc_RIENTRO_ADSL_BKL) ||
rec.getProcesso().equals(ProcessMapper.proc_RIENTRO_NAKED) || rec.getProcesso().equals(ProcessMapper.proc_RIENTRO_NAKED_BKL) ||
(ProcessMapper.isDoppioDonating(rec.getProcesso()) && rec.getStato().intValue() == StatoRichiestaRec.ATTESAVERIFICA_DATI))
{
buffer.append("S");
}
else
{
buffer.append("R");
}
buffer.append("</j:TipoProcesso>");
buffer.append("<j:TipoAtterraggio>");
if(rec.getAtterraggio().equals(ProcessMapper.proc_RIENTRO_NAKED))
{
buffer.append("N");
}
else
{
buffer.append("F");
}
buffer.append("</j:TipoAtterraggio>");
buffer.append("<j:IdLinea>");
buffer.append(rec.getNumeroTelefono());
buffer.append("</j:IdLinea>");
buffer.append("<j:CodiceRisorsa>");
buffer.append(rec.getCor());
buffer.append("</j:CodiceRisorsa>");
buffer.append("<j:DataCheck>");
buffer.append(DateUtils.toString(rec.getDataCheck(), PATTERN_CHECK_DATE));
buffer.append("</j:DataCheck>");
buffer.append("<j:StatoRichiesta>");
buffer.append(statoRichiesta);
buffer.append("</j:StatoRichiesta>");
if(codiceKO != null)
{
buffer.append("<j:CodiceKO>");
buffer.append(codiceKO);
buffer.append("</j:CodiceKO>");
}
if(descKO != null)
{
buffer.append("<j:DescrizioneKO>");
buffer.append(descKO);
buffer.append("</j:DescrizioneKO>");
}
buffer.append(soapDataClose);
return buffer.toString();
}
@Override
public String getSOAPEpilogue() {
return "</soapenv:Envelope>";
}
@Override
public String getFileName(Object obj) {
return "Request_" + ((GnpRichiesteRec)obj).getIdEsigenza() + ".xml";
}
}

View File

@@ -0,0 +1,64 @@
/**
*
*/
package it.valueteam.gnpsim.obj;
/**
* @author sys0
*
*/
public class CausaliRifiutoOloDTO {
private String tipoComunicazione;
private String causaleRifiuto;
private String codiceMotivo_rifiuto;
private String motivoRifiuto;
/**
* @return the causaleRifiuto
*/
public String getCausaleRifiuto() {
return causaleRifiuto;
}
/**
* @param causaleRifiuto the causaleRifiuto to set
*/
public void setCausaleRifiuto(String causaleRifiuto) {
this.causaleRifiuto = causaleRifiuto;
}
/**
* @return the codiceMotivo_rifiuto
*/
public String getCodiceMotivo_rifiuto() {
return codiceMotivo_rifiuto;
}
/**
* @param codiceMotivo_rifiuto the codiceMotivo_rifiuto to set
*/
public void setCodiceMotivo_rifiuto(String codiceMotivo_rifiuto) {
this.codiceMotivo_rifiuto = codiceMotivo_rifiuto;
}
/**
* @return the motivoRifiuto
*/
public String getMotivoRifiuto() {
return motivoRifiuto;
}
/**
* @param motivoRifiuto the motivoRifiuto to set
*/
public void setMotivoRifiuto(String motivoRifiuto) {
this.motivoRifiuto = motivoRifiuto;
}
/**
* @return the tipoComunicazione
*/
public String getTipoComunicazione() {
return tipoComunicazione;
}
/**
* @param tipoComunicazione the tipoComunicazione to set
*/
public void setTipoComunicazione(String tipoComunicazione) {
this.tipoComunicazione = tipoComunicazione;
}
}

View File

@@ -0,0 +1,52 @@
/**
*
*/
package it.valueteam.gnpsim.obj;
/**
* @author sys0
*
*/
public class OloReplyDto {
private String idEsigenza;
private String cor;
private String cor2;
/**
* @return the cor
*/
public String getCor() {
return cor;
}
/**
* @param cor the cor to set
*/
public void setCor(String cor) {
this.cor = cor;
}
/**
* @return the cor2
*/
public String getCor2() {
return cor2;
}
/**
* @param cor2 the cor2 to set
*/
public void setCor2(String cor2) {
this.cor2 = cor2;
}
/**
* @return the idEsigenza
*/
public String getIdEsigenza() {
return idEsigenza;
}
/**
* @param idEsigenza the idEsigenza to set
*/
public void setIdEsigenza(String idEsigenza) {
this.idEsigenza = idEsigenza;
}
}

View File

@@ -0,0 +1,69 @@
package it.valueteam.gnpsim.obj;
import it.valueteam.gnp.obj.InfobusMap;
import java.util.*;
import it.valueteam.gnpsim.utility.*;
public class SystemMap {
public static final int SISTEMA_CRMR = 1;
public static final int SISTEMA_CRMB = 2;
public static final int SISTEMA_PITAGORA_XDSL = 3;
public static final int SISTEMA_PITAGORA = 4;
public static final int SISTEMA_CRMR_HZ = 5;
public static final int SISTEMA_DBC = 6;
public static final int SISTEMA_CRMB_DONOR = 7;
public static final int SISTEMA_CRMR_DONOR = 8;
private static Properties propIB = SimConfFile.getInstance().ReadSection("InfobusIN");
private SystemMap() {
}
public static String getSystemFromSimValue(int sys) throws Exception {
String result = null;
switch (sys) {
case SISTEMA_CRMR:
case SISTEMA_CRMR_HZ:
case SISTEMA_CRMR_DONOR:
result = InfobusMap.IDSYSTEM_FROMIB_CRMR;
break;
case SISTEMA_CRMB:
case SISTEMA_CRMB_DONOR:
result = InfobusMap.IDSYSTEM_FROMIB_CRMB;
break;
default:
throw new Exception("Sistema sconociuto");
}
return result;
}
public static String getServiceFromSimValue(int sys) throws Exception {
String result = null;
switch (sys) {
case SISTEMA_CRMR:
case SISTEMA_CRMB:
result = propIB.getProperty("jndiname_acqService");
break;
case SISTEMA_CRMR_HZ:
result = propIB.getProperty("jndiname_acqHzService");
break;
case SISTEMA_CRMB_DONOR:
case SISTEMA_CRMR_DONOR:
result = propIB.getProperty("jndiname_verificaCsResponse");
break;
default:
throw new Exception("Sistema sconociuto");
}
return result;
}
}

View File

@@ -0,0 +1,147 @@
package it.valueteam.gnpsim.sender;
import java.util.*;
import it.valueteam.gnp.service.*;
import it.valueteam.gnpsim.utility.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import tim.infobus.data.IBData;
import it.valueteam.gnpsim.obj.SystemMap;
public class IBSender {
private static Properties propIB = SimConfFile.getInstance().ReadSection(
"InfobusIN");
public IBSender() {
}
public static final void main(String[] args) throws Exception {
IBSender sender = new IBSender();
if (args.length < 1)
throw new Exception("Parametri insufficenti");
int system = Integer.parseInt(args[0]);
String serviceName = null;
if (args.length == 2) {
serviceName = args[1];
}
String readingPath = null;
switch (system) {
case SystemMap.SISTEMA_CRMB:
readingPath = propIB.getProperty("GEN_PATH_CRMB");
System.out.println("Reading folder " + readingPath);
sender.sendFiles(readingPath, system, serviceName);
break;
case SystemMap.SISTEMA_CRMR:
readingPath = propIB.getProperty("GEN_PATH_CRMR");
sender.sendFiles(readingPath,system, serviceName);
break;
case SystemMap.SISTEMA_CRMR_HZ:
readingPath = propIB.getProperty("GEN_PATH_CRMB_HZ");
sender.sendHZFiles(readingPath,system);
break;
case SystemMap.SISTEMA_CRMB_DONOR:
readingPath = propIB.getProperty("GEN_PATH_CRMB_DONOR");
sender.sendFiles(readingPath,system, serviceName);
break;
case SystemMap.SISTEMA_CRMR_DONOR:
readingPath = propIB.getProperty("GEN_PATH_CRMR_DONOR");
sender.sendFiles(readingPath,system, serviceName);
break;
}
}
private void sendHZFiles(String readingPath, int system) throws Exception {
String[] toSend = IOUtility.readFileXML(readingPath);
for (int i = 0; i < toSend.length; i++) {
sendHZRequest(toSend[i], system);
}
}
private void sendFiles(String readingPath, int system, String serviceName) throws Exception {
String[] toSend = IOUtility.readFileXML(readingPath);
for (int i = 0; i < toSend.length; i++) {
sendRequest(toSend[i], system, serviceName);
}
}
public void sendRequest(String tracciato, int system) throws Exception {
sendRequest(tracciato, system, null);
}
public void sendRequest(String tracciato, int system, String ibServiceName) throws Exception {
String jndiName = SystemMap.getServiceFromSimValue(system);
switch (system) {
case SystemMap.SISTEMA_CRMR:
case SystemMap.SISTEMA_CRMB:
AcqServiceHome acqServiceHome = (AcqServiceHome) PortableRemoteObject.narrow(getHomeIbIn(jndiName), AcqServiceHome.class);
AcqService service = acqServiceHome.create();
service.richiestaCRM(createIBData(system, tracciato, ibServiceName));
break;
case SystemMap.SISTEMA_CRMB_DONOR:
case SystemMap.SISTEMA_CRMR_DONOR:
VerificaCSResponseHome verificaCSResponseHome = (VerificaCSResponseHome) PortableRemoteObject.narrow(getHomeIbIn(jndiName), VerificaCSResponseHome.class);
VerificaCSResponse csResponse = verificaCSResponseHome.create();
csResponse.esitoVerificaCS(createIBData(system, tracciato, ibServiceName));
break;
default:
throw new Exception("Sistema sconociuto");
}
}
public void sendHZRequest(String tracciato, int system) throws Exception {
String jndiName = SystemMap.getServiceFromSimValue(system);
AcqServiceHZHome acqServiceHome = (AcqServiceHZHome) PortableRemoteObject.narrow(getHomeIbIn(jndiName), AcqServiceHZHome.class);
AcqServiceHZ service = acqServiceHome.create();
service.richiestaCRM(createIBData(system, tracciato, null));
}
private IBData createIBData(int system, String tracciato, String ibServiceName) throws Exception {
IBData ibData = new IBData();
byte[] bDati = tracciato.getBytes();
ibData.setData(bDati);
ibData.setSystem(SystemMap.getSystemFromSimValue(system));
if (ibServiceName != null) {
ibData.setService( ibServiceName );
}
return ibData;
}
private static Object getHomeIbIn(String jndiName) throws Exception {
Context ctx = getServerContextForIBIN();
Object ref = ctx.lookup(jndiName);
return ref;
}
private static Context getServerContextForIBIN() throws Exception {
Hashtable<String, String> ht = new Hashtable<String, String>();
Context ctx = null;
ht.put(Context.INITIAL_CONTEXT_FACTORY, propIB
.getProperty("initialContextFactory"));
ht.put(Context.SECURITY_PRINCIPAL, propIB.getProperty("user"));
ht.put(Context.SECURITY_CREDENTIALS, propIB.getProperty("password"));
ht.put(Context.PROVIDER_URL, propIB.getProperty("url"));
ctx = new InitialContext(ht);
return ctx;
}
}

View File

@@ -0,0 +1,144 @@
package it.valueteam.gnpsim.sender;
import it.valueteam.gnpsim.utility.SimConfFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
public class SOAPSender {
private static Properties propWSPitagora = SimConfFile.getInstance().ReadSection("WS_Pitagora");
private static Properties propWSCRMA = SimConfFile.getInstance().ReadSection("WS_CRMA");
private static final int MIN_PARAMS_NUMBER = 1;
private static final int PARAM_SISTEMA_IDX = 0;
private static final int PARAM_SISTEMA_PITAGORA = 1;
private static final int PARAM_SISTEMA_CRMA = 2;
private URL url;
private String filepath;
private SOAPSender(Properties props)
throws Exception
{
// Create the connection where we're going to send the file.
url = new URL(props.getProperty("WS_ENDPOINT"));
filepath = props.getProperty("GEN_PATH");
}
public static void main(String[] args) throws Exception {
if(args.length < MIN_PARAMS_NUMBER)
throw new Exception("Numero parametri insufficiente. Consultare la documentazione");
SOAPSender sender = null;
int sistema = Integer.parseInt(args[PARAM_SISTEMA_IDX]);
switch(sistema)
{
case PARAM_SISTEMA_PITAGORA:
sender = new SOAPSender(propWSPitagora);
break;
case PARAM_SISTEMA_CRMA:
sender = new SOAPSender(propWSCRMA);
break;
default:
throw new Exception("Sistema sconosciuto");
}
sender.sendAllFiles();
}
// copy method from From E.R. Harold's book "Java I/O"
public static void copy(InputStream in, OutputStream out)
throws IOException {
// do not allow other threads to read from the
// input or write to the output while copying is
// taking place
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}
}
}
}
private void sendAllFiles()
throws Exception
{
File directory = new File(filepath);
String[] fileNames = directory.list();
for(int i=0; i < fileNames.length; ++i)
{
sendFile(fileNames[i]);
File filesent = new File(filepath+fileNames[i]);
filesent.delete();
}
}
private void sendFile(String fileName)
throws Exception
{
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Open the input file. After we copy it to a byte array, we can see
// how big it is so that we can set the HTTP Cotent-Length
// property. (See complete e-mail below for more on this.)
String xmlFile2Send = filepath + fileName;
System.out.println("Invio messaggio SOAP contenuto nel file " + xmlFile2Send);
System.out.println("All'indirizzo " + url);
FileInputStream fin = new FileInputStream(xmlFile2Send);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Copy the SOAP file to the open connection.
copy(fin,bout);
fin.close();
byte[] b = bout.toByteArray();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty( "Content-Length",
String.valueOf( b.length ) );
httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
// httpConn.setRequestProperty("SOAPAction",SOAPAction);
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr =
new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

View File

@@ -0,0 +1,763 @@
package it.valueteam.gnpsim.utility;
/**
* Title: Amministrazione magistratura
* Description:
* Copyright: Copyright (c) 2000
* Company: OW
* @author Paloni Gian Luca
* @version 1.0
*/
import java.text.*;
import java.util.*;
/**
Classe di metodi statici per il trattamento delle date
@author Marco Salvalaggio
*/
public class DateUtils
{
public static String getCurrentStringDate() {
return "'"+DateUtils.toString(new java.util.Date()) +
" "+DateUtils.getHourMinSec(new java.util.Date())+"', 'yyyy-MM-dd HH24:mi:ss'";
}
public static String getCurrentNomeFileStringDate() {
return DateUtils.toStringFileName(new java.util.Date()) +
DateUtils.getHourMinSecFileName(new java.util.Date());
}
/**
Determina se due date sono uguali, prendendo in considerazione
anche la possibilita' che una delle due, o tutte e due, siano null.
*/
public static boolean areEqual( Date data1, Date data2 )
{
if( data1 == data2 )
return true;
if( data1 == null )
return false;
if( data2 == null )
return false;
return data1.equals(data2);
}
/* conversione di una java.util.Date in una java.sql.Timestamp : Fabrizio Ceracchi*/
public static java.sql.Timestamp date2Timestamp(java.util.Date du)
{
if (du==null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(du);
/* (PG: 8/5/01): Class constructor deprecated...
java.sql.Timestamp ds=new java.sql.Timestamp(cal.get(Calendar.YEAR)-1900,
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND),
0);
*/
// (PG: 8/5/01): New Version..
java.sql.Timestamp ds=new java.sql.Timestamp(cal.getTime().getTime());
// ends
return ds;
}
public static Date getCurrentSysDate(boolean zeroHour){
Date d = new java.util.Date();
if (!zeroHour || d==null) return d;
return zeroHour(d);
}
/**
METODO utilizzato per recuperare le date complete di ora dal DB.
L'oggetto ottenuto con result.getObject contiene la data completa
che viene traformata in un oggetto Date con un casting.
@param r ResultSet da cui estrarre la data
@param field Stringa identificativa del campo del db da cui estrarre la data
@return la data completa di ora
*/
public static java.util.Date getDateTime( java.sql.ResultSet r, String field )
throws java.sql.SQLException
{
return (java.util.Date)r.getObject(field);
}
/**
Trasforma una stringa secondo il formato dd/mm/yyyy in data.
In caso di errore di conversione viene lanciata un'eccezione.
*/
public static Date toDate(String d)
throws Exception
{
if( d == null || d.trim().length() == 0 )
return null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
Date data = null;
try
{
// Questo va bene lato client
sdf.setLenient(false);
data = sdf.parse(d);
}
catch( ParseException pEx )
{
// Questo lato server
/*************************************************************/
/* Il problema è che, a quanto sembra, la JVM lato server */
/* non converte correttamente le date pari al 29 febbraio di */
/* un qualsiasi anno bisestile. (MS 14/11/2000) */
/*************************************************************/
sdf.setLenient(true);
data = sdf.parse(d);
String tempStr = sdf.format(data);
if( !d.equals(tempStr) )
throw pEx;
}
if( data == null )
throw new Exception("Formato della data non valido");
return data;
}
/**
* Questo metodo partendo dalla data odierna ottiene la data di oggi con un'ora impostabile
* da parametro.
* Il parametro è una Stringa formattata come HH:MM:ss che
* rappresenta ora,minuti,secondi.
* @param ora
* @return
* @throws java.lang.Exception
*/
public static Date getTodayWithHour(String ora) throws Exception
{
try {
java.util.Date data_odierna = new java.util.Date(); //data odierna
String data = DateUtils.toString(data_odierna); //la date diventa String in formato yyyy-mm-dd
String data_ora = data + " "+ ora; //la data diventa una stringa di formato yyyy-mm-dd HH:MM:ss
java.util.Date oggi_vero = DateUtils.toDateHourBis(data_ora);
return oggi_vero;
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
* Questo metodo partendo dalla data odierna ottiene la data di domani con un'ora impostabile
* da parametro.
* Il parametro è una Stringa formattata come HH:MM:ss che
* rappresenta ora,minuti,secondi.
* @param ora
* @return
* @throws java.lang.Exception
*/
public static Date getTomorrowWithHour(String ora) throws Exception
{
try {
java.util.Date data_odierna = new java.util.Date(); //data odierna
String data = DateUtils.toString(data_odierna); //la date diventa String in formato yyyy-mm-dd
String domani = DateUtils.aggiungiGiorniLavorativi(data, 1); //Aggiunge un giorno lavorativo
String data_ora = domani + " "+ ora; //la data diventa una stringa di formato yyyy-mm-dd HH:MM:ss
java.util.Date domani_vero = DateUtils.toDateHourBis(data_ora);
return domani_vero;
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
Trasforma una stringa secondo il formato passato in data.
In caso di errore di conversione viene lanciata un'eccezione.
*/
public static Date toDate(String d,String format)
throws Exception
{
if( d == null || d.trim().length() == 0 )
return null;
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
Date data = null;
try
{
// Questo va bene lato client
sdf.setLenient(false);
data = sdf.parse(d);
}
catch( ParseException pEx )
{
// Questo lato server
/*************************************************************/
/* Il problema è che, a quanto sembra, la JVM lato server */
/* non converte correttamente le date pari al 29 febbraio di */
/* un qualsiasi anno bisestile. (MS 14/11/2000) */
/*************************************************************/
sdf.setLenient(true);
data = sdf.parse(d);
String tempStr = sdf.format(data);
if( !d.equals(tempStr) )
throw pEx;
}
if( data == null )
throw new Exception("Formato della data non valido");
return data;
}
/**
Trasforma una stringa secondo il formato yyyy-MM-dd HH:mm:ss.S in data.
In caso di errore di conversione viene lanciata un'eccezione.
Utile per riconvertire in Date un oggetto che originariamente lo era già
ma sul quale è stato applicato toString
*/
public static Date stringToDate(String d)
throws Exception
{
if( d == null || d.trim().length() == 0 )
return null;
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
Date data = null;
try
{
// Questo va bene lato client
sdf.setLenient(false);
data = sdf.parse(d);
}
catch( ParseException pEx )
{
// Questo lato server
/*************************************************************/
/* Il problema è che, a quanto sembra, la JVM lato server */
/* non converte correttamente le date pari al 29 febbraio di */
/* un qualsiasi anno bisestile. (MS 14/11/2000) */
/*************************************************************/
sdf.setLenient(true);
data = sdf.parse(d);
String tempStr = sdf.format(data);
if( !d.equals(tempStr) )
throw pEx;
}
if( data == null )
throw new Exception("Formato della data non valido");
return data;
}
/**
Trasforma una stringa secondo il formato dd/mm/yyyy hh:mm:ss in data.
In caso di errore di conversione viene lanciata un'eccezione.
*/
public static Date toDateHour(String d)
throws Exception
{
if( d == null || d.trim().length() == 0 )
return null;
if (d.trim().length() <= 10)
d = d+" 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
Date data = null;
try
{
// Questo va bene lato client
sdf.setLenient(false);
data = sdf.parse(d);
}
catch( ParseException pEx )
{
// Questo lato server
/*************************************************************/
/* Il problema è che, a quanto sembra, la JVM lato server */
/* non converte correttamente le date pari al 29 febbraio di */
/* un qualsiasi anno bisestile. (MS 14/11/2000) */
/*************************************************************/
sdf.setLenient(true);
data = sdf.parse(d);
String tempStr = sdf.format(data);
if( !d.equals(tempStr) )
throw pEx;
}
if( data == null )
throw new Exception("Formato della data non valido");
return data;
}
/**
Trasforma una stringa secondo il formato yyyy-mm-dd hh:mm:ss in data.
In caso di errore di conversione viene lanciata un'eccezione.
*/
public static Date toDateHourBis(String d)
throws Exception
{
if( d == null || d.trim().length() == 0 )
return null;
if (d.trim().length() <= 10)
d = d+" 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
Date data = null;
try
{
// Questo va bene lato client
sdf.setLenient(false);
data = sdf.parse(d);
}
catch( ParseException pEx )
{
// Questo lato server
/*************************************************************/
/* Il problema è che, a quanto sembra, la JVM lato server */
/* non converte correttamente le date pari al 29 febbraio di */
/* un qualsiasi anno bisestile. (MS 14/11/2000) */
/*************************************************************/
sdf.setLenient(true);
data = sdf.parse(d);
String tempStr = sdf.format(data);
if( !d.equals(tempStr) )
throw pEx;
}
if( data == null )
throw new Exception("Formato della data non valido");
return data;
}
/**
Trasforma una data in stringa secondo il formato yyyy-MM-dd
*/
public static String toString(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone tz = TimeZone.getTimeZone("ECT");
if( tz != null )
sdf.setTimeZone( tz );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato yyyyMMdd
*/
public static String toStringFileName(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
TimeZone tz = TimeZone.getTimeZone("ECT");
if( tz != null )
sdf.setTimeZone( tz );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato yyyy-mm-dd
*/
public static String toStringStandard(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
/**
Trasforma una stringa che rappresenta una data in formato dd/mm/yyyy
in stringa secondo il formato yyyy-mm-dd
*/
public static String standardDateFormat(String d)
throws Exception
{
if( d == null )
return "";
return toStringStandard( toDate(d) );
}
/**
Trasforma una data in stringa secondo il formato dd/mm/yyyy hh:mm:ss
*/
public static String toStringHour(java.util.Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato hh:mm
*/
public static String getHour(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato yyyy
*/
public static String getYear(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato HH:mm:ss
*/
public static String getHourMinSec(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
/**
Trasforma una data in stringa secondo il formato HH:mm:ss
*/
public static String getHourMinSecFileName(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
sdf.setTimeZone( TimeZone.getTimeZone("ECT") );
return sdf.format(d);
}
public static java.sql.Timestamp toTimestamp(String s) throws Exception {
return date2Timestamp(DateUtils.toDate(s));
}
public static Date zeroHour(Date d){
if (d==null) return null;
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
/**
* QUESTO METODO AGGIUNGE IL NUMERO DI GIORNI LAVORATIVI ALLA DATA INDICATA
* CHE DEV'ESSERE NEL FORMATO yyyy-MM-dd CONTROLLANDO CHE QUESTA DATA NON SIA A SUA
* VOLTA UN GIORNO FESTIVO, IN TAL CASO LA INCREMENTA FINO AD ARRIVARE AL PRIMO GIORNO
* LAVORATIVO UTILE SUCCESSIVO A TALE DATA.
*/
public static String aggiungiGiorniLavorativi(String dataRicezione, int giorni) throws Exception
{
ImpostaDate id = new ImpostaDate();
return id.aggiungiGiorniItalianFormat(dataRicezione, giorni);
}
public static String aggiungiGiorniLavorativi(Date dataRicezione,int giorni, String pattern) throws Exception {
String sDate = toString(dataRicezione,pattern);
return aggiungiGiorniLavorativi(sDate,giorni);
}
public static String aggiungiGiorniLavorativiCrm(Date dataRicezione,int giorni, String pattern) throws Exception {
String sDate = toString(dataRicezione,pattern);
return aggiungiGiorniLavorativiCrm(sDate,giorni);
}
public static String aggiungiGiorniLavorativiCrm(String dataRicezione, int giorni) throws Exception
{
ImpostaDate id = new ImpostaDate();
return id.aggiungiGiorniItalianCrmFormat(dataRicezione, giorni);
}
/**
*Trasforma una data in stringa secondo il formato voluto
* es: yyyy-MM-dd HH:mm:ss
* es: yyyy-MM-dd
*/
public static String toString(Date d,String format)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
TimeZone tz = TimeZone.getTimeZone("ECT");
if( tz != null )
sdf.setTimeZone( tz );
return sdf.format(d);
}
public static String getCurrentStringDateEstesa() {
return DateUtils.toStringEstesa(new java.util.Date()) +
" "+DateUtils.getHourMinSec(new java.util.Date());
}
public static String toStringEstesa(Date d)
{
if( d == null )
return "";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
TimeZone tz = TimeZone.getTimeZone("ECT");
if( tz != null )
sdf.setTimeZone( tz );
return sdf.format(d);
}
/**
*Prende una data in formato YYYY-MM-DD HH:MM:SS o MM-DD-YYYY HH:MM:SS
*e la fa diventare DD/MM/YYYY HH:MM:SS
*/
public static String toItalianStringHour(String sData) throws Exception{
String sNewData = "";
if((sData==null) || (sData.equals(""))){
return sNewData;
}
String sAnno = "";
String sMese = "";
String sGior = "";
String sOra = "";
String s = "";
String s2 = "";
String s3 = "";
//controlla che il separatore sia il '-' o lo '/'
int indice = sData.indexOf('-');
if(indice < 0)indice = sData.indexOf('/');
if(indice < 0)return sNewData;
if(indice == 4){//il formato è con YYYY-
sAnno = sData.substring(0,4);
sMese = sData.substring(5,7);
sGior = sData.substring(8,10);
sOra = sData.substring(11);
sNewData = sGior + "/" + sMese + "/" + sAnno + " " + sOra;
}else{
s = sData.substring(0,indice);
s2 = sData.substring(indice+1,indice+3);
s3 = sData.substring(indice+4,indice+8);
sOra = sData.substring(indice+9);
if(Integer.parseInt(s2) >= 12){//il formato è MM-DD-YYYY
sNewData = s2 + "/" + s + "/" + s3 +" " + sOra;
}else{
sNewData = sData; //xchè il formato è già italiano.
}
}
return sNewData;
}
/**
*Prende una data in formato YYYY-MM-DD HH:MM:SS o MM-DD-YYYY
*e la fa diventare DD/MM/YYYY
*/
public static String toItalianString(String sData) throws Exception{
String sNewData = "";
if((sData==null) || (sData.equals(""))){
return sNewData;
}
String sAnno = "";
String sMese = "";
String sGior = "";
//controlla che il separatore sia il '-' o lo '/'
sAnno = sData.substring(0,4);
sMese = sData.substring(5,7);
sGior = sData.substring(8,10);
sNewData = sGior + "/" + sMese + "/" + sAnno ;
return sNewData;
}
/**
* Toglie l'ora da una data (stringa) in formato YYYY-MM-DD HH24:MI:SS
* torna -> YYYY-MM-DD
*/
public static String troncaOra(String sData) throws Exception{
String sNewData = "";
if((sData==null) || (sData.equals(""))){
return sNewData;
}
sNewData = sData.substring(0,sData.indexOf(" "));
return sNewData;
}
/**
* Metodo per aggiungere giorni solari alla data passata in input (formato yyyy-MM-dd)
* @param inputDate
* @param numGiorni
* @return
* @throws java.lang.Exception
*/
public static Date aggiungiGiorniSolari(Date inputDate, int numGiorni) throws Exception {
return toDate(aggiungiGiorniSolari(toString(inputDate),numGiorni),"yyyy-MM-dd");
}
/**
* Metodo per aggiungere giorni solari alla data passata in input (formato yyyy-MM-dd)
* @param inputDate
* @param numGiorni
* @return
* @throws java.lang.Exception
*/
public static String aggiungiGiorniSolari(String inputDate, int numGiorni) throws Exception
{
try
{
java.util.Date data = DateUtils.toDate(inputDate, "yyyy-MM-dd");
//Impostazione del timezone
TimeZone tz = TimeZone.getTimeZone("Europe/Rome");
Calendar calendar = new GregorianCalendar(tz);
//Calendario impostato alla data in input
calendar.setTime(data);
//Giorni aggiunti
calendar.add(Calendar.DAY_OF_MONTH, numGiorni);
// System.out.println("DATA: " + calendar.getTime());
return DateUtils.toString(calendar.getTime());
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
* Restituisce la java.sql.Date corrispondente alla java.util.Date
* @param du Date
* @return Date
*/
public static java.sql.Date date2sqlDate(java.util.Date du) {
if (du == null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(du);
java.sql.Date ds = new java.sql.Date(cal.getTime().getTime());
return ds;
}
public static java.util.Date sqlDate2date(java.sql.Date sqlData) {
if (sqlData == null)
return null;
else
return new java.util.Date(sqlData.getTime());
}
public static java.util.Date timestamp2date(java.sql.Timestamp sqlTimeStamp) {
if (sqlTimeStamp == null)
return null;
else
return new java.util.Date(sqlTimeStamp.getTime());
}
public static Date aggiungiGiorniLavorativiTodate(Date dataRicezione,int giorni) throws Exception {
return toDate(aggiungiGiorniLavorativi(toString(dataRicezione,"dd-MM-yyyy"),giorni),"dd-MM-yyyy");
}
}

View File

@@ -0,0 +1,103 @@
package it.valueteam.gnpsim.utility;
import java.io.*;
public class IOUtility {
public IOUtility() {
}
public static void writeFile(String nomeFile, String[] content) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(nomeFile));
if(content!=null){
for (int i = 0; i < content.length; i++) {
writer.write(content[i]+"\n");
System.out.println("WRITE FILE: \n" + nomeFile);
System.out.println("CONTENT : \n" + content[i]);
}
}
writer.flush();
}
catch (Exception ex) {
System.out.println("ERRORE DURANTE LA SCRITTURA DEL FILE : " + nomeFile);
System.out.println("ERROR MESSAGE: " + ex.getMessage());
ex.printStackTrace();
}
finally {
try {
if (writer != null) {
writer.close();
}
}
catch (IOException ex1) {
System.out.println(
"ERRORE DURANTE LA CHIUSURA DELLO STREAM PER IL FILE : " + nomeFile);
}
}
}
public static String[] readFileXML(String path) {
File directory = new File(path);
String[] result = null;
BufferedReader reader = null;
try {
String[] files = directory.list();
if (files == null || files.length == 0) {
System.out.println("Nessun File presente nella directory : " + path);
}
else {
result = new String[files.length];
for (int i = 0; i < files.length; i++) {
try {
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new FileReader(path + files[i]));
while (reader.ready()) {
buffer.append(reader.readLine());
}
result[i] = buffer.toString();
System.out.println("READ FILE : \n" + path + files[i]);
System.out.println("CONTENT : \n" + result[i]);
}
catch (Exception ex) {
System.out.println("ERRORE DURANTE LA LETTURA DEL FILE : " + path +
files[i]);
}
finally {
try {
if (reader != null)
reader.close();
}
catch (IOException ex1) {
System.out.println(
"ERRORE DURANTE LA CHIUSURA DELLO STREAM DI LETTURA ");
}
}
File f = new File(path + files[i]);
System.out.println("DELETE FILE : \n" + path + files[i]);
f.deleteOnExit();
}
}
}
catch (Exception ex) {
System.out.println("ERRORE DURANTE LA LETTURA DEI FILE IN : " + path);
ex.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,414 @@
package it.valueteam.gnpsim.utility;
import java.util.*;
public class ImpostaDate
{
protected static Properties propFest = SimConfFile.getInstance().ReadSection(
"Festivita");
public static boolean isFestivity(GregorianCalendar cal)
{
boolean isFestivity = false;
int giorno = cal.get(Calendar.DAY_OF_MONTH);
int mese = cal.get(Calendar.MONTH)+1;
//Controlla che non sia un lunedì di Pasqua
if(getFestivitaPasquale() == cal.get(Calendar.DAY_OF_YEAR))
isFestivity = true;
if (!isFestivity) {
Collection festivita = propFest.values();
Iterator iterFest = festivita.iterator();
//Controlla che non sia una festivita
while (iterFest.hasNext()) {
String dataFestivita = (String) iterFest.next();
if (dataFestivita.equalsIgnoreCase("SABATO")) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
isFestivity = true;
}
else
if (dataFestivita.equalsIgnoreCase("DOMENICA")) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
isFestivity = true;
}
else {
int giornoFestivita = Integer.parseInt(dataFestivita.substring(0,
dataFestivita.indexOf("/")));
int meseFestivita = Integer.parseInt(dataFestivita.substring(
dataFestivita.indexOf("/") + 1));
if (giorno == giornoFestivita && mese == meseFestivita)
isFestivity = true;
}
}
}
return isFestivity;
}
private static int getFestivitaPasquale()
{
GregorianCalendar gc = new GregorianCalendar();
int anno = gc.get(Calendar.YEAR);
Integer integer = new Integer(anno);
double A=integer.doubleValue();
double bisest = 0;
if ((A % 4 == 0) && (A % 100 != 0) || (A % 400 == 0))
bisest = 1;
double n=A % 19;
double c=Math.floor(A/100);
double u=A % 100;
double s=Math.floor(c/4);
double t=c % 4;
double p=Math.floor((c+8)/25);
double q=Math.floor((c-p+1)/3);
double e=(19*n+c-s-q+15) % 30;
double b=Math.floor(u/4);
double d=u % 4;
double l=(32+2*t+2*b-e-d) % 7;
double h=Math.floor((n+11*e+22*l)/451);
double m=Math.floor((e+l-17*h+114)/31);
double j=(e+l-17*h+114) % 31;
j=j+1;
double xpasqua=59+bisest;
if (m==3) xpasqua=xpasqua+j;
if (m==4) xpasqua=xpasqua+31+j;
// double xcarnevale=xpasqua-49;
// double xmartedigrasso=xpasqua-47;
// double xceneri=xpasqua-46;
double xlunedidipasqua=xpasqua+1;
// double xpalme=xpasqua-7;
// double xascensione=xpasqua+39;
// double xpentecoste=xpasqua+49;
// double xtrinita=xpasqua+56;
// double xcorpusdomini=xpasqua+60;
// double hgiorno=0;
Double dou = new Double(xlunedidipasqua);
return dou.intValue();
}
public String addWorkingDay(String Dins, int numberDay)
{
////System.out.println("addWorkingDays:inizio");
////System.out.println("paramatri="+Dins+" "+numberDay);
GregorianCalendar cal;
int aa=0,gg=0,mm=0;
aa=Integer.parseInt(Dins.substring(0,4));
//System.out.println("aa="+aa);
mm=(Integer.parseInt(Dins.substring(5,7)))-1;
// mm=Integer.parseInt(Dins.substring(5,7));
//System.out.println("mm="+mm);
gg=Integer.parseInt(Dins.substring(8,10));
//System.out.println("gg="+gg);
cal=new GregorianCalendar(aa,mm,gg);
////System.out.println("cal="+cal);
int i = 0;
while(i < numberDay)
{
cal.add(Calendar.DAY_OF_YEAR,1);
if(!isFestivity(cal))
i++;
}
String Sa=""+cal.get(Calendar.YEAR);
//System.out.println("Sa="+Sa);
String Sm=""+(cal.get(Calendar.MONTH)+1);
//System.out.println("Sa="+Sm);
String Sg=""+cal.get(Calendar.DATE);
//System.out.println("Sg="+Sg);
Sm=Sm.length()==1?"0"+Sm:Sm;
Sg=Sg.length()==1?"0"+Sg:Sg;
//System.out.println("data di ritorno--------->>> "+Sa+"-"+Sm+"-"+Sg);
//System.out.println("FineMetodo");
return ""+Sa+"-"+Sm+"-"+Sg;
}
public static boolean confronto(String cut_over,String richiesta_op)
{
boolean tempo=true;
int gg=0,mm=0;
//System.out.println("aa="+aa);
mm=(Integer.parseInt(cut_over.substring(5,7)))-1;
//System.out.println("mm="+mm);
gg=Integer.parseInt(cut_over.substring(8,10));
//System.out.println("gg="+gg);
////System.out.println("cal="+cal);
int gg1=0,mm1=0;
//System.out.println("aa="+aa1);
mm1=(Integer.parseInt(richiesta_op.substring(5,7)))-1;
//System.out.println("mm="+mm1);
gg1=Integer.parseInt(richiesta_op.substring(8,10));
//System.out.println("gg="+gg1);
//System.out.println("cal="+cal1);
if(mm==mm1)
{
if((gg-gg1)<10)
{
tempo=true;
//System.out.println("1");
//System.out.println("1"+(gg-gg1));
}
if((gg-gg1)>10)
{
tempo= false;
//System.out.println("2");
//System.out.println("2"+(gg-gg1));
}
}
else if(mm1==4||mm1==6||mm1==11||mm1==9)
{
int temp=30-gg1;
if((temp+gg)<10)
{
tempo= true;
//System.out.println("3");
//System.out.println("3"+gg+""+gg1);
}
if((temp+gg)>10)
{
tempo=false;
//System.out.println("4");
}
}
else if(mm1==2)
{
int temp=28-gg1;
if((temp+gg)<10)
{
tempo= true;
//System.out.println("5");
}
if((temp+gg)>10)
{
tempo= false;
//System.out.println("6");
}
}
else
{
int temp=31-gg1;
if((temp+gg)<10)
{
tempo= true;
//System.out.println("7");
}
if((temp+gg)>10)
{
tempo= false;
//System.out.println("8");
}
}
//System.out.println("FINE METODO CONFRONTO");
return tempo;
}
public String verificaManutenzioneProgrammata(String cut_over)
{
GregorianCalendar cal;
int aa=0,gg=0,mm=0;
aa=Integer.parseInt(cut_over.substring(0,4));
//System.out.println("aa="+aa);
mm=(Integer.parseInt(cut_over.substring(5,7)));
//System.out.println("mm="+mm);
gg=Integer.parseInt(cut_over.substring(8,10));
//System.out.println("gg="+gg);
cal=new GregorianCalendar(aa,mm-1,gg);
////System.out.println("cal="+cal);
do
{
cal.add(Calendar.DAY_OF_MONTH,1);
}
while(isFestivity(cal));
String mese=""+(cal.get(Calendar.MONTH)+1);
if (mese.length()==1)
mese="0"+mese;
String giorno=""+cal.get(Calendar.DAY_OF_MONTH);
if (giorno.length()==1)
giorno="0"+giorno;
String dat=""+cal.get(Calendar.YEAR)+"-"+mese+"-"+giorno;
//System.out.println("dat: "+dat);
return dat;
}
public String aggiungiGiorni(String data,int giorni)
{
GregorianCalendar cal;
int aa=0,gg=0,mm=0;
aa=Integer.parseInt(data.substring(0,4));
//System.out.println("aa="+aa);
mm=(Integer.parseInt(data.substring(5,7)));
//System.out.println("mm="+mm);
gg=Integer.parseInt(data.substring(8,10));
//System.out.println("gg="+gg);
cal=new GregorianCalendar(aa,mm-1,gg);
////System.out.println("cal="+cal);
if(giorni>0)
{
int conta=0;
while(conta<giorni)
{
cal.add(Calendar.DAY_OF_MONTH,1);
if(!isFestivity(cal))
conta++;
}
}
else
{
int conta=-giorni;
/* CP. 7/02/03
*/
while(conta>0) {
cal.add(Calendar.DAY_OF_MONTH,-1);
if(!isFestivity(cal))
conta--;
}
}
String mese=""+(cal.get(Calendar.MONTH)+1);
if (mese.length()==1)
mese="0"+mese;
String giorno=""+cal.get(Calendar.DAY_OF_MONTH);
if (giorno.length()==1)
giorno="0"+giorno;
String dat=""+cal.get(Calendar.YEAR)+"-"+mese+"-"+giorno;
//System.out.println("dat: "+dat);
return dat;
}
public String aggiungiGiorniItalianFormat(String data,int giorni)
{
GregorianCalendar cal;
int aa=0,gg=0,mm=0;
aa=Integer.parseInt(data.substring(6,10));
//System.out.println("aa="+aa);
mm=(Integer.parseInt(data.substring(3,5)));
//System.out.println("mm="+mm);
gg=Integer.parseInt(data.substring(0,2));
//System.out.println("gg="+gg);
cal=new GregorianCalendar(aa,mm-1,gg);
////System.out.println("cal="+cal);
if(giorni>0)
{
int conta=0;
while(conta<giorni)
{
cal.add(Calendar.DAY_OF_MONTH,1);
if(!isFestivity(cal))
conta++;
}
}
else
{
int conta=-giorni;
/* CP. 7/02/03
*/
while(conta>0) {
cal.add(Calendar.DAY_OF_MONTH,-1);
if(!isFestivity(cal))
conta--;
}
}
String mese=""+(cal.get(Calendar.MONTH)+1);
if (mese.length()==1)
mese="0"+mese;
String giorno=""+cal.get(Calendar.DAY_OF_MONTH);
if (giorno.length()==1)
giorno="0"+giorno;
// String dat=""+cal.get(Calendar.YEAR)+"-"+mese+"-"+giorno;
String dat=""+giorno+"/"+mese+"/"+cal.get(Calendar.YEAR);
//System.out.println("dat: "+dat);
return dat;
}
public String aggiungiGiorniItalianCrmFormat(String data,int giorni)
{
GregorianCalendar cal;
int aa=0,gg=0,mm=0;
aa=Integer.parseInt(data.substring(6,10));
//System.out.println("aa="+aa);
mm=(Integer.parseInt(data.substring(3,5)));
//System.out.println("mm="+mm);
gg=Integer.parseInt(data.substring(0,2));
//System.out.println("gg="+gg);
cal=new GregorianCalendar(aa,mm-1,gg);
////System.out.println("cal="+cal);
if(giorni>0)
{
int conta=0;
while(conta<giorni)
{
cal.add(Calendar.DAY_OF_MONTH,1);
if(!isFestivity(cal))
conta++;
}
}
else
{
int conta=-giorni;
/* CP. 7/02/03
*/
while(conta>0) {
cal.add(Calendar.DAY_OF_MONTH,-1);
if(!isFestivity(cal))
conta--;
}
}
String mese=""+(cal.get(Calendar.MONTH)+1);
if (mese.length()==1)
mese="0"+mese;
String giorno=""+cal.get(Calendar.DAY_OF_MONTH);
if (giorno.length()==1)
giorno="0"+giorno;
// String dat=""+cal.get(Calendar.YEAR)+"-"+mese+"-"+giorno;
String dat=""+giorno+"-"+mese+"-"+cal.get(Calendar.YEAR);
//System.out.println("dat: "+dat);
return dat;
}
/**
* @param dataRicezione
* @param giorni
* @return
*/
public String aggiungiGiorniItalianPitagoraFormat(String dataRicezione, int giorni) {
return null;
}
}

View File

@@ -0,0 +1,641 @@
package it.valueteam.gnpsim.utility;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
/**
* <b><p>Description:</b><br>
* JIniFile stores and retrieves application-specific information and settings from INI files.
* <br><br>
* JIniFile enables handling the storage and retrieval of application-specific information
* and settings in a standard INI file. The INI file text format is a standard introduced
* in Windows 3.x for storing and retrieving application settings from session to session.
* An INI file stores information in logical groupings, called "sections." For example,
* the WIN.INI file contains a section called "[Desktop]". Within each section, actual data
* values are stored in named keys. Keys take the form:
* <br><br>
* &lt;keyname&gt;=&lt;value&gt;<br>
* A FileName is passed to the JIniFile constructor and identifies the INI file that the object accesses.</p>
* @author Andreas Norman
* @version 1.0
*
*/
public class JIniFile extends ArrayList {
private static final long serialVersionUID = 1L;
private File userFileName;
//private static Logger logger = Logger.getLogger("phco.init");
/**
* Constructor JIniFile
*
* Creates a JIniFile object for an application. Create assigns the FileName parameter
* to the FileName property, which is used to specify the name of the INI file to use.
* <p>
* <b>Note:</b> By default the INI files are stored in the Application directory. To work with an INI file in another
* location, specify the full path name of the file in FileName.
*/
@SuppressWarnings("unchecked")
public JIniFile(String name) {
System.out.println("ini-file LOADING " + name);
clear();
this.userFileName = new File(name);
if (userFileName.exists()) {
System.out.println("ini-file READING ");
try {
BufferedReader inbuf = new BufferedReader(new FileReader(this.userFileName));
while (true) {
String s = inbuf.readLine();
if (s == null) {
break;
}
add(s);
}
inbuf.close();
System.out.println("ini-file READING OK");
} catch ( IOException ex ) {
System.out.println("ini-file FILE " + name + " reading exception: " + ex);
}
} else {
System.out.println("ini-file FILE " + name + " DOES NOT EXIST");
}
}
/**
* Call ReadSections to retrieve the names of all sections in the INI file into an ArrayList object.
*
* @return an ArrayList holding the sections
*
*/
public ArrayList<String> ReadSections() {
ArrayList<String> list = new ArrayList<String>();
String s;
for (int i=0; i < size(); i++) {
s = get(i).toString();
if (s.startsWith("[") && s.endsWith("]")) {
list.add(s.substring(1,(s.length()-1)));
}
}
return list;
}
/**
* Call UpdateFile to flush buffered reads from and writes to the INI file to disk.
*
* @return returns <code>true</code> if sucessful
*
*/
public boolean UpdateFile() {
try {
BufferedWriter outbuf = new BufferedWriter(new FileWriter(this.userFileName.toString(), false));
int i=0;
while (i<size()) {
String s = get(i).toString();
if (s == null) {
break;
}
outbuf.write(s);
outbuf.newLine();
i++;
}
outbuf.close();
return true;
} catch ( IOException ioe ) {
return false;
}
}
/**
* Call ReadString to read a string value from an INI file. Section identifies the
* section in the file that contains the desired key. key is the name of the key
* from which to retrieve the value. defaultValue is the string value to return if the:<br>
* - Section does not exist.<br>
* - Key does not exist.<br>
* - Data value for the key is not assigned.<br>
*
* @param Section the section name
* @param key the key name
* @param defaultValue default value if no value is found
*
* @return returns the value. If empty or nonexistent it will return the default value
*
*/
public String ReadString(String Section, String key, String defaultValue) {
String value=defaultValue;
if (ValuePosition(Section, key) > 0) {
int strLen = key.length()+1;
value = get(ValuePosition(Section, key)).toString().substring(strLen, get(ValuePosition(Section, key)).toString().length());
}
return value;
}
public String ReadStringRemapped(String Section, String key, String defaultValue, JIniFile remapFile) {
String value=defaultValue;
if (ValuePosition(Section, key) > 0) {
int strLen = key.length()+1;
String realValue = get(ValuePosition(Section, key)).toString().substring(strLen, get(ValuePosition(Section, key)).toString().length());
if ((realValue != null) && (realValue.length() > 0)) {
value=remapFile.ReadString(key, realValue, defaultValue);
}
}
return value;
}
/**
* Call ReadSectionValues to read the keys, and the values from all keys, within a specified
* section of an INI file into an ArrayList object. Section identifies the section in the file
* from which to read key values.
*
* @param Section the section name
*
* @return an ArrayList holding the values in the specified section.
*
*/
public ArrayList<String> ReadSectionValues(String Section) {
ArrayList<String> myList = new ArrayList<String>();
int start = this.SectionPosition(Section)+1;
String s;
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
s = get(i).toString().substring(get(i).toString().indexOf("=")+1, get(i).toString().length());
if (s.startsWith("[") && s.endsWith("]")) {
break;
} else {
myList.add(s);
}
}
}
return myList;
}
/**
* Call ReadSection to read the keys, and the values from all keys, within a specified
* section of an INI file into an Properties object. Section identifies the section in the file
* from which to read key-value pairs.
*
* @param Section the section name
*
* @return a Properties holding the key-value pairs in the specified section.
*
*/
public Properties ReadSection(String Section) {
Properties myList = new Properties();
int start = this.SectionPosition(Section)+1;
String line,key="",val="";
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
line = get(i).toString();
if (line.startsWith("[") && line.endsWith("]")) {
break;
}
else if((!line.equals(""))&&(line.indexOf("=")!=-1)){
val = line.substring(line.indexOf("=")+1, line.length());
key = line.substring(0,line.indexOf("="));
myList.setProperty(key,val);
}
}
}
return myList;
}
/**
* Call ReadSection to read the keys, and the values from all keys, within a specified
* section of an INI file into an Properties object. Section identifies the section in the file
* from which to read key-value pairs.
*
* @param Section the section name
*
* @return a ArrayList holding the key-value pairs in sequence key1,value1,key2,value2 etc.
*
*/
public ArrayList<String> ReadSectionAsArray(String Section) {
ArrayList<String> myList = new ArrayList<String>();
int start = this.SectionPosition(Section)+1;
String line,key="",val="";
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
line = get(i).toString();
if (line.startsWith("[") && line.endsWith("]")) {
break;
}
else if((!line.equals(""))&&(line.indexOf("=")!=-1)){
val = line.substring(line.indexOf("=")+1, line.length());
key = line.substring(0,line.indexOf("="));
myList.add(key);
myList.add(val);
}
}
}
return myList;
}
public String ReturnSectionAsString(String Section){
String line,res="";
int start = this.SectionPosition(Section)+1;
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
line = get(i).toString();
if (line.startsWith("[") && line.endsWith("]")) {
break;
}
else res=res+line;
}
}
return res;
}
/**
* Call ReadInteger to read a string value from an INI file. Section identifies the
* section in the file that contains the desired key. key is the name of the key
* from which to retrieve the value. defaultValue is the integer value to return if the:<br>
* - Section does not exist.<br>
* - Key does not exist.<br>
* - Data value for the key is not assigned.<br>
*
* @param Section the section name
* @param key the key name
* @param defaultValue default value if no value is found
*
* @return returns the value. If empty or nonexistent it will return the default value
*
*/
public int ReadInteger(String Section, String key, int defaultValue) {
int value=defaultValue;
if (ValuePosition(Section, key) > 0) {
int strLen = key.length()+1;
value = Integer.parseInt(get(ValuePosition(Section, key)).toString().substring(strLen, get(ValuePosition(Section, key)).toString().length()));
}
return value;
}
/**
* Call ReadFloat to read a string value from an INI file. Section identifies the
* section in the file that contains the desired key. key is the name of the key
* from which to retrieve the value. defaultValue is the float value to return if the:<br>
* - Section does not exist.<br>
* - Key does not exist.<br>
* - Data value for the key is not assigned.<br>
*
* @param Section the section name
* @param key the key name
* @param defaultValue default value if no value is found
*
* @return returns the value. If empty or nonexistent it will return the default value
*
*/
public Float ReadFloat(String Section, String key, Float defaultValue) {
Float value = new Float(0f);
value = defaultValue;
if (ValuePosition(Section, key) > 0) {
int strLen = key.length()+1;
value = Float.valueOf(get(ValuePosition(Section, key)).toString().substring(strLen, get(ValuePosition(Section, key)).toString().length()));
}
return value;
}
/**
* Call Readbool to read a string value from an INI file. Section identifies the
* section in the file that contains the desired key. key is the name of the key
* from which to retrieve the value. defaultValue is the boolean value to return if the:<br>
* - Section does not exist.<br>
* - Key does not exist.<br>
* - Data value for the key is not assigned.<br>
*
* @param Section the section name
* @param key the key name
* @param defaultValue default value if no value is found
*
* @return returns the value. If empty or nonexistent it will return the default value
*
*/
public boolean ReadBool(String Section, String key, boolean defaultValue) {
boolean value=defaultValue;
if (ValuePosition(Section, key) > 0) {
int strLen = key.length()+1;
value = Boolean.getBoolean(get(ValuePosition(Section, key)).toString().substring(strLen, get(ValuePosition(Section, key)).toString().length()));
}
return value;
}
/**
* SectionExists is used internally to determine the position of a section within the INI file
* specified in FileName.
* <p>
* Section is the INI file section SectionExists determines the position of.
* <p>
* SectionExists returns an Integer value that indicates the position of the section in question.
*
* @param Section the section name
*
* @return will return the position of the section. Returns -1 not found.
*
*/
private int SectionPosition(String Section) {
String s;
int pos = -1;
for (int i=0; i < size(); i++) {
s = get(i).toString();
if (s.equals("["+Section+"]")) {
pos = i;
break;
}
}
return pos;
}
/**
* Use SectionExists to determine whether a section exists within the INI file specified in FileName.
* <p>
* Section is the INI file section SectionExists determines the existence of.
* <p>
* SectionExists returns a Boolean value that indicates whether the section in question exists.
*
* @param Section the section name
*
* @return returns <code>true</code> if the section exists.
*
*/
public boolean SectionExist(String Section) {
String s;
boolean val = false;
for (int i=0; i < size(); i++) {
s = get(i).toString();
if (s.equals("["+Section+"]")) {
val = true;
break;
}
}
return val;
}
/**
* Call EraseSection to remove a section, all its keys, and their data values from
* an INI file. Section identifies the INI file section to remove.
*
* @param Section the section name
*
*/
public void EraseSection(String Section) {
String s;
int start = this.SectionPosition(Section)+1;
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
s = get(i).toString();
if (s.startsWith("[") && s.endsWith("]")) {
break;
} else {
remove(i);
i--;
}
}
remove(this.SectionPosition(Section));
}
}
/**
* Call ReadSection to retrieve the names of all keys within a specified section of an
* INI file into an ArrayList object.
*
* @param Section the section name
*
* @return an ArrayList holding all key names.
*
*/
public ArrayList<String> ReadSectionKeys(String Section) {
String s;
ArrayList<String> myList = new ArrayList<String>();
int start = this.SectionPosition(Section)+1;
if (this.SectionPosition(Section) > -1) {
for (int i=start; i < size(); i++) {
s = get(i).toString();
if (s.startsWith("[") && s.endsWith("]")) {
break;
}
else if(s.compareTo("")==0){
continue;
}
else {
s=s.substring(0, s.indexOf("="));
myList.add(s);
}
}
}
return myList;
}
/**
* Use ValueExist to determine whether a key exists in the INI file specified in FileName.<br>
* Section is the section in the INI file in which to search for the key.<br>
* key is the name of the key to search for.<br>
* ValueExist returns a Boolean value that indicates whether the key exists in the specified section.<br>
*
* @param Section the section name
* @param key the key name
*
* @return returns <code>true</code> if value exists
*
*/
public boolean ValueExist(String Section, String key) {
int start = SectionPosition(Section);
String s;
boolean val = false;
for (int i=start+1; i < size(); i++) {
s = get(i).toString();
if (s.startsWith(key+"=")) {
val = true;
break;
} else if (s.startsWith("[") && s.endsWith("]")) {
break;
}
}
return val;
}
/**
* ValuePosition is used internally to determine the position of a in the INI file specified in FileName.
* <P>
* Section is the section in the INI file in which to search for the key.
* <P>
* key is the name of the key to search for.
* <P>
* ValuePosition returns an Integer value that indicates the position of the key in the INI file.
*
* @param Section the section name
* @param key the key name
*
* @return returns the position of the Value. If not found it will return -1
*
*/
private int ValuePosition(String Section, String key) {
int start = SectionPosition(Section);
String s;
int pos =-1;
for (int i=start+1; i < size(); i++) {
s = get(i).toString();
if (s.startsWith(key+"=")) {
pos = i;
break;
} else if (s.startsWith("[") && s.endsWith("]")) {
break;
}
}
return pos;
}
/**
* Call DeleteKey to erase an INI file entry. Section is string containing the name
* of an INI file section, and key is a string containing the name of the key from
* for which to set a nil value.
* <p>
* <b>Note:</b> Attempting to delete a key in a nonexistent section or attempting to delete a
* nonexistent key are not errors. In these cases, DeleteKey does nothing.
*
* @param Section the section name
* @param key the key name
*
*/
public void DeleteKey(String Section, String key) {
if (this.ValuePosition(Section, key) > 0) {
remove(this.ValuePosition(Section, key));
}
}
/**
* Call WriteString to write a string value to an INI file. Section identifies the section in the
* file that contain the key to which to write. key is the name of the key for which to set a value.
* value is the string value to write.
* <p>
* <b>Note:</b> Attempting to write a data value to a nonexistent section or attempting to write data to a nonexistent
* key are not errors. In these cases, WriteString creates the section and key and sets its initial value
* to value.
*
* @param Section the section name
* @param key the key name
* @param value the value
*
*/
public void WriteString(String Section, String key, String value) {
String s = key+"="+value;
this.addToList(Section, key, s);
}
/**
* Call WriteBool to write a boolean value to an INI file. Section identifies the section in the
* file that contain the key to which to write. key is the name of the key for which to set a value.
* value is the boolean value to write.
* <p>
* <b>Note:</b> Attempting to write a data value to a nonexistent section or attempting to write data to a nonexistent
* key are not errors. In these cases, WriteBool creates the section and key and sets its initial value
* to value.
*
* @param Section the section name
* @param key the key name
* @param value the value
*
*/
public void WriteBool(String Section, String key, Boolean value) {
String s = key+"="+value.toString();
this.addToList(Section, key, s);
}
/**
* Call WriteFloat to write a float value to an INI file. Section identifies the section in the
* file that contain the key to which to write. key is the name of the key for which to set a value.
* value is the float value to write.
* <p>
* <b>Note:</b> Attempting to write a data value to a nonexistent section or attempting to write data to a nonexistent
* key are not errors. In these cases, WriteFloat creates the section and key and sets its initial value
* to value.
*
* @param Section the section name
* @param key the key name
* @param value the value
*
*/
public void WriteFloat(String Section, String key, float value) {
String s = key+"="+Float.toString(value);
this.addToList(Section, key, s);
}
/**
* Call WriteInteger to write an integer value to an INI file. Section identifies the section in the
* file that contain the key to which to write. key is the name of the key for which to set a value.
* value is the integer value to write.
* <p>
* <b>Note:</b> Attempting to write a data value to a nonexistent section or attempting to write data to a nonexistent
* key are not errors. In these cases, WriteInteger creates the section and key and sets its initial value
* to value.
*
* @param Section the section name
* @param key the key name
* @param value the value
*
*/
public void WriteInteger(String Section, String key, int value) {
String s = key+"="+Integer.toString(value);
this.addToList(Section, key, s);
}
/**
* addToList is used internally to add values to the INI file specified in FileName.
* <p>
* Section is the section in the INI file in which to search for the key.
* <p>
* key is the name of the key to search for.
* <p>
* value is the name of the value to write
* <p>
* <b>Note:</b> Attempting to write a data value to a nonexistent section or attempting to write data to a nonexistent
* key are not errors. In these cases, addToList creates the section and key and sets its initial value
* to value.
*
* @param Section the section name
* @param key the key name
* @param value the value
*
*/
@SuppressWarnings("unchecked")
private void addToList(String Section, String key, String value) {
if (this.SectionExist((Section))) {
if (this.ValueExist(Section, key)) {
int pos = this.ValuePosition(Section, key);
remove(pos);
add(pos, value);
} else {
add(/*(this.SectionPosition(Section)+1) l'ho tolto io!!!!*/value);
}
} else {
add("["+Section+"]");
add(value);
}
}
@SuppressWarnings("unchecked")
public void addSpace(){
add("");
}
}

View File

@@ -0,0 +1,39 @@
package it.valueteam.gnpsim.utility;
import java.util.Properties;
public class JndiUtility {
protected static Properties propJndi = SimConfFile.getInstance().ReadSection(
"JNDI");
protected static Properties propIbIn = SimConfFile.getInstance().ReadSection(
"InfobusIN");
private JndiUtility() {
}
/*
private static Context getServerContext() throws Exception {
Hashtable ht = new Hashtable();
Context ctx = null;
ht.put(Context.INITIAL_CONTEXT_FACTORY, propJndi.getProperty("java.naming.factory.initial"));
ht.put(Context.SECURITY_PRINCIPAL, propJndi.getProperty("java.naming.security.principal"));
ht.put(Context.SECURITY_CREDENTIALS, propJndi.getProperty("java.naming.security.credentials"));
ht.put(Context.PROVIDER_URL,propJndi.getProperty("java.naming.provider.url"));
ctx = new InitialContext(ht);
return ctx;
}
*/
}

View File

@@ -0,0 +1,30 @@
/*
* Created on Jan 25, 2005
*
*/
package it.valueteam.gnpsim.utility;
/**
* @author Giovanni
*
*/
public class SimConfFile {
/**
* Ritorna un'istanza della classe
* @return PropertiesDefault
*/
public static JIniFile _instance =null;
public static JIniFile getInstance() {
if (_instance == null) {
String filepath = System.getProperty("sim_conf_file","");
_instance = new JIniFile(filepath);
}
return _instance;
}
}

View File

@@ -0,0 +1,159 @@
package it.valueteam.gnpsim.utility;
import org.exolab.castor.xml.*;
import java.io.*;
import java.util.Hashtable;
/**
* <p>Title: MNP</p>
* <p>Description: Classe che gestisce il databinding con Castor, gestione thread safe</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: ValueTeam - TeleAp</p>
* @author Carlo Poccia
* @version 1.0
*/
public class XmlUtility {
private XmlUtility() {
}
/**
* Converte un Castor binded XML object ad una stringa XML
* @param castorObj Object
* @param validate boolean
* @throws Exception
* @return String
*/
public static String getXmlStringFromCastorXmlObject(Object castorObj, boolean validate) throws Exception {
String xml=null;
if (castorObj == null)
throw new IllegalArgumentException("Object to marshaller is null");
StringWriter writer = new StringWriter();
// Marshal
Marshaller marshaller = new Marshaller();
marshaller.setValidation(validate);
Marshaller.marshal(castorObj, writer);
writer.flush();
xml = writer.toString();
writer.close();
return xml;
}
/**
* Come getXmlStringFromCastotXmlObject senza validazione
* @param castorObj Object
* @throws Exception
* @return String
*/
public static String getXmlStringFromCastorXmlObject(Object castorObj) throws Exception {
return getXmlStringFromCastorXmlObject(castorObj,false);
}
/**
* Converte una stringa XML in un Castor binded XML object
* @param className Class
* @param xml String
* @param validate boolean
* @throws Exception
* @return Object
*/
public static Object getCastorXmlObjectFromXmlString(Class className, String xml, boolean validate) throws Exception {
Object castorObj = null;
if (xml == null)
throw new IllegalArgumentException("Null Xml string");
StringReader reader = new StringReader(xml);
// Unmarshaller
Unmarshaller unmarshaller = new Unmarshaller();
unmarshaller.setValidation(validate);
castorObj = Unmarshaller.unmarshal(className, reader);
reader.close();
return castorObj;
}
/**
* Converte una stringa XML in un Castor binded XML object
* @param className Class
* @param xml String
* @param validate boolean
* @throws Exception
* @return Object
*/
public static Object getCastorXmlObjectFromFileName(Class className, String fileName, boolean validate) throws Exception {
Object castorObj = null;
if (fileName == null)
throw new IllegalArgumentException("Null fileName string");
FileReader reader = new FileReader(fileName);
// Unmarshaller
Unmarshaller unmarshaller = new Unmarshaller();
unmarshaller.setValidation(validate);
castorObj = Unmarshaller.unmarshal(className, reader);
reader.close();
return castorObj;
}
/**
* Come getCastotXmlObjectFromXmlString ma senza validazione
* @param className Class
* @param xml String
* @throws Exception
* @return Object
*/
public static Object getCastorXmlObjectFromXmlString(Class className,String xml) throws Exception {
return getCastorXmlObjectFromXmlString(className, xml, false);
}
// ritorna la stringa corrispondente alla String s, secondo XML
public static String xmlString(String s)
{
Hashtable H=loadHtmlHT();
boolean inTag = false;
char openTag = '<';
char closeTag = '>';
//System.out.println("[functions.xmlString]\nFILE DI INGRESSO: "+s);
StringBuffer sb=new StringBuffer (s);
for(int i=0;i<sb.length();i++)
{
char c = sb.charAt(i);
if( c==openTag )
inTag = true;
Character chara = new Character(c);
if(!inTag && H.containsKey(chara))
{
sb.deleteCharAt(i);
String sost=(String)H.get(chara);
sb.insert( i,sost );
i+=(sost.length()-1);
}
if( inTag && c==closeTag )
inTag = false;
}
//System.out.println("[functions.xmlString]\nFILE DI USCITA: "+sb.toString());
return sb.toString();
}
@SuppressWarnings("unchecked")
private static Hashtable loadHtmlHT()
{
Hashtable h=new Hashtable();
h.put(new Character('&'),"&amp;" );
h.put(new Character('\''),"&apos;" );
h.put(new Character('\"'),"&quot;" );
return h;
}
}