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,782 @@
package it.valueteam.infotracciati;
import java.io.*;
import java.util.*;
import org.exolab.castor.xml.*;
import it.valueteam.gnp.dao.xml.infotracciati.*;
import it.valueteam.infotracciati.exception.*;
import it.valueteam.infotracciati.formatter.*;
import it.valueteam.infotracciati.object.*;
import it.valueteam.infotracciati.xao.*;
/**
* <p>Title: FlowMaker</p>
*
* <p>Description: Classe : per le generazione del record a partire da un bean
* per la formattazione di un bean a partire da un record di un tracciato.</p>
*
* <p></p>
*
* <p>Informazioni per la creazione del file xml di configurazione:</p>
*
* <p>Il tag FlowType contiene i seguenti attributi:</p>
*
* <p>flow - tipo di flusso del tracciato</p>
*
* <p>fieldsNum - numero di campi del tracciato</p>
*
* <p>separator - separatore dei campi del tracciato</p>
*
* <p>decorator</p>
*
* <p>recordsNum - numero di record del file</p>
*
* <p>recordLength - lunghezza del record</p>
*
* <p></p>
*
* <p>Il tag InfoFields contiene i seguenti attributi:</p>
*
* <p>position - posizione del campo all'inetrno del tracciato</p>
*
* <p>value - nome del campo del tracciato deve essere uguale al nome della
* proprietà del bean</p>
*
* <p>fieldLength - lunghezza del campo, da utilizzare se fill è true o per lunghezze fisse</p>
*
* <p>maxFieldLength - lunghezza massima del campo, da utilizzare se fill è
* false</p>
*
* <p>pattern - formattazione del campo</p>
*
* <p>patternType - tipo di pattern da eseguire</p>
*
* <p>fill - se true viene rimosso/inserito il fill altrimenti niente</p>
*
* <p>I possibili valori per il patternType sono : </p>
*
* <p>1 - per proprietà costanti che vengono convertite in stringhe tramite il
* metodo toString() - in questo caso il pattern deve indicare il valore che la
* stringa deve avere </p>
*
* <p>2 - per proprietà java.util.Date - in questo caso il pattern deve indicare
* la formattazione della data secondo lo stardard della classa
* java.text.SimpleDateFormat</p>
*
* <p>3 - per proprietà numeriche - in questo caso il pattern non viene valutato
* </p>
*
* <p>4 - per le proprietà che devono rispettare una espressione regolare - in
* questo caso il pattern deve indicare l'espressione regolare che deve essere
* controllata</p>
*
* <p>In fase di formattazione del bean a partire da un record del tracciato è
* possibile eliminare l'eventuale fill presente per il campo del tracciato In
* fase di creazione del record a partire dal bean è possibile inserire il fill
* per il raggiungimento della lunghezza del campo indicata nel file di
* configurazione. Nel tag InfoFill vengono inserite le informazioni per
* l'eventuale fill, i possibili valori per l'attributo fillPosition sono:</p>
*
* <p>DX - se il fill deve essere rimosso/inserito a destra </p>
*
* <p>SX - se il fill deve essere rimosso/inserito a sinistra </p>
*
* <p>Copyright: Copyright (c) una notte di fine agosto del 2007</p>
*
* <p>Company: CA & Co.</p>
*
* @author Carmelo Aprile
* @version 1.0
*/
public class FlowMaker {
/**
* PATTERN_TYPE_CONSTANT
* patternTpe per valori costanti
*/
private static final int PATTERN_TYPE_CONSTANT = 1;
/**
* PATTERN_TYPE_DATE
* patternType per le date
*/
private static final int PATTERN_TYPE_DATE = 2;
/**
* PATTERN_TYPE_NUMBER
* patternType per i tipi numerici
*/
private static final int PATTERN_TYPE_NUMBER = 3;
/**
* PATTERN_TYPE_REGEX
* patternType per le espressioni regolari
*/
private static final int PATTERN_TYPE_REGEX = 4;
/**
* FILL_DX
* fill presente a destra
*/
private static String FILL_DX = "DX";
/**
* FILL_SX
* fill presente a sinistra
*/
private static String FILL_SX = "SX";
private InfoTracciatiXAO xao;
private Map dynamicFieldsMap;
private Map fixedFieldsMapIn;
private Map fixedFieldsMapOut;
private int recordFieldNum;
/**
*
* @param fileName String - file xml che mappa il tracciato
* @param flusso String - tipo di flusso contenuto nel file xml
* @throws GenericException - sollevata nel caso si errore generico
* @throws MarshalException - sollevata nel caso si errore di marshaling del file xml che mappa il tracciato : fileName
* @throws IOException - sollevata nel caso di errore di lettura del file xml che mappa il tracciato : fileName
* @throws ValidationException - sollevavta nel caso di errore di validazione del file xml : fileName
* @throws BadFlowException - sollevata nel caso che il flusso non corrisponde a quello contenuto nel file xml
* @throws NotValidXMLException - sollevata nel caso in cui il valore di un campo required non è presenti
*/
public FlowMaker(String fileName, String flusso) throws GenericException,
NotValidXMLException, BadFlowException{
xao = new InfoTracciatiXAO(flusso, fileName);
dynamicFieldsMap = xao.getDynamicFieldsMap();
fixedFieldsMapIn = xao.getFixedFieldsMapIn();
fixedFieldsMapOut = xao.getFixedFieldsMapOut();
validatePositionFlowIn();
validatePositionFlowOut();
}
/**
* <p>Metodp per la formattazione di record in ingresso per tracciati flat</p>
*
* <p>Se validate = false allora le proprietà vengono convertita a String </p>
*
* <p>Se validate = true e il campo non rispetta il pattern o la lunghezza del
* campo allora la proprietà viene settato false all'interno dell'oggetto di
* ritorno</p>
*
* @param record String - il singolo record del tracciato
* @param validate boolean - true se si desidera che il bean rispetti i
* pattern indicati nel file xml
* @throws NotValidXMLException sollevata se una o più posizioni indicate nel
* file xml di configurazione sono uguali
* @throws BadRecordFormatException - sollevata se il record ha una lunghezza
* errata o se il numero di campi indicato nel file xml non è esatto
* @throws FillPositionException sollevata se la posizione del fill non è
* consentita
* @throws GenericException sollevata per errori generici
* @return InfoTracciatiFlowIn - Contiene la validità del record (IsValid),
* la proprietà che non rispetta la formattazione (isValid=false), una Map
* con key=nome della proprietà; value=valore formattato della proprietà
* nel rispetto dei pattern indicati nel file xml di configurazione del
* tracciato.
*/
public InfoTracciatiFlowIn generateFormattedFlowIn(String record,
boolean validate) throws BadRecordFormatException,
GenericException, NotValidXMLException {
// risultato del parser
Map fieldMap = new HashMap(); ;
boolean isValid = true;
Object property = null;
boolean propertyValid = false;
InfoFields infoFields = null;
InfoFieldsIn infoFieldsIn = null;
InfoTracciatiFlowIn infoRecordField = null;
int recordLength = xao.getRecordLegth();
int recordsFieldNum = xao.getFieldsNum();
if (recordLength != 0) {
if (record.length() != recordLength) {
throw new BadRecordFormatException("Lunghezza record errato : " +
record.length());
}
}
String[] recordFields = splitRecord(record, xao.getSeparator(), xao.getDecorator(), xao.getRecordFinalChar());
if (recordsFieldNum != 0) {
if (recordFields.length != recordsFieldNum) {
throw new BadRecordFormatException("Numero campi record errato : " +
recordFields.length);
}
}
FormattedProperty formattedProperty = new FormattedProperty();
for (int i = 1; i <= recordsFieldNum; i++) {
infoRecordField = new InfoTracciatiFlowIn();
Integer currPos = new Integer(i);
if (dynamicFieldsMap.containsKey(currPos)) {
infoFields = (InfoFields) dynamicFieldsMap.get(currPos);
if (validate) {
formattedProperty = checkField(recordFields[i - 1], infoFields);
if (!formattedProperty.isPropertyValid) {
isValid = false;
}
property = formattedProperty.formattedProperty;
propertyValid = formattedProperty.isPropertyValid;
}
else {
property = recordFields[i - 1];
propertyValid = true;
}
fieldMap.put(infoFields.getValue(), property);
if (!isValid) {
infoRecordField.setValid(false);
infoRecordField.setFieldsMap(fieldMap);
infoRecordField.setKoPropertyName(infoFields.getValue());
break;
}
}
else if (fixedFieldsMapIn.containsKey(currPos)) {
infoFieldsIn = (InfoFieldsIn) fixedFieldsMapIn.get(currPos);
if (validate) {
formattedProperty = checkFixedFieldIn(recordFields[i - 1],
infoFieldsIn.getValue());
if (!formattedProperty.isPropertyValid) {
isValid = false;
}
property = formattedProperty.formattedProperty;
propertyValid = formattedProperty.isPropertyValid;
}
else {
property = recordFields[i - 1];
propertyValid = true;
}
fieldMap.put(infoFieldsIn.getPropertyName(), property);
if (!isValid) {
infoRecordField.setValid(false);
infoRecordField.setFieldsMap(fieldMap);
infoRecordField.setKoPropertyName(infoFieldsIn.getPropertyName());
break;
}
}
else {
throw new BadRecordFormatException(
"Le posizioni indicate nel file xml sono errate");
}
} //chiusura for
infoRecordField.setValid(isValid);
infoRecordField.setFieldsMap(fieldMap);
return infoRecordField;
}
/**
* validatePosition
*/
private void validatePositionFlowIn() throws NotValidXMLException {
Iterator iter = dynamicFieldsMap.keySet().iterator();
while (iter.hasNext()) {
Integer position = (Integer) iter.next();
if (fixedFieldsMapIn.containsKey(position)) {
throw new NotValidXMLException("La posizione " + position +
"è contenuta sia tra i campi dinamici" +
" che tra i campi fissi");
}
}
}
/**
* checkPattern
*
* @param string String
* @param string1 String
* @param string2 String
* @return boolean
*/
private FormattedProperty checkPattern(String recordField, String pattern,
int patternType) throws
GenericException {
FormattedProperty formattedProperty = null;
if (!Formatter.isNull(pattern) || patternType == PATTERN_TYPE_NUMBER) {
switch (patternType) {
case PATTERN_TYPE_CONSTANT:
if (Formatter.checkConstantString(recordField, pattern)) {
formattedProperty = new FormattedProperty(recordField, true);
}
else {
formattedProperty = new FormattedProperty(recordField, false);
}
break;
case PATTERN_TYPE_DATE:
if (Formatter.checkDataisOk(recordField, pattern)) {
try {
formattedProperty = new FormattedProperty(Formatter.toDate(
recordField, pattern), true);
}
catch (Exception ex) {
ex.printStackTrace();
throw new GenericException(ex);
}
}
else {
formattedProperty = new FormattedProperty(recordField, false);
}
break;
case PATTERN_TYPE_NUMBER:
if (Formatter.verifica_Num(recordField)) {
formattedProperty = new FormattedProperty(new Long(recordField), true);
}
else {
formattedProperty = new FormattedProperty(recordField, false);
}
break;
case PATTERN_TYPE_REGEX:
if (Formatter.verificaPattern(recordField, pattern)) {
formattedProperty = new FormattedProperty(recordField, true);
}
else {
formattedProperty = new FormattedProperty(recordField, false);
}
break;
default:
formattedProperty = new FormattedProperty(recordField, false);
}
}
else {
formattedProperty = new FormattedProperty(recordField, true);
}
return formattedProperty;
}
private FormattedProperty checkField(String recordField, InfoFields info) throws
GenericException {
FormattedProperty formattedProperty = new FormattedProperty();
// se la lunghezza non corrisponde a quella indicata nell'xml di conf.
// o (per campi a lunghezza variabile) la lunghezza del campo è maggiore del massimo valore indicato nel xml
if ( !Formatter.checkFieldLength(recordField, info.getFieldLength())
|| (info.getMaxFieldLength()!=0 && recordField.length() > info.getMaxFieldLength())) {
formattedProperty = new FormattedProperty(recordField, false);
}
else if(!info.isMandatory() && Formatter.isNull(recordField)){
formattedProperty = new FormattedProperty(recordField,true);
}
else {
if (info.getFill()) {
recordField = removeFill(recordField, info);
}
formattedProperty = checkPattern(recordField, info.getPattern(),
info.getPatternType());
}
return formattedProperty;
}
/**
* <p>Metodo per la creazione di un record del tracciato </p>
*
* @param fieldsMapArgument Map - mappa contenente key = nome proprietà;
* value = valore proprietà;
* @param validate boolean - true se deve essere usata la formattazione
* indicata nel file xml.
* @throws NotValidXMLException - sollevata se una o più posizioni indicate
* nel file xml di configurazione sono uguali
* @throws BadFieldFormatException sollevata se il campo del bean non
* rispetta il pattern contenuto nel file xml
* @throws FillPositionException sollevata se la posizione del fill non è
* consentita possibili valori DX,SX
* @throws BadPositionException sollevata se la posizione indicata nel file
* xml per la proprietà è superire al numero dei campi del record indicata
* nel file xml stesso
* @return InfoTracciatiFlowOut - oggetto contenente il numero dei campi del
* tracciato; una mappa con key = posizione campoall'interno del record;
* value = valore formattato della proprietà inclusi separatore e decorator
*/
public String generateFormattedRecord(Map fieldsMapArgument,
boolean validate) throws BadFieldFormatException,
BadPositionException {
int fieldNum = xao.getFieldsNum();
this.recordFieldNum = fieldNum;
Integer currPos = null;
StringBuffer recordResult = new StringBuffer();
InfoFields infoFields;
InfoFieldsOut infoFieldsOut;
Object value = null;
String separator = xao.getSeparator();
String decorator = xao.getDecorator();
String recordFinalChar=xao.getRecordFinalChar();
//---------------------------------
if (fieldsMapArgument == null || fieldsMapArgument.size() == 0) {
throw new IllegalArgumentException(
"La mappa argomento non è valorizzata ");
}
String formattedProperty = new String();
for (int i = 1; i <= fieldNum; i++) {
currPos = new Integer(i);
if (dynamicFieldsMap.containsKey(currPos)) {
infoFields = (InfoFields) dynamicFieldsMap.get(currPos);
if (!fieldsMapArgument.containsKey(infoFields.getValue())) {
throw new IllegalArgumentException("La proprietà " +
infoFields.getValue() +
"non è presente nella mappa argomento del metodo");
}
value = fieldsMapArgument.get(infoFields.getValue());
//se il campo passato al'interno dell'hashMap è null, lo valorizzo a stringa vuota
if(value==null){
value="";
}
if (validate) {
formattedProperty = formatProperty(value, infoFields);
}
else {
formattedProperty = value.toString();
}
if (infoFields.getFill()) {
formattedProperty = addFill(formattedProperty, infoFields);
}
//se è l'ultimo campo inserisco il recordFinalChar attribute del xml
//in scrittura viene inserito il RecordFinalChar, da inserire nell'xml
// se il redord deve terminare con un particolare carattere altrimenti
//non c'è carattere finale
if(i==fieldNum){
formattedProperty = decorator + formattedProperty + decorator +
recordFinalChar;
}else{
formattedProperty = decorator + formattedProperty + decorator +
separator;
}
recordResult.append(formattedProperty);
}
else if (fixedFieldsMapOut.containsKey(currPos)) {
infoFieldsOut = (InfoFieldsOut) fixedFieldsMapOut.get(currPos);
value = infoFieldsOut.getValue();
if (value==null || value.toString().length()==0) {
value = new String();
}
//se è l'ultimo campo inserisco il recordFinalChar attribute del xml
//in scrittura viene inserito il RecordFinalChar, da inserire nell'xml
// se il redord deve terminare con un particolare carattere altrimenti
//non c'è carattere finale
if(i==fieldNum){
value = decorator + value + decorator +
recordFinalChar;
recordResult.append(value);
}else{
value = decorator + value + decorator + separator;
recordResult.append(value);
}
}
else {
throw new BadPositionException(
"Errore di configurazione per il campo in posizione:" + i);
}
}
//---------------------------------
return recordResult.toString();
}
/**
* validatePositionFlowOut
*/
private void validatePositionFlowOut() throws NotValidXMLException {
Iterator iter = dynamicFieldsMap.keySet().iterator();
while (iter.hasNext()) {
Integer position = (Integer) iter.next();
if (fixedFieldsMapOut.containsKey(position)) {
throw new NotValidXMLException("La posizione " + position +
"è contenuta sia tra i campi dinamici" +
" che tra i campi fissi");
}
}
}
/**
* formatProperty
*
* @param value String
* @param infoFields InfoFields
* @return FormattedProperty
*/
private String formatProperty(Object value, InfoFields infoFields) throws
BadFieldFormatException {
String formatProperty = null;
int patternType = infoFields.getPatternType();
if ((!Formatter.isNull(infoFields.getPattern()) ||
patternType == PATTERN_TYPE_NUMBER) && (infoFields.getMandatory() || !Formatter.isNull(value.toString()))) {
switch (patternType) {
case 1:
if (Formatter.checkConstantString( (String) value,
infoFields.getPattern())) {
formatProperty = (String) value;
}
else {
throw new BadFieldFormatException("Formato del campo errato : " +
infoFields.getValue());
}
break;
case 2:
String date = null;
if (Formatter.verificaData(value)) {
date = Formatter.dateToString( (Date) value,
infoFields.getPattern());
}
else {
throw new BadFieldFormatException("Il tipo del campo è errato : " +
infoFields.getValue());
}
if (Formatter.checkDataisOk(date, infoFields.getPattern())) {
formatProperty = date;
}
else {
throw new BadFieldFormatException("Formato del campo errato : " +
infoFields.getValue());
}
break;
case 3:
if (Formatter.verifica_Num(value.toString())) {
formatProperty = value.toString();
}
else {
throw new BadFieldFormatException("Formato del campo errato : " +
infoFields.getValue());
}
break;
case 4:
if (Formatter.verificaPattern(value.toString(), infoFields.getPattern())) {
formatProperty = value.toString();
}
else {
throw new BadFieldFormatException("Formato del campo errato : " +
infoFields.getValue());
}
break;
default:
throw new BadFieldFormatException("Tipo pattern non supportato : " +
patternType + " per la proprietà " +
infoFields.getValue());
}
}
else {
formatProperty = value.toString();
}
return formatProperty;
}
/**
* Hidden claas di utility
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
class FormattedProperty {
FormattedProperty() {
}
FormattedProperty(Object formattedProperty, boolean isPropertyValid) {
this.formattedProperty = formattedProperty;
this.isPropertyValid = isPropertyValid;
}
Object formattedProperty;
boolean isPropertyValid;
}
private String addFill(String field, InfoFields infoFields) {
InfoFill infoFill = infoFields.getInfoFill();
String fillPosition = infoFill.getFillPosition();
String fillValue = infoFill.getFillValue();
String result = field;
StringBuffer fill = new StringBuffer();
if (field.length() < infoFields.getFieldLength()) {
int fillToAdd = infoFields.getFieldLength() - field.length();
for (int i = 0; i < fillToAdd; i++) {
fill.append(fillValue);
}
if (fillPosition.equalsIgnoreCase(FILL_DX)) {
result = result + fill.toString();
}
else if (fillPosition.equalsIgnoreCase(FILL_SX)) {
result = fill.toString() + result;
}
}
return result;
}
private String removeFill(String field, InfoFields infoFields) {
InfoFill infoFill = infoFields.getInfoFill();
// String fillPosition = infoFill.getFillPosition();
//
// String result = null;
//
// int fillToRemove = field.length() - infoFields.getFieldLength();
//
// if (fillPosition.equalsIgnoreCase(FILL_DX)) {
// result = field.substring(0, field.length() - fillToRemove);
// }
// else if (fillPosition.equalsIgnoreCase(FILL_SX)) {
// result = field.substring(fillToRemove, field.length());
// }
String result = field.replaceAll("["+infoFill.getFillValue()+"]","");
return result;
}
private FormattedProperty checkFixedFieldIn(String propertyValue,
String propertyName) {
if (Formatter.checkConstantString(propertyValue, propertyName)) {
return new FormattedProperty(propertyValue, true);
}
else {
return new FormattedProperty(propertyValue, false);
}
}
public int getRecordFieldNum() throws IllegalOperationException {
if (this.recordFieldNum > 0) {
return this.recordFieldNum;
}
else {
throw new IllegalOperationException(
"Operazione non consentita per la formattazione" +
"del flusso in ingresso");
}
}
private String[] splitRecord(String record, String separator, String decorator, String recordFinalChar) throws
NotValidXMLException {
String[] result = null;
if(!Formatter.isNull(decorator)){
record=record.replaceAll("["+decorator+"]","");
}
if (!Formatter.isNull(separator)) {
result = getField(record, separator, recordFinalChar);
}
else {
int numRecordFields = xao.getFieldsNum();
int recordL = xao.getRecordLegth();
result = new String[numRecordFields];
Map infoFieldsMap = xao.getInfoFieldsMap();
int currPos = 0;
if (infoFieldsMap.size() != numRecordFields) {
throw new NotValidXMLException("Campi mancanti nei DynamicField!");
}
for (int i = 1; i <= numRecordFields; i++) {
Integer fieldPosition = new Integer(i);
if (infoFieldsMap.containsKey(fieldPosition)) {
int fieldL = ( (Long) infoFieldsMap.get(fieldPosition)).intValue();
if (currPos + fieldL > recordL)
throw new NotValidXMLException("La somma della lunghezza dei campi supera "+
"la lunghezza complessiva del tracciato!");
if (fieldL == 0)
throw new NotValidXMLException("Esistono uno o più lunghezze di campi non "+
"valorizzate. La Lunghezza dei campi è obbligatoria "+
"per tracciati senza separatore");
result[i - 1] = record.substring(currPos, currPos + fieldL);
currPos = currPos + fieldL;
}
}
}
return result;
}
/**
* Se il carattere finale (recordFinalChar)e il separatore coincidono
* viene eseguito il tokenizer in maniera giusta e IF1 e IF2 non vengono eseguiti
*
* Se l'ultimo campo del record non ha carattere finale
* allora viene eseguito IF1 che prende i restanti caratteri del record
* dopo l'ultimo separatore escluso
*
* Se il carattere finale è diverso dal separatore vengono presi i restanti caratteri
* dall'ultimo separatore al carattere finale esclusi
*
* @param record String
* @param separator String
* @param recordFinalChar String
* @return String[]
*/
private String[] getField(String record, String separator, String recordFinalChar){
String[] result=null;
record = record.replaceAll("["+separator+"]", " "+separator);
List token = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(record, separator);
while(tokenizer.hasMoreTokens()){
String tok = tokenizer.nextToken();
token.add(tok.subSequence(0,tok.length()-1));
}
//IF1
if(Formatter.isNull(recordFinalChar)){
int lastIndexSeparator=record.lastIndexOf(separator);
token.add(record.substring(lastIndexSeparator+1,record.length()));
}else //IF2
if(!recordFinalChar.equals(separator)){
int lastIndexSeparator=record.lastIndexOf(separator);
int indexOfRecordFinalChar=record.indexOf(recordFinalChar);
token.add(record.substring(lastIndexSeparator+1,indexOfRecordFinalChar));
}
result = new String[token.size()];
result = (String[])token.toArray(result);
return result;
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class BadFieldFormatException extends Exception{
public BadFieldFormatException() {
}
public BadFieldFormatException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class BadFlowException extends Exception{
public BadFlowException() {
}
public BadFlowException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class BadPositionException extends Exception{
public BadPositionException() {
}
public BadPositionException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class BadRecordFormatException extends Exception{
public BadRecordFormatException() {
}
public BadRecordFormatException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class FillPositionException extends Exception {
public FillPositionException() {
}
public FillPositionException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,16 @@
package it.valueteam.infotracciati.exception;
public class GenericException extends Exception{
public GenericException() {
}
public GenericException(String p0) {
super(p0);
}
public GenericException(Exception p0) {
super(p0);
}
}

View File

@@ -0,0 +1,11 @@
package it.valueteam.infotracciati.exception;
public class IllegalOperationException extends Exception{
public IllegalOperationException() {
}
public IllegalOperationException(String p0) {
super(p0);
}
}

View File

@@ -0,0 +1,16 @@
package it.valueteam.infotracciati.exception;
public class NotValidXMLException extends Exception{
public NotValidXMLException() {
}
public NotValidXMLException(String p0) {
super(p0);
}
public NotValidXMLException(Throwable p0) {
super(p0);
}
}

View File

@@ -0,0 +1,354 @@
package it.valueteam.infotracciati.formatter;
/**
* <p>Title: GNP</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author
* @version 1.0
*/
//import mnp
//import java
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.*;
import it.valueteam.infotracciati.utility.*;
public class Formatter {
private static String DEFAULT_DATE_PATTERN = "ddMMyyyy";
private static String DATE_CLASS = "java.util.Date";
private static String STRING_CLASS = "java.util.Date";
private Formatter() {
}
/**
* Individua la presenza di caratteri non desiderati da XML
* richiamata dalle sottoclassi di Bit e Sid
* @param inStr stringa su cui effettuare il controllo
* @return 'OK' se la stringa è valida, il carattere che da problemi altrimenti
*
* */
protected static String isValidXMLData(String inStr) {
// Creo il set con i caratteri da controllare
HashSet set = new HashSet();
set.add("<");
set.add(">");
// Se trovo uno dei caratteri speciali: scarto la stringa
for (int i = 0; i < inStr.length(); i++) {
String s = String.valueOf(inStr.charAt(i));
if (set.contains(s))return s;
}
return "OK";
}
/**
* Torna true se la stringa passata come argomento è null (BIT,SID,MSP,MSC)
* @param cod
* @return boolean
*/
public static boolean isNull(String cod) {
if ( (cod == null) || (cod.trim().length() == 0))
return true;
return false;
}
/**
* Alessia :
* Metodo che controlla la validità formale della data.
* AAAA-MM-GG
* return: true -> data formalmente valida
* false -> data errata.
*/
protected boolean checkDataisOk(String sData) {
int anno;
int mese;
int giorno;
java.util.Date app_data;
// carlo nuova gestione yyyy-MM-dd
try {
app_data = DateUtils.stringToDate(sData);
}
catch (Exception e) {
return false;
}
return true;
}
/**
* Alessia :
* Metodo che controlla la validità formale della data.
* AAAA-MM-GG
* return: true -> data formalmente valida
* false -> data errata.
*/
public static boolean checkDataisOk(String sData, String format) {
int anno;
int mese;
int giorno;
java.util.Date app_data;
// carlo nuova gestione yyyy-MM-dd
try {
app_data = DateUtils.toDate(sData, format);
}
catch (Exception e) {
return false;
}
return true;
}
/**
* Controlla se il carattere car è presente nella stringa s
*/
protected boolean is_in(String s, String car) {
boolean isin = false;
int i = 0;
while (i < s.length() && !isin) {
String c = String.valueOf(s.charAt(i));
isin = c.equals(car);
i++;
}
return isin;
}
/**
* Ritorna una sottostringa di lunghezza massima len
* @param val
* @param len
* @return
*/
protected String truncString(String val, int len) {
if (val == null)
return "";
if (val.length() <= len)
return val;
else
return val.substring(0, len);
}
/**
* C.M
* Verifica che la stringa passata sia un numero (senza cifre decimali, i.e. senza '.')
* @param numero
* @return boolean
*/
public static boolean verifica_Num(String num) {
try {
Long.parseLong(num);
}
catch (Exception e) {
return false;
}
return true;
}
public static boolean setProperty(Object bean, String name,Object value, boolean isValid, boolean validate) throws
IllegalArgumentException {
boolean result=true;
try{
Method[] methods = bean.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if ( (methodName.substring(3, methodName.length())).equalsIgnoreCase(
name)
&& methodName.startsWith("set")) {
Object[] values = new Object[1];
if (!isValid && validate &&
!getTypeParameterOfSetterMethod(methods[i]).equals(STRING_CLASS))
value = null;
if ( (getTypeParameterOfSetterMethod(methods[i]).equals(DATE_CLASS)) &&
!validate) {
try {
value = DateUtils.toDate( (String) value, DEFAULT_DATE_PATTERN);
}
catch (Exception ex) {
ex.printStackTrace();
result = false;
value = null;
}
}
values[0] = value;
methods[i].invoke(bean, values);
break;
}
}
}catch(Exception ex){
throw new IllegalArgumentException(ex.getMessage());
}
return result;
}
/**
* ritorna la stessa stringa ma lunga "lunghezza"
* @param nome String
* @param lunghezza int
* @param carattereRiempimento char carattere con cui riempire il fill
* @throws Exception
* @return String
*/
protected String fill(String nome, int lunghezza, char carattereRiempimento) throws
Exception {
String ret = "";
char cAppo[] = new char[lunghezza];
String sAppo = "";
if (nome == null) {
for (int i = 0; i < lunghezza; i++) cAppo[i] = ' ';
return new String(cAppo);
}
if (nome.length() < lunghezza) {
for (int i = 0; i < lunghezza; i++) {
if (i < nome.length()) cAppo[i] = nome.charAt(i);
else cAppo[i] = ' ';
//System.out.println("el:"+cAppo[i]);
}
ret = new String(cAppo);
}
else if (nome.length() == lunghezza) {
ret = nome;
}
else {
ret = nome.substring(0, lunghezza);
}
return ret;
}
public static boolean checkFieldLength(String field, int length){
if(length==0)
return true;
if(field.length()==length)
return true;
else return false;
}
/**
* checkConstantString
*/
public static boolean checkConstantString(String string,String pattern) {
return string.equalsIgnoreCase(pattern);
}
/**
* getProperty
*
* @param bean Object
* @param string String
* @return String
*/
public static Object getProperty(Object bean, String propertyName) throws
IllegalArgumentException {
Object result = null;
try{
Method[] methods = bean.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if ( (methodName.substring(3, methodName.length())).equalsIgnoreCase(
propertyName)
&& methodName.startsWith("get")) {
Object[] values = null;
result = methods[i].invoke(bean, values);
break;
}
}
}catch(Exception ex){
throw new IllegalArgumentException(ex.getMessage());
}
return result;
}
/**
* toDate
*
* @param recordField String
* @param pattern String
* @return Object
*/
public static Object toDate(String recordField, String pattern) throws
Exception {
return DateUtils.toDate(recordField,pattern);
}
public static Object toString(String recordField, String pattern) throws
Exception {
return DateUtils.toDate(recordField,pattern);
}
/**
* toString
*
* @param value Date
* @param string String
* @return String
*/
public static String dateToString(Date value, String string) {
return DateUtils.toString(value,string);
}
private static String getTypeParameterOfSetterMethod(Method method){
String result = method.getParameterTypes()[0].getName();
return result;
}
/**
* verificaPattern
*
* @param recordField String
* @param pattern String
* @return boolean
*/
public static boolean verificaPattern(String recordField, String pattern) {
Pattern patt = Pattern.compile(pattern);
Matcher match = patt.matcher(recordField);
return match.matches();
}
/**
* verificaData
*
* @param value Object
* @return boolean
*/
public static boolean verificaData(Object value) {
try{
Date date = (Date)value;
}catch(Throwable th){
return false;
}
return true;
}
}

View File

@@ -0,0 +1,36 @@
package it.valueteam.infotracciati.object;
import java.util.*;
public class InfoTracciatiFlowIn {
private boolean isValid;
private Map fieldsMap;
private String koPropertyName;
public InfoTracciatiFlowIn() {
fieldsMap = new HashMap();
}
public boolean isValid() {
return isValid;
}
public String getKoPropertyName() {
return koPropertyName;
}
public void setValid(boolean isValid) {
this.isValid = isValid;
}
public void setKoPropertyName(String koPropertyName) {
this.koPropertyName = koPropertyName;
}
public Map getFieldsMap() {
return fieldsMap;
}
public void setFieldsMap(Map fieldsMap) {
this.fieldsMap = fieldsMap;
}
}

View File

@@ -0,0 +1,706 @@
package it.valueteam.infotracciati.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;
}
}
/**
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();
}
/**
*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());
}
}

View File

@@ -0,0 +1,256 @@
package it.valueteam.infotracciati.utility;
/**
* Title: MNP Project
* Description: Mobile Number Portability
* Copyright: Copyright (c) 2002
* Company: ObjectWay spa
* @author Gian Luca Paloni
* @version 1.0
*/
import it.valueteam.logging.Tracer;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
/**
* Funzioni di pubblica utilità
* */
public class Func {
/**
* Raddoppia gli apici presenti nella stringa
* @param str Stringa da analizzare
* @return Stringa con apici raddoppiati
* */
public static String raddoppiaApici(String str) {
if (str == null) {
return null;
}
int insert = 0;
StringBuffer appo = new StringBuffer(str);
for (int i = 0; i < str.length(); i++, insert++) {
String c = String.valueOf(str.charAt(i));
if (c.equals("'")) {
appo.insert(insert++, "'");
}
}
return appo.toString();
}
/**
* serve quando si fanno le insert, per evitare che si inseriscano quei noiosissimi "null" nei campi
* invece di niente
* */
public static String noNull(String valore) {
if (valore != null) {
return valore;
} else {
return "";
}
}
/**
* Prende in input un Object di cui stampa il valore di tutti i campi concatenandoli in una stringa
* @param o
* @return
*/
public static String getFieldDescription(Object o) {
String desc = "";
int j = 0;
Method[] methods = null;
if (o == null) {
return null;
}
methods = o.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
String name = method.getName();
String value = null;
Object obj = null;
String inizio = "";
try {
if (name.startsWith("get")
&& !name.equalsIgnoreCase("getClass")) {
obj = method.invoke(o, null);
if (obj != null) {
value = obj.toString();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (value != null) {
if (j == 0) {
inizio = " [";
} else {
inizio = ", ";
}
desc += (inizio + name.substring(3) + " = " + value);
j++;
}
if (i == (methods.length - 1)) {
desc = desc + "]";
}
}
return desc;
}
//ritorna la stessa stringa ma lunga "lunghezza"
public static String fill(String nome, int lunghezza) {
String ret = "";
char cAppo[] = new char[lunghezza];
String sAppo = "";
if (nome == null) {
for (int i = 0; i < lunghezza; i++) {
cAppo[i] = ' ';
}
return new String(cAppo);
}
if (nome.length() < lunghezza) {
for (int i = 0; i < lunghezza; i++) {
if (i < nome.length()) {
cAppo[i] = nome.charAt(i);
} else {
cAppo[i] = ' ';
}
}
ret = new String(cAppo);
} else if (nome.length() == lunghezza) {
ret = nome;
} else {
ret = nome.substring(0, lunghezza);
}
return ret;
}
/**
* Eliminana dalla stringa la prima occorrenza della stringa codice_olo
* @param campo Stringa da modificare
* @param codice_olo Stringa da eliminare
* @return
* @throws Exception
*/
public static String stripCodiceOLO(String campo, String codice_olo) throws
Exception {
int pos = (campo == null ? -2 : campo.indexOf(codice_olo));
if (pos == -1) {
return campo; // Il codice OLO non è presente nella stringa
}
if (pos == -2) {
return ""; // Evito di tornare NULL
}
if (pos == 0) {
return campo.substring(pos + 1);
} else {
return campo.substring(0, pos) + campo.substring(pos + 1);
}
}
/**
* Aggiunge alla stringa il codice_olo
* @param campo Stringa da modificare
* @param codice_olo Stringa da aggiungere
* @return
* @throws Exception
*/
public static String addCodiceOLO(String campo, String codice_olo) throws
Exception {
String valore = (campo == null ? "" : campo);
// verifico se è già stato aggiunto
int pos = valore.indexOf(codice_olo);
if (pos != -1) {
return valore;
}
return valore + codice_olo;
}
/**
* Torna true se la stringa passata come argomento è null
* @param cod
* @return boolean
*/
public static boolean isNull(String cod) {
if ((cod == null) || (cod.trim().length() == 0)) {
return true;
}
return false;
}
/**
* getNull - Ritorna null se valore è un stringa vuota oppure null, altrimenti ritorna valore
*
* @param valore String
* @return String
*/
public static String getNull(String valore) {
if ((valore == null) || ("".equals(valore))) {
return null;
} else {
return valore;
}
}
public void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
/**
* Ritorna i fields di un oggetto
* @param o
* @return
*/
public static Map getInfoProperty(Object o) {
Field[] fields = null;
Map result = new HashMap();
if (o == null) {
return null;
}
fields = o.getClass().getFields();
for(int i = 0; i<fields.length; i++){
result.put(fields[i].getName(),fields[i].getType());
}
return result;
}
}

View File

@@ -0,0 +1,158 @@
package it.valueteam.infotracciati.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();
}
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;
}
}

View File

@@ -0,0 +1,226 @@
package it.valueteam.infotracciati.xao;
import java.io.*;
import java.util.*;
import org.exolab.castor.xml.*;
import it.valueteam.gnp.dao.xml.infotracciati.*;
import it.valueteam.infotracciati.exception.*;
import it.valueteam.infotracciati.utility.*;
public class InfoTracciatiXAO {
private Map dynamicFieldsMap;
private Map fixedFieldsMapIn;
private Map fixedFieldsMapOut;
private int fieldsNum;
private int recordLength;
private String separator;
private String decorator;
private String recordFinalChar;
private Map infoFieldMap;
/**
* Costruttore
*
* @param flowName nome del flusso da caricare
* @param fileName nome del file xml dal quale caricare il flusso
* @throws Exception
*/
public InfoTracciatiXAO(String flowName, String fileName) throws
NotValidXMLException, BadFlowException, GenericException {
try {
dynamicFieldsMap = new HashMap();
fixedFieldsMapIn = new HashMap();
fixedFieldsMapOut = new HashMap();
infoFieldMap = new HashMap();
SystemFlows systemFlows = (SystemFlows) XmlUtility.getCastorXmlObjectFromFileName(SystemFlows.class,fileName,false);
if(!systemFlows.isValid()){
NotValidXMLException ex = new NotValidXMLException("Il file "+ fileName + " non <20> valido");
ex.printStackTrace();
throw ex;
}
FlowType flowType = getFlowType(systemFlows,flowName);
if (flowType!=null) {
this.fieldsNum = flowType.getFieldsNum();
this.separator = flowType.getSeparator();
this.recordLength= flowType.getRecordLength();
this.decorator= flowType.getDecorator();
// this.recordFinalChar=flowType.getRecordFinalChar();
ListFields listFields = flowType.getListFields();
mappingDynamicFields(listFields.getDynamicFields());
mappingFixedFieldsIn(listFields.getFixedFields());
mappingFixedFieldsOut(listFields.getFixedFields());
}
else {
throw new BadFlowException("Il tipo di flusso non presente nel file di configurazione: " + fileName);
}
}
catch (IOException ex) {
System.out.println(
"Errore in lettura del file XML relativo al tracciato verso Pitagora");
throw new GenericException(ex);
}
catch (ValidationException ex) {
System.out.println("Errore di validazione");
throw new NotValidXMLException(ex);
}
catch (MarshalException ex) {
System.out.println("Errore marshall");
throw new NotValidXMLException(ex);
}
catch (Exception ex) {
System.out.println("Errore generico");
throw new GenericException("Errore generico");
}
}
/**
* getFlowType
*
* @param systemFlows SystemFlows
* @param flowName String
* @return FlowType
*/
private FlowType getFlowType(SystemFlows systemFlows, String flowName) {
SystemFlowsItem[] item = systemFlows.getSystemFlowsItem();
FlowType flow = null;
for(int i=0; i<item.length; i++){
flow = item[i].getFlowType();
if(flow.getFlow().equals(flowName)){
break;
}
else
flow = null;
}
return flow;
}
/**
* mappingDynamicFields
*
* @param dynamicFields DynamicFields
*/
private void mappingDynamicFields(DynamicFields dynamicFields) throws
NotValidXMLException {
DynamicFieldsItem[] dynaFields = dynamicFields.getDynamicFieldsItem();
InfoFields info = null;
if (dynaFields != null) {
for (int i = 0; i < dynaFields.length; i++) {
info = dynaFields[i].getInfoFields();
Integer key = new Integer(info.getPosition());
if(dynamicFieldsMap.containsKey(key))
throw new NotValidXMLException("Esistono posizioni uguali indicate all'interno dei campi dinamici");
dynamicFieldsMap.put(key, info);
infoFieldMap.put(key, new Long(info.getFieldLength()));
}
}
}
private void mappingFixedFieldsIn(FixedFields fixedFields) throws
NotValidXMLException {
Iterator iterSequence = fixedFields.iterateFixedFieldsSequence();
while(iterSequence.hasNext()){
FixedFieldsSequence sequence = (FixedFieldsSequence) iterSequence.next();
if (sequence != null) {
FixedFieldsSequenceItem[] sequenceItem = sequence.
getFixedFieldsSequenceItem();
for (int i = 0; i < sequenceItem.length; i++) {
InfoFieldsIn fin = sequenceItem[i].getInfoFieldsIn();
Integer key = new Integer(fin.getPosition());
if(fixedFieldsMapIn.containsKey(key))
throw new NotValidXMLException("Esistono posizioni uguali indicate all'interno dei campi fissi in ingresso");
fixedFieldsMapIn.put(key, fin);
infoFieldMap.put(key, new Long(fin.getValue().length()));
}
}
}
}
private void mappingFixedFieldsOut(FixedFields fixedFields) throws
NotValidXMLException {
Iterator iterSequence = fixedFields.iterateFixedFieldsSequence2();
while(iterSequence.hasNext()){
FixedFieldsSequence2 sequence = (FixedFieldsSequence2) iterSequence.next();
if (sequence != null) {
FixedFieldsSequence2Item[] sequenceItem = sequence.getFixedFieldsSequence2Item();
for (int i = 0; i < sequenceItem.length; i++) {
InfoFieldsOut fout = sequenceItem[i].getInfoFieldsOut();
Integer key = new Integer(fout.getPosition());
if(fixedFieldsMapOut.containsKey(key))
throw new NotValidXMLException("Esistono posizioni uguali indicate all'interno dei campi fissi in uscita");
fixedFieldsMapOut.put(key, fout);
}
}
}
}
/**
* Ritorna la mappa dei campi dinamici del tracciato in modalit<69> read-only
*
* @return Map
*/
public Map getDynamicFieldsMap() {
return Collections.unmodifiableMap(dynamicFieldsMap);
}
/**
* Ritorna la mappa dei campi dinamici del tracciato in modalit<69> read-only
*
* @return Map
*/
public Map getFixedFieldsMapIn() {
return Collections.unmodifiableMap(fixedFieldsMapIn);
}
public Map getFixedFieldsMapOut() {
return Collections.unmodifiableMap(fixedFieldsMapOut);
}
public int getFieldsNum() {
return fieldsNum;
}
public String getSeparator() {
return separator;
}
public int getRecordLegth() {
return this.recordLength;
}
public String getRecordFinalChar(){
if(this.recordFinalChar==null)
this.recordFinalChar="";
return this.recordFinalChar;
}
/**
* getDecorator
*
* @return String
*/
public String getDecorator() {
if(decorator ==null)
this.decorator="";
return this.decorator;
}
public Map getInfoFieldsMap(){
return Collections.unmodifiableMap(infoFieldMap);
}
}

View File

@@ -0,0 +1,21 @@
<<<<<<< version.properties
version 1.1 191007
version 1.2 221007
cambiata libreria castor - inserito nuovo attributo recordFinalChar
modificato controllo riga 374 sulla lunghezza del campo
modificato metodo removeFill in lettura
modificato il metodo getField in lettura (vedi javadoc)
########################################################
version 1.3 180508
non faceva l'append dell'ultimo campo :
if(i==fieldNum){
value = decorator + value + decorator +
recordFinalChar;
recordResult.append(value); MANCAVA QUESTA RIGA
}else{
value = decorator + value + decorator + separator;
recordResult.append(value);
}
########################################################