first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit 4d332ef662
27586 changed files with 3281783 additions and 0 deletions

View file

@ -0,0 +1,158 @@
package com.ablia.util;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;
public class AbMessages {
private static Hashtable propertyResources;
public static final String ERROR = "ERROR";
public static final String LOG_ERROR = "LOG_ERROR";
public static final String WARNING = "WARNING";
public static final String YES = "YES";
public static final String NO = "NO";
public static final String CANCEL = "CANCEL";
public static final String ATTENTION = "ATTENTION";
public static final String OK = "OK";
public static final String READ_OK = "READ_OK";
public static final String NO_RECORDS_FOUND = "NO_RECORDS_FOUND";
public static final String SAVE_OK = "SAVE_OK";
public static final String SEARCH_OK = "SEARCH_OK";
public static final String DELETE_OK = "DELETE_OK";
public static final String READ_FAIL = "READ_FAIL";
public static final String SAVE_FAIL = "SAVE_FAIL";
public static final String DELETE_FAIL = "DELETE_FAIL";
public static final String CONFIRM_DELETE = "CONFIRM_DELETE";
public static final String CONFIRM_SAVE = "CONFIRM_SAVE";
public static final String CART_SUBMIT_EMPTY = "CART_SUBMIT_EMPTY";
public static final String ALREADY_SAVED = "ALREADY_SAVED";
public static final String CART_NEED_LOGIN = "CART_NEED_LOGIN";
public static final String REFRESH_BEAN_FAILED = "REFRESH_BEAN_FAILED";
public static final String UNCHANGED_DATA = "UNCHANGED_DATA";
public static final String NEW = "NEW";
public static final String NEED_FIELDS = "NEED_FIELDS";
public static final String NO_ROW_SELECTED = "NO_ROW_SELECTED";
public static final String RECORD_LOCKED = "RECORD_LOCKED";
public static final String READ_LOCKED = "READ_LOCKED";
public static final String DUPLICATE_KEY = "DUPLICATE_KEY";
public static final String REF_INTEGRITY_FAIL = "REF_INTEGRITY_FAIL";
public static final String SEL_MAX_FAIL = "SEL_MAX_FAIL";
public static final String SEL_SUM_FAIL = "SEL_SUM_FAIL";
public static final String LOGIN_OK = "LOGIN_OK";
public static final String LOGIN_FAIL = "LOGIN_FAIL";
public static final String LOGIN_FIRST_ACCESS = "LOGIN_FIRST_ACCESS";
public static final String CONTROL_CODE_OK = "CONTROL_CODE_OK";
public static final String CONTROL_CODE_FAIL = "CONTROL_CODE_FAIL";
public static final String BM_ITEM_ADDED = "BM_ITEM_ADDED";
public static final String BM_ITEM_PRESENT = "BM_ITEM_PRESENT";
public static final String BM_ITEM_DELETED = "BM_ITEM_DELETED";
public static final String BM_ITEM_NOT_PRESENT = "BM_ITEM_NOT_PRESENT";
public static final String MR_FILE_ERROR = "MR_FILE_ERROR";
public static final String MR_FILE_LENGTH_ERROR = "MR_FILE_LENGTH_ERROR";
public static final String GRANT_NO_RW = "GRANT_NO_RW";
public static final String GRANT_NO_RWD = "GRANT_NO_RWD";
public static final String GRANT_NO_RM = "GRANT_NO_RM";
public static final String GRANT_NO_R = "GRANT_NO_R";
public static final String UPDATE_0 = "UPDATE_0";
public static final String PK_NULL_ERROR = "PK_NULL_ERROR";
public static final String LOGIN_SESSION_CLOSED = "LOGIN_SESSION_CLOSED";
protected static String getFileName() {
return "messages";
}
public static String getMessage(String key) {
return getMessage(Locale.getDefault(), key);
}
public static String getMessage(Locale locale, String key) {
try {
String prKey = locale.getLanguage();
if (getPropertyResources().containsKey(prKey))
return new String(((ResourceBundle)getPropertyResources().get(prKey)).getString(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
ResourceBundle pr = ResourceBundle.getBundle(getFileName(), locale);
getPropertyResources().put(prKey, pr);
return new String(pr.getString(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
} catch (Exception e) {
return "";
}
}
public static String getMessage(String s_locale, String key) {
try {
Locale locale = new Locale(s_locale);
String prKey = locale.getLanguage();
if (getPropertyResources().containsKey(prKey))
return ((ResourceBundle)getPropertyResources().get(prKey)).getString(key);
ResourceBundle pr = ResourceBundle.getBundle(getFileName(), locale);
getPropertyResources().put(prKey, pr);
return pr.getString(key);
} catch (Exception e) {
return "";
}
}
public static Hashtable getPropertyResources() {
if (propertyResources == null)
propertyResources = new Hashtable();
return propertyResources;
}
public static void resetMessages() {
if (propertyResources != null) {
propertyResources.clear();
propertyResources = null;
}
}
}

View file

@ -0,0 +1,36 @@
package com.ablia.util;
import com.ablia.db.DBAdapter;
import com.ablia.db.ResParm;
class AggiornaV3 extends ConsoleInput {
public static void main(String[] args) {
new AggiornaV3().aggiornaV3();
System.out.println("bye");
}
private ResParm aggiornaV3() {
ResParm rp = new ResParm();
setPropertyFile("aggiornaV3");
String sourceDir = getResource("SOURCE_DIR");
int i = 1;
String[] libs = { "admin/_V3/_js/", "admin/_V3/_inc/",
"admin/_V3/_css/", "Templates/" };
try {
String target;
while (!(target = getResource("TARGET_DIR_" + i)).isEmpty()) {
DBAdapter.copyFile(String.valueOf(sourceDir) + "admin/_V3/_abliajs.txt", String.valueOf(target) +
"admin/_V3/_abliajs.txt");
for (int j = 0; j < libs.length; j++) {
System.out.println("Copying from " + sourceDir + libs[j] +
" to " + target + libs[j]);
DBAdapter.copyDir(String.valueOf(sourceDir) + libs[j], String.valueOf(target) + libs[j]);
}
i++;
}
} catch (Exception e) {
rp.setException(e);
}
return rp;
}
}

View file

@ -0,0 +1,56 @@
package com.ablia.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.activation.DataSource;
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] abyte0, String s) {
this.data = abyte0;
this.type = s;
}
public ByteArrayDataSource(InputStream inputstream, String s) {
this.type = s;
try {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
int i;
while ((i = inputstream.read()) != -1)
bytearrayoutputstream.write(i);
this.data = bytearrayoutputstream.toByteArray();
} catch (IOException e) {}
}
public ByteArrayDataSource(String s, String s1) {
try {
this.data = s.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {}
this.type = s1;
}
public String getContentType() {
return this.type;
}
public InputStream getInputStream() throws IOException {
if (this.data == null)
throw new IOException("no data");
return new ByteArrayInputStream(this.data);
}
public String getName() {
return "dummy";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("cannot do this");
}
}

View file

@ -0,0 +1,19 @@
package com.ablia.util;
public class CharFillString {
private static final String ZERO = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
private static final String SPACE = " ";
public static String spaceFillStringRight(String source, int len) {
return String.valueOf(source) + " ".substring(0, len - source.length());
}
public static String spaceFillStringLeft(String source, int len) {
return String.valueOf(" ".substring(0, len - source.length())) + source;
}
public static String zeroFillStringLeft(String source, int len) {
return String.valueOf("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".substring(0, len - source.length())) + source;
}
}

View file

@ -0,0 +1,405 @@
package com.ablia.util;
import java.io.InputStream;
import java.sql.Date;
import java.util.Calendar;
import java.util.ResourceBundle;
public class CodiceFiscale {
private String nome;
private String cognome;
private Date dataDiNascita;
private String luogoDiNascita;
private String codiceLuogoDiNascita;
private char sesso;
private String codicefiscale;
private static final String PROP_COMUNI = "comuni";
private static final String ALFABETO = "abcdefghijklmnopqrstuvwxyz";
private static final String VOCALI = "aeiou";
private boolean errore;
private ResourceBundle propertyResource;
public CodiceFiscale() {}
private String pulisci(String s) {
String s1 = "";
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'à':
s1 = String.valueOf(s1) + "a";
break;
case 'è':
s1 = String.valueOf(s1) + "e";
break;
case 'é':
s1 = String.valueOf(s1) + "e";
break;
case 'ì':
s1 = String.valueOf(s1) + "i";
break;
case 'ò':
s1 = String.valueOf(s1) + "o";
break;
case 'ù':
s1 = String.valueOf(s1) + "u";
break;
default:
s1 = String.valueOf(s1) + s.charAt(i);
break;
case ' ':
case '\'':
break;
}
}
for (int j = 0; j < s1.length(); j++) {
if ("abcdefghijklmnopqrstuvwxyz".indexOf(s1.charAt(j)) < 0)
this.errore = true;
}
return s1;
}
private String pulisciLuogo(String s) {
String s1 = "";
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'à':
s1 = String.valueOf(s1) + "a'";
break;
case 'è':
s1 = String.valueOf(s1) + "e'";
break;
case 'é':
s1 = String.valueOf(s1) + "e'";
break;
case 'ì':
s1 = String.valueOf(s1) + "i'";
break;
case 'ò':
s1 = String.valueOf(s1) + "o'";
break;
case 'ù':
s1 = String.valueOf(s1) + "u'";
break;
default:
s1 = String.valueOf(s1) + s.charAt(i);
break;
}
}
return s1;
}
private boolean IsVocal(char c) {
return ("aeiou".indexOf(c) >= 0);
}
private String getCodiceCognome(String s) {
String s1 = "";
for (int i = 0; i < s.length(); i++) {
if (!IsVocal(s.charAt(i)))
s1 = String.valueOf(s1) + s.charAt(i);
}
if (s1.length() < 3) {
for (int j = 0; j < s.length(); j++) {
if (IsVocal(s.charAt(j)))
s1 = String.valueOf(s1) + s.charAt(j);
}
if (s1.length() < 3)
s1 = String.valueOf(s1) + "xxx";
}
return s1.substring(0, 3);
}
private String getCodiceNome(String s) {
String s1 = "";
for (int i = 0; i < s.length(); i++) {
if (!IsVocal(s.charAt(i)))
s1 = String.valueOf(s1) + s.charAt(i);
}
if (s1.length() > 3)
return s1.charAt(0) + s1.charAt(2) + s1.charAt(3);
if (s1.length() == 3)
return s1;
for (int j = 0; j < s.length(); j++) {
if (IsVocal(s.charAt(j)))
s1 = String.valueOf(s1) + s.charAt(j);
}
if (s1.length() < 3)
s1 = String.valueOf(s1) + "xxx";
return s1.substring(0, 3);
}
private String getCodiceData(Calendar calendar) {
String s, s1;
int i = calendar.get(1);
int j = calendar.get(2);
int k = calendar.get(5);
i %= 100;
if (i < 10) {
s = "0" + String.valueOf(i);
} else {
s = String.valueOf(i);
}
if (this.sesso == 'f' || this.sesso == 'F')
k += 40;
if (k < 10) {
s1 = "0" + String.valueOf(k);
} else {
s1 = String.valueOf(k);
}
if (k < 10)
return String.valueOf(i) + CODICI_MESE[j] + "0" + String.valueOf(k);
return String.valueOf(s) + CODICI_MESE[j] + s1;
}
private String getCodiceData(Date l_data) {
String s_anno, s_giorno;
Calendar cal = Calendar.getInstance();
cal.setTime(l_data);
int l_anno = cal.get(1);
int l_mese = cal.get(2);
int l_giorno = cal.get(5);
l_anno %= 100;
if (l_anno < 10) {
s_anno = "0" + String.valueOf(l_anno);
} else {
s_anno = String.valueOf(l_anno);
}
if (this.sesso == 'f' || this.sesso == 'F')
l_giorno += 40;
if (l_giorno < 10) {
s_giorno = "0" + String.valueOf(l_giorno);
} else {
s_giorno = String.valueOf(l_giorno);
}
return String.valueOf(s_anno) + CODICI_MESE[l_mese] + s_giorno;
}
private String readIn(InputStream inputstream) {
String s = "";
if (inputstream == null)
return "";
int i;
while ((i = inputstream.read()) != -1) {
try {
if (i == 10)
return s;
s = String.valueOf(s) + (char)i;
} catch (Exception e) {
break;
}
}
return s;
}
private String getCodiceLuogo2(String s) {
if (s == "")
return "errore";
String s1 = "";
InputStream inputstream = null;
inputstream = getClass().getResourceAsStream("/comuni.txt");
do {
} while ((s1 = readIn(inputstream)) != "" && !s1.startsWith(s));
if (s1 == "") {
this.errore = true;
return "oooo";
}
String s2 = s1.substring(s1.indexOf(';') + 1, s1.indexOf(';') + 5);
return s2;
}
private String getCodiceLuogo() {
String s = this.luogoDiNascita;
s = s.replace(' ', '_');
String res = getResource(s);
if (res.equals("")) {
this.errore = true;
return "oooo";
}
return res;
}
private static char getCodiceControllo(String s) {
int i = 0;
int j = 0;
for (int k = 0; k <= 14; k += 2) {
char c = s.charAt(k);
for (int i1 = 0; i1 < CARATTERI.length; i1++) {
if (CARATTERI[i1] == c)
j += CODICI_DISPARI[i1];
}
}
for (int l = 1; l <= 13; l += 2) {
char c1 = s.charAt(l);
for (int j1 = 0; j1 < CARATTERI.length; j1++) {
if (CARATTERI[j1] == c1)
i += CODICI_PARI[j1];
}
}
return CODICI_CONTROLLO[(i + j) % 26];
}
private void CalcolaCodice() {
String l_cognome = getCognome();
String l_nome = this.nome;
String l_luogoDiNascita = this.luogoDiNascita;
String l_erMsg = "";
l_cognome = l_cognome.toLowerCase();
l_cognome = pulisci(l_cognome);
l_nome = l_nome.toLowerCase();
l_nome = pulisci(l_nome);
l_luogoDiNascita = l_luogoDiNascita.toLowerCase();
l_luogoDiNascita = pulisciLuogo(l_luogoDiNascita);
l_luogoDiNascita = l_luogoDiNascita.toUpperCase();
if (l_cognome.equals("") || l_nome.equals("") || (l_luogoDiNascita.equals("") && getCodiceLuogoDiNascita().equals("")) ||
getDataDiNascita() == null) {
this.codicefiscale = "";
} else {
if (!this.errore)
this.codicefiscale = getCodiceCognome(l_cognome).toUpperCase();
if (!this.errore)
this.codicefiscale = String.valueOf(this.codicefiscale) + getCodiceNome(l_nome).toUpperCase();
if (!this.errore)
this.codicefiscale = String.valueOf(this.codicefiscale) + getCodiceData(getDataDiNascita()).toUpperCase();
if (!this.errore)
if (getCodiceLuogoDiNascita().toUpperCase().length() != 4) {
this.errore = true;
l_erMsg = "Codice luogo nascita errato";
} else {
this.codicefiscale = String.valueOf(this.codicefiscale) + getCodiceLuogoDiNascita().toUpperCase();
}
if (!this.errore)
if (this.codicefiscale.length() != 15) {
l_erMsg = "Cod. Controllo non calcolabile (lungh. < 16)";
} else {
this.codicefiscale = String.valueOf(this.codicefiscale) + getCodiceControllo(this.codicefiscale);
}
if (this.errore)
this.codicefiscale = "";
}
}
public CodiceFiscale(String l_cognome, String l_nome, Date l_dataNascita, String l_luogoNascita, char l_sesso) {
this.errore = false;
this.nome = l_nome;
this.cognome = l_cognome;
this.dataDiNascita = l_dataNascita;
this.luogoDiNascita = l_luogoNascita;
this.sesso = l_sesso;
}
public String getNome() {
return this.nome;
}
public String getCognome() {
return this.cognome;
}
public Date getDataDiNascita() {
return this.dataDiNascita;
}
public char getSesso() {
return this.sesso;
}
private static final char[] CODICI_MESE = new char[] {
'a', 'b', 'c', 'd', 'e', 'h', 'l', 'm', 'p', 'r',
's', 't' };
private static final char[] CARATTERI = new char[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9' };
private static final int[] CODICI_DISPARI = new int[] {
1, 5, 7, 9, 13, 15, 17, 19, 21, 2,
4, 18, 20, 11, 3, 6, 8, 12, 14, 16,
10, 22, 25, 24,
23, 1, 5, 7, 9, 13,
15, 17, 19, 21 };
private static final int[] CODICI_PARI = new int[] {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25,
1, 2, 3, 4,
5, 6, 7, 8, 9 };
private static final char[] CODICI_CONTROLLO = new char[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
public String getCodicefiscale() {
if (this.codicefiscale == null)
CalcolaCodice();
return this.codicefiscale;
}
public void setCodicefiscale(String codicefiscale) {
this.codicefiscale = codicefiscale;
}
private ResourceBundle getPropertyResource() {
if (this.propertyResource == null)
this.propertyResource = ResourceBundle.getBundle("comuni");
return this.propertyResource;
}
private String getResource(String key) {
try {
return getPropertyResource().getString(key);
} catch (Exception e) {
System.out.println("CodiceFiscale: " + e.getMessage() + " . Property file:" + "comuni");
return "";
}
}
public static final boolean controlloFormale(String l_cf) {
l_cf = l_cf.toUpperCase().trim();
if (l_cf.length() != 16 && l_cf.length() != 11)
return false;
if (l_cf.length() == 16) {
if (l_cf.matches("[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z][0-9][0-9][A-Z][0-9][0-9][A-Z][0-9][0-9][0-9][A-Z]")) {
String l_cf1 = l_cf.substring(0, 15);
char l_cc1 = getCodiceControllo(l_cf1);
if (l_cf.charAt(15) == l_cc1)
return true;
return false;
}
return false;
}
if (l_cf.length() == 11) {
if (l_cf.matches("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"))
return true;
return false;
}
return false;
}
public String getCodiceLuogoDiNascita() {
if (this.codiceLuogoDiNascita == null)
this.codiceLuogoDiNascita = getCodiceLuogo();
return (this.codiceLuogoDiNascita == null) ? "" : this.codiceLuogoDiNascita;
}
public void setCodiceLuogoDiNascita(String codiceLuogoDiNascita) {
this.codiceLuogoDiNascita = codiceLuogoDiNascita;
}
}

View file

@ -0,0 +1,28 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ConsoleInput extends Debug {
private BufferedReader br;
private BufferedReader getBr() {
if (this.br == null)
this.br = new BufferedReader(new InputStreamReader(System.in));
return this.br;
}
public String readLine(String s) {
String s1 = null;
try {
System.out.print(s);
s1 = getBr().readLine();
} catch (IOException ioexception) {
ioexception.printStackTrace(System.out);
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
return s1;
}
}

View file

@ -0,0 +1,859 @@
package com.ablia.util;
import com.ablia.db.ResParm;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectory;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.common.IImageMetadata;
import org.apache.sanselan.formats.jpeg.JpegImageMetadata;
import org.apache.sanselan.formats.jpeg.exifRewrite.ExifRewriter;
import org.apache.sanselan.formats.tiff.TiffImageMetadata;
import org.apache.sanselan.formats.tiff.constants.ExifTagConstants;
import org.apache.sanselan.formats.tiff.constants.TiffFieldTypeConstants;
import org.apache.sanselan.formats.tiff.fieldtypes.FieldType;
import org.apache.sanselan.formats.tiff.write.TiffOutputDirectory;
import org.apache.sanselan.formats.tiff.write.TiffOutputField;
import org.apache.sanselan.formats.tiff.write.TiffOutputSet;
public class CopyOfScaleImage extends DbConsole {
private static final DateFormat exifDateFormatter = new SimpleDateFormat(
"yyyy:MM:dd HH:mm:ss");
private static final long serialVersionUID = 1L;
private String watermarkText;
private String theScaledImageName;
private boolean checkScaled = true;
private boolean autoRotate = false;
private String scaledPrefix;
private long scaledFactor;
private int scaledHeight;
private int rotateDegree;
private boolean useTimestamp = true;
private String theImageName;
private int scaledWidth;
private int numbWatermark;
private String copyrightText;
private static final String DEF_SCALED_PREFIX = "TH/";
public CopyOfScaleImage() {
setCheckScaled(false);
setUseTimestamp(false);
}
public CopyOfScaleImage(String l_theImage, String l_scaledPrefix, long l_scaledFactor, int l_scaledWidth, int l_scaledHeight, int l_rotateDegree, boolean l_checkScaled, boolean l_useTimestamp) {
setTheImageName(l_theImage);
setScaledPrefix(l_scaledPrefix);
setScaledFactor(l_scaledFactor);
setScaledWidth(l_scaledWidth);
setScaledHeight(l_scaledHeight);
setRotateDegree(l_rotateDegree);
setCheckScaled(l_checkScaled);
setUseTimestamp(l_useTimestamp);
}
public CopyOfScaleImage(String l_theImage, String l_scaledPrefix, long l_scaledFactor, int l_scaledWidth, int l_scaledHeight, boolean l_checkScaled, boolean l_useTimestamp) {
setTheImageName(l_theImage);
setScaledPrefix(l_scaledPrefix);
setScaledFactor(l_scaledFactor);
setScaledWidth(l_scaledWidth);
setScaledHeight(l_scaledHeight);
setCheckScaled(l_checkScaled);
setUseTimestamp(l_useTimestamp);
}
public ResParm scaleIt() {
ResParm rp = new ResParm(true);
String absImg = getFullImagename(getTheImageName());
try {
if (isImageExist(absImg)) {
if (isScaled() || getWatermarkText() != null ||
getRotateDegree() > 0) {
rp = scaleImage(absImg);
} else {
rp.setMsg("Nessun parametro scaled: " + absImg);
}
} else {
rp.setMsg("ERRORE! Immagine non trovata: " + absImg);
rp.setStatus(false);
}
} catch (Exception ex) {
handleDebug(ex);
rp.setStatus(false);
rp.setMsg(ex);
}
return rp;
}
private ResParm scaleImage(String fullImageName) {
ResParm rp = new ResParm(true);
try {
int imgIdx = fullImageName.lastIndexOf(getFileSeparator()) + 1;
if (imgIdx == 0)
imgIdx = fullImageName.lastIndexOf('/') + 1;
String fullResultImageName = getFullScaledImagename(fullImageName);
if (scaleAgain(fullImageName)) {
String msg = "";
BufferedImage srcImage = ImageIO.read(new File(fullImageName));
Image resultImage = null;
Graphics2D g = srcImage.createGraphics();
int height = srcImage.getHeight();
int width = srcImage.getWidth();
int rotateDegree = getRotateDegree();
if (isAutoRotate()) {
File jpegFile = new File(fullImageName);
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
Directory exifDirectory = metadata.getDirectory(ExifDirectory.class);
Date theDate = null;
int orientation = -1;
if (exifDirectory.containsTag(36867))
theDate =
exifDirectory.getDate(36867);
if (exifDirectory.containsTag(274)) {
orientation =
exifDirectory.getInt(274);
if (orientation == 8) {
rotateDegree = 270;
} else if (orientation == 6) {
rotateDegree = 90;
}
}
}
if (rotateDegree > 0) {
double positiveDegrees = (double)(rotateDegree % 360 + (
(rotateDegree < 0) ? 360 : 0));
double degreesMod90 = positiveDegrees % 90.0D;
double radians = Math.toRadians(positiveDegrees);
double radiansMod90 = Math.toRadians(degreesMod90);
if (positiveDegrees > 0.0D) {
int quadrant = 0;
if (positiveDegrees < 90.0D) {
quadrant = 1;
} else if (positiveDegrees >= 90.0D &&
positiveDegrees < 180.0D) {
quadrant = 2;
} else if (positiveDegrees >= 180.0D &&
positiveDegrees < 270.0D) {
quadrant = 3;
} else if (positiveDegrees >= 270.0D) {
quadrant = 4;
}
double side1 = Math.sin(radiansMod90) * (double)height +
Math.cos(radiansMod90) * (double)width;
double side2 = Math.cos(radiansMod90) * (double)height +
Math.sin(radiansMod90) * (double)width;
double h = 0.0D;
int newWidth = 0, newHeight = 0;
if (quadrant == 1 || quadrant == 3) {
h = Math.sin(radiansMod90) * (double)height;
newWidth = (int)side1;
newHeight = (int)side2;
} else {
h = Math.sin(radiansMod90) * (double)width;
newWidth = (int)side2;
newHeight = (int)side1;
}
int shiftX = (int)(Math.cos(radians) * h) - ((
quadrant == 3 || quadrant == 4) ? width :
0);
int shiftY = (int)(Math.sin(radians) * h) + ((
quadrant == 2 || quadrant == 3) ? height :
0);
BufferedImage newbi = new BufferedImage(newWidth,
newHeight, srcImage.getType());
Graphics2D g2d = newbi.createGraphics();
g2d.setBackground(Color.black);
g2d.clearRect(0, 0, newWidth, newHeight);
g2d.rotate(radians);
g2d.drawImage(srcImage, shiftX, -shiftY, null);
srcImage = newbi;
g = srcImage.createGraphics();
resultImage = Toolkit.getDefaultToolkit().createImage(
srcImage.getSource());
}
}
if (getWatermarkText() != null) {
g.setComposite(AlphaComposite.getInstance(
10, 0.8F));
g.setColor(Color.white);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int DIM_WM_BASE = 30;
int dimWM = 30 * width / 460;
g.setFont(new Font("Verdana", 1,
dimWM));
String watermark = getWatermarkText();
String copyright = getCopyrightText();
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle2D rectWm = fontMetrics.getStringBounds(watermark,
g);
int centerXWm = (srcImage.getWidth() -
(int)rectWm.getWidth()) / 2;
int centerYWm = (srcImage.getHeight() +
(int)rectWm.getHeight() / 2) / 2;
for (int i = 0; i < getNumbWatermark(); i++) {
int currentYWm = (srcImage.getHeight() +
(int)rectWm.getHeight() / 2) / (
getNumbWatermark() + 1) * (
i + 1);
g.drawString(watermark, centerXWm, currentYWm);
}
if (!getCopyrightText().isEmpty()) {
g.setFont(new Font("Verdana",
1, 8));
FontMetrics fontMetricsC = g.getFontMetrics();
StringTokenizer st = new StringTokenizer(copyright,
"\n");
int j = -1;
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.endsWith("\r"))
token = token.substring(0, token.length() - 2);
Rectangle2D rectC = fontMetricsC.getStringBounds(token, g);
int centerXC = (srcImage.getWidth() -
(int)rectC.getWidth()) / 2;
g.drawString(token, centerXC, centerYWm + j * 12);
j++;
}
}
g.dispose();
resultImage = Toolkit.getDefaultToolkit().createImage(
srcImage.getSource());
String temp = "ScaleImage wm inserito nell'immagine " +
fullResultImageName;
msg = String.valueOf(msg) + temp;
}
if (isScaled()) {
int w = srcImage.getWidth(), h = srcImage.getHeight();
if ((getScaledWidth() == 0 || getScaledWidth() != w) && (getScaledHeight() == 0 || getScaledHeight() != h)) {
int sw, sh;
if (getScaledWidth() == 0 && getScaledHeight() == 0) {
int sf = (int)(100L / getScaledFactor());
sw = w / sf;
sh = h / sf;
} else if (getScaledWidth() != 0 &&
getScaledHeight() == 0) {
sw = getScaledWidth();
sh = getScaledWidth() * h / w;
} else if (getScaledWidth() == 0 &&
getScaledHeight() != 0) {
sh = getScaledHeight();
sw = getScaledHeight() * w / h;
} else {
sw = getScaledWidth();
sh = getScaledHeight();
}
resultImage = srcImage.getScaledInstance(sw, sh,
16);
String temp = "ScaleImage immagine scalata creata: w=" +
sw + " h=" +
sh + " imgname=" + fullResultImageName;
msg = String.valueOf(msg) + temp;
}
}
if (resultImage != null) {
BufferedImage biRescaled = toBufferedImage(resultImage,
1);
File fullResultImageNameDir = new File(
getFullScaledImagePath(fullImageName));
boolean dirOk = true;
if (!fullResultImageNameDir.exists()) {
dirOk = fullResultImageNameDir.mkdirs();
msg = "Create dir " +
getFullScaledImagePath(fullImageName) + "\n";
}
if (dirOk) {
File scaledImageFile = new File(fullResultImageName);
ImageIO.write(biRescaled, "jpeg", scaledImageFile);
scaledImageFile = null;
}
setTheScaledImageName(fullResultImageName);
rp.setMsg(msg);
srcImage.flush();
srcImage = null;
biRescaled.flush();
biRescaled = null;
fullResultImageNameDir = null;
}
} else {
rp.setMsg("Immagine già scalata: " + fullImageName);
setTheScaledImageName(fullResultImageName);
}
} catch (Exception e) {
rp.setMsg("ScaleImage scaleImage ERROR!!!! " + e.getMessage());
rp.setStatus(false);
}
return rp;
}
private boolean scaleAgain(String fullImageName) {
try {
int imgIdx = fullImageName.lastIndexOf(getFileSeparator()) + 1;
if (imgIdx == 0)
imgIdx = fullImageName.lastIndexOf('/') + 1;
String fullImageNameScaled = getFullScaledImagename(fullImageName);
boolean scaleAgain = false;
if (isFileExist(fullImageNameScaled)) {
if (isCheckScaled() && getRotateDegree() == 0) {
BufferedImage srcImage = ImageIO.read(new File(
fullImageName));
BufferedImage scaledImage = ImageIO.read(new File(
fullImageNameScaled));
int w = srcImage.getWidth();
int sw = scaledImage.getWidth();
int sh = scaledImage.getHeight();
if (getScaledFactor() != 0L) {
int sf = (int)(100L / getScaledFactor());
if (w / sw == sf) {
scaleAgain = false;
} else {
scaleAgain = true;
}
}
if (getScaledWidth() != 0 && !scaleAgain)
if (getScaledWidth() == sw) {
scaleAgain = false;
} else {
scaleAgain = true;
}
if (getScaledHeight() != 0 && !scaleAgain)
if (getScaledHeight() == sh) {
scaleAgain = false;
} else {
scaleAgain = true;
}
} else {
scaleAgain = false;
}
if (scaleAgain) {
File dir = new File(getFullScaledImagePath(fullImageName));
File[] imgs = dir.listFiles();
if (imgs != null) {
File theImg = null;
String temp = getImageNameNoExt(fullImageName);
for (int i = 0; i < imgs.length; i++) {
theImg = imgs[i];
if (theImg.getName().indexOf(temp) != -1)
theImg.delete();
}
}
}
} else {
scaleAgain = true;
}
return scaleAgain;
} catch (Exception e) {
System.out.println("ScaleImage method scaleAgain() " +
e.getMessage());
e.printStackTrace(System.out);
return false;
}
}
private String getFullImagename(String imageName) {
try {
String fullImageName = imageName;
if (isFileExist(fullImageName)) {
this.theImageName = imageName;
} else if (isFileExist(String.valueOf(fullImageName) + ".jpg")) {
this.theImageName = String.valueOf(imageName) + ".jpg";
} else if (isFileExist(String.valueOf(fullImageName) + ".gif")) {
this.theImageName = String.valueOf(imageName) + ".gif";
} else {
this.theImageName = null;
}
} catch (Exception e) {
this.theImageName = null;
}
return this.theImageName;
}
private String xgetTheSuffixImageExt(String imageName) {
if (this.theImageName == null)
return "";
if (imageName.endsWith(".jpg") || imageName.endsWith(".gif"))
return "";
return this.theImageName.substring(this.theImageName.lastIndexOf('.'),
this.theImageName.length());
}
private String getFileSeparator() {
return System.getProperty("file.separator");
}
private boolean isFileExist(String fileName) {
return new File(fileName).exists();
}
private boolean isImageExist(String imageName) {
return !(getFullImagename(imageName) == null);
}
private static BufferedImage toBufferedImage(Image image, int type) {
int w = image.getWidth(null);
int h = image.getHeight(null);
BufferedImage result = new BufferedImage(w, h, type);
Graphics2D g = result.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
private boolean isScaled() {
if (this.scaledFactor > 0L || this.scaledWidth > 0 || this.scaledHeight > 0)
return true;
return false;
}
public String getScaledPrefix() {
return (this.scaledPrefix == null) ? "TH/" : this.scaledPrefix;
}
public void setScaledPrefix(String scaledPrefixFile) {
this.scaledPrefix = scaledPrefixFile;
}
public long getScaledFactor() {
return this.scaledFactor;
}
public void setScaledFactor(long scaledFactor) {
this.scaledFactor = scaledFactor;
}
public int getScaledWidth() {
return this.scaledWidth;
}
private String getFullScaledImagename(String fullImageName) {
String fullImageNameScaled;
int imgIdx = fullImageName.lastIndexOf(getFileSeparator()) + 1;
if (imgIdx == 0)
imgIdx = fullImageName.lastIndexOf('/') + 1;
String wm = "", rd = "";
if (getWatermarkText() != null)
wm = "_wm";
if (getRotateDegree() != 0)
rd = "_R" + getRotateDegree();
if (isUseTimestamp()) {
File theImg = new File(fullImageName);
Timestamp t = new Timestamp(theImg.lastModified());
String imgName = fullImageName.substring(imgIdx,
fullImageName.length());
imgName = String.valueOf(imgName.substring(0, imgName.lastIndexOf("."))) +
wm +
rd +
"_" +
t.getTime() +
imgName.substring(imgName.lastIndexOf("."),
imgName.length());
fullImageNameScaled = String.valueOf(fullImageName.substring(0, imgIdx)) +
getScaledPrefix() + imgName;
} else {
String imgName = fullImageName.substring(imgIdx,
fullImageName.length());
imgName = String.valueOf(imgName.substring(0, imgName.lastIndexOf("."))) +
wm +
rd +
imgName.substring(imgName.lastIndexOf("."),
imgName.length());
fullImageNameScaled = String.valueOf(fullImageName.substring(0, imgIdx)) +
getScaledPrefix() + imgName;
}
return fullImageNameScaled;
}
private String getFullScaledImagePath(String fullImageName) {
int imgIdx = fullImageName.lastIndexOf(getFileSeparator()) + 1;
if (imgIdx == 0)
imgIdx = fullImageName.lastIndexOf('/') + 1;
String fullImageNameScaled = String.valueOf(fullImageName.substring(0, imgIdx)) +
getScaledPrefix();
return fullImageNameScaled;
}
private String getImageNameNoExt(String fullImageName) {
int imgIdx = fullImageName.lastIndexOf("/") + 1;
int imgIdxDot = fullImageName.lastIndexOf('.');
if (imgIdx < imgIdxDot)
return fullImageName.substring(imgIdx, imgIdxDot);
return fullImageName.substring(imgIdx, fullImageName.length());
}
public void setScaledWidth(int scaledWidth) {
this.scaledWidth = scaledWidth;
}
public boolean isCheckScaled() {
return this.checkScaled;
}
public void setCheckScaled(boolean checkScaled) {
this.checkScaled = checkScaled;
}
public String getTheImageName() {
return this.theImageName;
}
public void setTheImageName(String theImageName) {
this.theImageName = theImageName;
}
public String getTheScaledImageName() {
return this.theScaledImageName;
}
public void setTheScaledImageName(String theScaledImageName) {
this.theScaledImageName = theScaledImageName;
}
public int getScaledHeight() {
return this.scaledHeight;
}
public void setScaledHeight(int scaledHeight) {
this.scaledHeight = scaledHeight;
}
public boolean isUseTimestamp() {
return this.useTimestamp;
}
public void setUseTimestamp(boolean useTimestamp) {
this.useTimestamp = useTimestamp;
}
public ResParm scaleIt(String watermark) {
setWatermarkText(watermark);
return scaleIt();
}
public String getWatermarkText() {
return this.watermarkText;
}
public void setWatermarkText(String theWatermarkFileName) {
this.watermarkText = theWatermarkFileName;
}
public int getRotateDegree() {
return this.rotateDegree;
}
public void setRotateDegree(int rotateDegree) {
this.rotateDegree = rotateDegree;
}
public int getNumbWatermark() {
return (this.numbWatermark <= 0) ? 1 : this.numbWatermark;
}
public void setNumbWatermark(int numbWatermark) {
this.numbWatermark = numbWatermark;
}
public ResParm scaleIt(String watermark, int numbWatermark) {
setWatermarkText(watermark);
setNumbWatermark(numbWatermark);
return scaleIt();
}
public String getCopyrightText() {
return (this.copyrightText == null) ? "" :
this.copyrightText.trim();
}
public void setCopyrightText(String copyrightText) {
this.copyrightText = copyrightText;
}
public ResParm scaleIt(String watermark, String l_copyrightText, int numbWatermark) {
setWatermarkText(watermark);
setCopyrightText(l_copyrightText);
setNumbWatermark(numbWatermark);
return scaleIt();
}
public ResParm scaleImageToFile(String srcFileName, String targetDir, int dimLatoLungo, int dpi, String watermark, int wmX, int wmY) {
ResParm rp = new ResParm(true);
try {
int sw, sh;
File jpegFile = new File(srcFileName);
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
Directory exifDirectory = metadata.getDirectory(ExifDirectory.class);
Date theDate = null;
int orientation = -1;
int rotataDegree = 0;
if (exifDirectory.containsTag(36867))
theDate =
exifDirectory.getDate(36867);
if (exifDirectory.containsTag(274)) {
orientation =
exifDirectory.getInt(274);
if (orientation == 8) {
rotataDegree = 270;
} else if (orientation == 6) {
rotataDegree = 90;
}
}
int imgIdx = srcFileName.lastIndexOf(getFileSeparator()) + 1;
if (imgIdx == 0)
imgIdx = srcFileName.lastIndexOf('/') + 1;
String fullResultImageName = String.valueOf(targetDir) +
srcFileName.substring(imgIdx);
String tempResultImageName = String.valueOf(targetDir) + "T_" +
srcFileName.substring(imgIdx);
String msg = "";
BufferedImage srcImage = ImageIO.read(new File(srcFileName));
Image resultImage = null;
Graphics2D g = srcImage.createGraphics();
int height = srcImage.getHeight();
int width = srcImage.getWidth();
if (rotataDegree > 0) {
double positiveDegrees = (double)(rotataDegree % 360 + (
(rotataDegree < 0) ? 360 : 0));
double degreesMod90 = positiveDegrees % 90.0D;
double radians = Math.toRadians(positiveDegrees);
double radiansMod90 = Math.toRadians(degreesMod90);
if (positiveDegrees > 0.0D) {
int quadrant = 0;
if (positiveDegrees < 90.0D) {
quadrant = 1;
} else if (positiveDegrees >= 90.0D && positiveDegrees < 180.0D) {
quadrant = 2;
} else if (positiveDegrees >= 180.0D &&
positiveDegrees < 270.0D) {
quadrant = 3;
} else if (positiveDegrees >= 270.0D) {
quadrant = 4;
}
height = srcImage.getHeight();
width = srcImage.getWidth();
double side1 = Math.sin(radiansMod90) * (double)height +
Math.cos(radiansMod90) * (double)width;
double side2 = Math.cos(radiansMod90) * (double)height +
Math.sin(radiansMod90) * (double)width;
double d1 = 0.0D;
int newWidth = 0, newHeight = 0;
if (quadrant == 1 || quadrant == 3) {
d1 = Math.sin(radiansMod90) * (double)height;
newWidth = (int)side1;
newHeight = (int)side2;
} else {
d1 = Math.sin(radiansMod90) * (double)width;
newWidth = (int)side2;
newHeight = (int)side1;
}
int shiftX = (int)(Math.cos(radians) * d1) - ((
quadrant == 3 || quadrant == 4) ? width : 0);
int shiftY = (int)(Math.sin(radians) * d1) + ((
quadrant == 2 || quadrant == 3) ? height : 0);
BufferedImage newbi = new BufferedImage(newWidth,
newHeight, srcImage.getType());
Graphics2D g2d = newbi.createGraphics();
g2d.setBackground(Color.black);
g2d.clearRect(0, 0, newWidth, newHeight);
g2d.rotate(radians);
g2d.drawImage(srcImage, shiftX, -shiftY, null);
srcImage = newbi;
g = srcImage.createGraphics();
resultImage = Toolkit.getDefaultToolkit().createImage(
srcImage.getSource());
}
}
if (watermark != null) {
g.setComposite(AlphaComposite.getInstance(
10, 0.8F));
g.setColor(Color.white);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int DIM_WM_BASE = 30;
int dimWM = 30 * width / dimLatoLungo;
g.setFont(new Font("Verdana", 1,
dimWM));
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle2D rectWm = fontMetrics.getStringBounds(watermark, g);
FontMetrics fontMetricsC = g.getFontMetrics();
StringTokenizer st = new StringTokenizer(watermark, "\n");
int i = -1;
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.endsWith("\r"))
token = token.substring(0, token.length() - 2);
Rectangle2D rectC = fontMetricsC.getStringBounds(token, g);
g.drawString(token, wmX, wmY + i * 12);
i++;
}
g.dispose();
resultImage = Toolkit.getDefaultToolkit().createImage(
srcImage.getSource());
String str = "ScaleImage wm inserito nell'immagine " +
fullResultImageName;
msg = String.valueOf(msg) + str;
}
int w = srcImage.getWidth(), h = srcImage.getHeight();
if (w > h) {
sw = dimLatoLungo;
sh = dimLatoLungo * h / w;
} else {
sh = dimLatoLungo;
sw = dimLatoLungo * w / h;
}
resultImage = srcImage.getScaledInstance(sw, sh,
16);
String temp = "ScaleImage immagine scalata creata: w=" + sw +
" h=" + sh + " imgname=" + fullResultImageName;
msg = String.valueOf(msg) + temp;
if (resultImage != null) {
BufferedImage biRescaled = toBufferedImage(resultImage,
1);
File fullResultImageNameDir = new File(targetDir);
boolean dirOk = true;
if (!fullResultImageNameDir.exists())
dirOk = fullResultImageNameDir.mkdirs();
if (dirOk) {
File scaledImageFile = new File(tempResultImageName);
ImageIO.write(biRescaled, "jpeg", scaledImageFile);
scaledImageFile = null;
}
rp.setMsg(msg);
srcImage.flush();
srcImage = null;
biRescaled.flush();
biRescaled = null;
fullResultImageNameDir = null;
}
if (theDate != null) {
changeExifMetadataDate(new File(tempResultImageName), theDate,
fullResultImageName);
new File(tempResultImageName).delete();
}
setTheScaledImageName(fullResultImageName);
} catch (Exception e) {
rp.setMsg("ScaleImage scaleImage ERROR!!!! " + e.getMessage());
rp.setStatus(false);
}
return rp;
}
public void changeExifMetadataDate(File jpegImageFile, Date theDate, String dstFile) {
OutputStream os = null;
try {
TiffOutputSet outputSet = null;
IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
JpegImageMetadata jpegMetadata = (JpegImageMetadata)metadata;
if (jpegMetadata != null) {
TiffImageMetadata exif = jpegMetadata.getExif();
if (exif != null)
outputSet = exif.getOutputSet();
}
if (outputSet == null)
outputSet = new TiffOutputSet();
String stringDate = exifDateFormatter.format(theDate);
TiffOutputField dateTag = new TiffOutputField(
ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
(FieldType)TiffFieldTypeConstants.FIELD_TYPE_ASCII,
stringDate.length(), stringDate.getBytes());
TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();
exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
exifDirectory.add(dateTag);
os = new FileOutputStream(dstFile);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
os.close();
os = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void changeExifMetadataDate3(byte[] imgB, File dst, Date theDate) {
OutputStream os = null;
try {
TiffOutputSet outputSet = null;
IImageMetadata metadata = Sanselan.getMetadata(imgB);
JpegImageMetadata jpegMetadata = (JpegImageMetadata)metadata;
if (jpegMetadata != null) {
TiffImageMetadata exif = jpegMetadata.getExif();
if (exif != null)
outputSet = exif.getOutputSet();
}
if (outputSet == null)
outputSet = new TiffOutputSet();
TiffOutputField dateTag = TiffOutputField.create(
ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL,
outputSet.byteOrder, theDate.toString());
TiffOutputDirectory exifDirectory = outputSet.getOrCreateExifDirectory();
exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
exifDirectory.add(dateTag);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(dst, os, outputSet);
os.close();
os = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public ResParm scaleImageToFile(String srcFileName, String targetDir, int dimLatoLungo, int dpi) {
return scaleImageToFile(srcFileName, targetDir, dimLatoLungo, dpi,
null, 0, 0);
}
public boolean isAutoRotate() {
return this.autoRotate;
}
public void setAutoRotate(boolean autoRotate) {
this.autoRotate = autoRotate;
}
}

View file

@ -0,0 +1,100 @@
package com.ablia.util;
import com.ablia.common.Parm;
import com.ablia.db.ApplParm;
import com.ablia.db.ApplParmFull;
import com.ablia.db.DriversJdbc;
import com.ablia.db.JdbcStub;
public class DbConsole extends Debug {
protected ApplParmFull apFull;
private ConsoleInput ci;
private JdbcStub db;
private String outputPaht;
private Parm parm;
protected boolean consoleYN() {
String temp = getCi().readLine("(Y/N)[Y]: ");
if (temp.toLowerCase().equals("n"))
return false;
return true;
}
protected ApplParmFull getApFull() {
if (this.apFull == null)
try {
if (getResource("dbDriver").equals("") ||
getResource("database").equals("")) {
System.out.println("Jdbc connection.....");
System.out.println("Choose the Jdbc driver (it must be in your classpath):");
for (int i = 0; i < DriversJdbc.getTotNumberOfDrivers(); i++)
System.out.println("(" + i + ") " + DriversJdbc.getDriverDescription(i));
String driver = getCi().readLine("Driver=");
String DSN = getCi().readLine("jdbc resource: " + DriversJdbc.getDriverDescription(Integer.parseInt(driver)));
String login = getCi().readLine("Login: ");
String pwd = getCi().readLine("Password: ");
ApplParm ap = new ApplParm(Integer.parseInt(driver), DSN, login, pwd);
this.apFull = new ApplParmFull(ap);
} else {
ApplParm ap = new ApplParm(Integer.parseInt(getResource("dbDriver")),
getResource("database"), getResource("user"),
getResource("password"), 1, 10, 300);
ap.setDebugLevel(Integer.parseInt(getResource("DEBUG_LEVEL")));
ap.setPropertyFileName(getPropertyFile());
this.apFull = new ApplParmFull(ap);
}
} catch (Exception e) {
e.printStackTrace(System.out);
return null;
}
return this.apFull;
}
protected ConsoleInput getCi() {
if (this.ci == null)
this.ci = new ConsoleInput();
return this.ci;
}
protected JdbcStub getDb() {
if (this.db == null)
try {
this.db = new JdbcStub(getApFull().getAp());
} catch (Exception e) {
e.printStackTrace(System.out);
return null;
}
return this.db;
}
protected final String getOutputPaht() {
if (this.outputPaht == null) {
this.outputPaht = getCi().readLine("Output path:(/Users/acolzi/Downloads/_temp) ");
if (this.outputPaht.isEmpty())
this.outputPaht = "/Users/acolzi/Downloads/_temp";
if (!this.outputPaht.endsWith("/"))
this.outputPaht = String.valueOf(this.outputPaht) + "/";
}
return this.outputPaht;
}
protected String getPs() {
return "/";
}
public Parm getParm(String theKey) {
if (this.parm == null)
this.parm = new Parm(getApFull());
try {
this.parm.findByCodice(theKey);
return this.parm;
} catch (Exception e) {
handleDebug(e);
return this.parm;
}
}
}

View file

@ -0,0 +1,423 @@
package com.ablia.util;
import com.ablia.db.ApplParmFull;
import com.ablia.db.DBAdapter;
import com.ablia.log.Log;
import com.ablia.mail.MailProperties;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Debug implements DebugInterface {
protected ApplParmFull apFull;
private boolean debug = false;
private String debugFile = "/var/log/ablia_debug.log";
private static final String PROPERTY_DEBUG_FILE = "debug";
private int debugLevel = 3;
protected String createDebugMessage(int l_debugLevel, String theMsg, Exception e, ApplParmFull apFull) {
StringBuffer msg = new StringBuffer(DebugInterface.LOG_DESC[l_debugLevel]);
Date d = new Date(System.currentTimeMillis());
msg.append(d.toString());
msg.append("\nVersion: ");
msg.append(DBAdapter.getVersion());
msg.append("\nClass: ");
msg.append(getClass().getName());
if (theMsg != null) {
msg.append("\n0-------------------- DEBUG MESSAGE --------------------\n");
msg.append(theMsg);
msg.append("\n0------------------------------------------------------------------\n");
}
if (l_debugLevel == 5 || l_debugLevel == 2 || l_debugLevel == 0) {
if (this instanceof DBAdapter) {
msg.append("\n\n1-------------------- BEAN DESC RECORD --------------------\n");
msg.append(((DBAdapter)this).getDescRecord());
msg.append("\n1------------------------------------------------------------------\n");
}
msg.append("\n2-------------------- Calling Stack Trace --------------------\n");
msg.append(getCallingStackTrace());
msg.append("\n2------------------------------------------------------------------\n");
}
if (e != null) {
msg.append("\n3-------------------- Exception --------------------\n");
msg.append(e.toString());
msg.append("\nException Stack trace follow:\n");
StackTraceElement[] arrayOfStackTraceElement;
for (int j = (arrayOfStackTraceElement = e.getStackTrace()).length, i = 0; i < j; ) {
StackTraceElement s = arrayOfStackTraceElement[i];
msg.append(s);
msg.append("\n");
i++;
}
msg.append("3------------------------------------------------------------------\n");
}
if (l_debugLevel == 5 || l_debugLevel == 2 || l_debugLevel == 0) {
Runtime rt = Runtime.getRuntime();
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
msg.append("\n");
msg.append("4-------------------- Virtual Machine Memory stats --------------------");
msg.append("\n");
msg.append(" used memory = ");
msg.append(nf.format(rt.totalMemory() - rt.freeMemory()));
msg.append("\n");
msg.append(" total memory = ");
msg.append(nf.format(rt.totalMemory()));
msg.append("\n");
msg.append(" free memory = ");
msg.append(nf.format(rt.freeMemory()));
msg.append("\n");
msg.append("4------------------------------------------------------------------\n");
msg.append("\n");
msg.append("5-------------------- CONNECTION POOL STATS --------------------\n");
if (apFull != null) {
msg.append(apFull.getApDescription());
} else {
msg.append("ApFull NULL!!");
}
msg.append("\n");
msg.append("5------------------------------------------------------------------\n");
}
return msg.toString();
}
public boolean getDebug() {
return this.debug;
}
public String getDebugFile() {
return this.debugFile;
}
public int getDebugLevel() {
return this.debugLevel;
}
public void handleDebug(Exception exception) {
if (exception instanceof java.sql.SQLException)
handleDebug(exception, 0);
handleDebug(exception, 4);
}
public void handleDebug(Exception exception, int logLevel) {
if (getDebug() && getDebugLevel() >= logLevel) {
String msg = createDebugMessage(logLevel, null, exception, this.apFull);
System.out.print(msg);
writeLog(msg);
if (logLevel == 0) {
if (this.apFull != null)
if (!this.apFull.getDatabase().endsWith("_log"))
Log.addFatal(this.apFull, this.apFull.getReqIpAddress(), this.apFull.getLastUpdId_user(), msg);
sendDebugMailMessage("ablia.jar debug mail - FATAL EXCEPTION", msg);
}
}
}
public void handleDebug(PreparedStatement ps) {
handleDebug(ps, 3);
}
public void handleDebug(PreparedStatement ps, int logLevel) {
if (getDebug() && getDebugLevel() >= logLevel) {
String msg = createDebugMessage(logLevel, ps.toString(), null, this.apFull);
System.out.print(msg);
writeLog(msg);
if (logLevel == 0)
sendDebugMailMessage("ablia.jar debug mail - FATAL PreparedStatement ERROR", msg);
}
}
public void handleDebug(String s) {
handleDebug(s, 4);
}
public void handleDebug(String s, int logLevel) {
if (getDebug() && getDebugLevel() >= logLevel) {
String msg = createDebugMessage(logLevel, s, null, this.apFull);
writeLog(msg);
if (logLevel == 0) {
if (this.apFull != null)
Log.addFatal(this.apFull, this.apFull.getReqIpAddress(), this.apFull.getLastUpdId_user(), msg);
sendDebugMailMessage("ablia.jar debug mail - FATAL MESSAGE ERROR", msg);
}
}
}
public void setDebug(boolean flag) {
this.debug = flag;
}
public void setDebugFile(String string) {
this.debugFile = string;
}
public void setDebugLevel(int i) {
this.debugLevel = i;
}
public synchronized void writeLog(String msg) {
if (getDebug() & ((getDebugFile() != null)) & (getDebugFile().isEmpty() ? false : true))
FileLogger.getInstance(getDebugFile()).writeMessage(msg);
}
private void sendMailMessage(MailProperties prop) {
String subject = null, from = null, cc = null, bcc = null, l_msg = null, l_files = null, l_smtp = getMailSMTPServer();
boolean isHtml = false;
from = prop.getProperty("FROM");
subject = prop.getProperty("SUBJECT");
String to = prop.getProperty("TO");
l_msg = prop.getProperty("MSG");
l_files = prop.getProperty("FILES");
if (prop.getProperty("SMTP") != null)
l_smtp = prop.getProperty("SMTP");
String mailer = "Ablia(c) mail Servlet";
Properties props = System.getProperties();
props.put("mail.smtp.host", l_smtp);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(false);
try {
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, (Address[])InternetAddress.parse(to, false));
if (cc != null)
msg.setRecipients(Message.RecipientType.CC, (Address[])InternetAddress.parse(cc, false));
if (bcc != null)
msg.setRecipients(Message.RecipientType.BCC, (Address[])InternetAddress.parse(bcc, false));
msg.setSubject(subject);
if (l_files == null) {
if (isHtml) {
msg.setDataHandler(new DataHandler(new ByteArrayDataSource(l_msg, "text/html")));
} else {
msg.setText(l_msg);
}
} else {
MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart mbText = new MimeBodyPart();
if (isHtml) {
mbText.setDataHandler(new DataHandler(new ByteArrayDataSource(l_msg, "text/html")));
} else {
mbText.setText(l_msg);
}
mimeMultipart.addBodyPart((BodyPart)mbText);
java.util.StringTokenizer st = new java.util.StringTokenizer(l_files, ",");
while (st.hasMoreElements()) {
MimeBodyPart mbFile = new MimeBodyPart();
FileDataSource fds = new FileDataSource(st.nextToken());
mbFile.setDataHandler(new DataHandler((DataSource)fds));
mbFile.setFileName(fds.getName());
mimeMultipart.addBodyPart((BodyPart)mbFile);
}
msg.setContent((Multipart)mimeMultipart);
}
msg.setHeader("X-Mailer", mailer);
msg.setSentDate(new Date());
Transport.send((Message)msg);
String msgOk = createDebugMessage(4, "Debug mail message sent to " + to, null, this.apFull);
System.out.print(msgOk);
writeLog(msgOk);
} catch (Exception e) {
handleDebug(e, 3);
}
}
private void sendDebugMailMessage(String subject, String l_msg) {
if (getMailFrom().isEmpty() || getMailToDebug().isEmpty() || getMailSMTPServer().isEmpty()) {
String msg = createDebugMessage(3, "Cannot send debug mail message!", null, this.apFull);
System.out.println(msg);
writeLog(msg);
} else {
MailProperties mp = new MailProperties();
mp.setProperty("FROM", getMailFrom());
mp.setProperty("TO", getMailToDebug());
String hostname = "";
try {
InetAddress addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
} catch (UnknownHostException e) {}
mp.setProperty("SUBJECT", String.valueOf(hostname) + " - " + subject);
mp.setProperty("MSG", l_msg);
sendMailMessage(mp);
}
}
protected String getMailSMTPServer() {
if (!getResource("SMTP").equals(""))
return getResource("SMTP");
return "";
}
protected String getMailTo() {
if (!getResource("TO").equals(""))
return getResource("TO");
return "";
}
protected String getMailToDebug() {
if (!getResource("TO_DEBUG").equals(""))
return getResource("TO_DEBUG");
return "";
}
protected String getMailFrom() {
if (!getResource("FROM").equals(""))
return getResource("FROM");
return "";
}
private ResourceBundle getPropertyResource() {
if (this.propertyResource == null)
if (getPropertyFile().isEmpty()) {
this.propertyResource = ResourceBundle.getBundle("debug");
} else {
this.propertyResource = ResourceBundle.getBundle(getPropertyFile());
}
return this.propertyResource;
}
protected String getResource(String key) {
try {
return getPropertyResource().getString(key);
} catch (Exception e) {
handleDebug("Debug: " + e.getMessage() + " . Property file:" + "debug", 3);
return "";
}
}
protected int getResourceInt(String key) {
if (getResource(key).isEmpty())
return 0;
try {
return Integer.parseInt(getResource(key));
} catch (Exception e) {
handleDebug(e, 3);
return 0;
}
}
protected long getResourceLong(String key) {
if (getResource(key).isEmpty())
return 0L;
try {
return Long.parseLong(getResource(key));
} catch (Exception e) {
handleDebug(e, 3);
return 0L;
}
}
protected double getResourceDouble(String key) {
if (getResource(key).isEmpty())
return 0.0D;
try {
return Double.parseDouble(getResource(key));
} catch (Exception e) {
handleDebug(e, 3);
return 0.0D;
}
}
public String getPropertyFile() {
return (this.propertyFile == null) ? "" : this.propertyFile.trim();
}
private String propertyFile = "ablia";
private ResourceBundle propertyResource;
public static final String VERSION_LOG_FILE = "versionLog.txt";
public void setPropertyFile(String propertyFile) {
this.propertyFile = propertyFile;
}
public final String getSoftwareVersion() {
String temp = getSoftwareVersionLog();
if (temp.indexOf("\n") >= 0)
return temp.substring(0, temp.indexOf("\n"));
return temp;
}
public final String getSoftwareVersionLog() {
String packageName = "/" + getClass().getPackage().getName().replace('.', '/') + "/";
return getResourceAsString(String.valueOf(packageName) + "versionLog.txt");
}
public static final String getCallingStackTrace() {
StringBuilder msg = new StringBuilder("Connection Calling Stack Trace:\n");
StringBuilder msgAll = new StringBuilder("Connection Calling Stack Trace (NO DBAdapter class found!):\n");
StackTraceElement[] callingFrame = Thread.currentThread().getStackTrace();
boolean dbAdapterTrovato = false;
boolean dbAdapterSparito = false;
if (callingFrame.length > 0) {
int numRigheDBAdapter = 0;
for (int i = 1; i < callingFrame.length; i++) {
String temp = String.valueOf(callingFrame[i].getClassName()) + "." + callingFrame[i].getMethodName();
msgAll.append(temp);
msgAll.append("\n");
if (temp.indexOf("DBAdapter") > 1)
dbAdapterTrovato = true;
if (dbAdapterTrovato && temp.indexOf("DBAdapter") < 0)
dbAdapterSparito = true;
if (dbAdapterSparito) {
msg.append(temp);
msg.append("\n");
numRigheDBAdapter++;
if (numRigheDBAdapter >= 5)
break;
}
}
}
if (dbAdapterSparito)
return msg.toString();
return msgAll.toString();
}
public static final String getResourceAsString(String resource) {
StringBuilder temp = new StringBuilder();
InputStream input = Debug.class.getResourceAsStream(resource);
BufferedInputStream bis = new BufferedInputStream(input);
byte[] contents = new byte[1024];
int bytesRead = 0;
try {
while ((bytesRead = bis.read(contents)) != -1)
temp.append(new String(contents, 0, bytesRead));
bis.close();
input.close();
} catch (Exception e) {
temp.append("ERROR READING " + resource);
temp.append(e.getMessage());
} finally {
try {
bis.close();
input.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return temp.toString();
}
}

View file

@ -0,0 +1,46 @@
package com.ablia.util;
import java.sql.PreparedStatement;
public interface DebugInterface {
public static final String[] LOG_DESC = new String[] { "FATAL! ", "INFO_1! ", "ERROR! ",
"WARNING! ", "INFO! ", "DEBUG! " };
public static final int LOG_LVL_DEBUG = 5;
public static final int LOG_LVL_ERROR = 2;
public static final int LOG_LVL_FATAL = 0;
public static final int LOG_LVL_INFO1 = 1;
public static final int LOG_LVL_INFORMATION = 4;
public static final int LOG_LVL_WARNING = 3;
boolean getDebug();
String getDebugFile();
int getDebugLevel();
void handleDebug(Exception paramException);
void handleDebug(Exception paramException, int paramInt);
void handleDebug(PreparedStatement paramPreparedStatement);
void handleDebug(PreparedStatement paramPreparedStatement, int paramInt);
void handleDebug(String paramString);
void handleDebug(String paramString, int paramInt);
void setDebug(boolean paramBoolean);
void setDebugFile(String paramString);
void setDebugLevel(int paramInt);
void writeLog(String paramString);
}

View file

@ -0,0 +1,179 @@
package com.ablia.util;
import java.math.BigDecimal;
public class DoubleOperator {
private BigDecimal value;
public DoubleOperator() {
setValue(new BigDecimal("0"));
}
public DoubleOperator(double l_value) {
setValue(new BigDecimal(String.valueOf(l_value)));
}
public DoubleOperator(String l_value) {
setValue(new BigDecimal(l_value));
}
public DoubleOperator(float l_value) {
setValue(new BigDecimal(String.valueOf(l_value)));
}
public DoubleOperator(double l_value, int l_scale, int l_round) {
setValue(new BigDecimal(String.valueOf(l_value)));
setScale(l_scale, l_round);
}
public void add(float l_value) {
add(String.valueOf(l_value));
}
public void add(double l_value) {
add(String.valueOf(l_value));
}
public void add(long l_value) {
add(String.valueOf(l_value));
}
public void add(int l_value) {
add(String.valueOf(l_value));
}
private void add(String l_value) {
BigDecimal temp = new BigDecimal(l_value);
setValue(getValue().add(temp));
}
public void add(DoubleOperator l_value) {
add(l_value.getResult());
}
public void divide(double l_value) {
BigDecimal temp = new BigDecimal(String.valueOf(l_value));
setValue(getValue().divide(temp, 5));
}
public void divide(float l_value) {
BigDecimal temp = new BigDecimal(String.valueOf(l_value));
setValue(getValue().divide(temp, 5));
}
public void divide(double l_value, int l_scale, int l_round) {
divide(String.valueOf(l_value), l_scale, l_round);
}
public void divide(float l_value, int l_scale, int l_round) {
divide(String.valueOf(l_value), l_scale, l_round);
}
public void divide(int l_value, int l_scale, int l_round) {
divide(String.valueOf(l_value), l_scale, l_round);
}
public void divide(long l_value, int l_scale, int l_round) {
divide(String.valueOf(l_value), l_scale, l_round);
}
public void divide(DoubleOperator l_value) {
divide(l_value.getResult());
}
private void divide(String l_value, int l_scale, int l_round) {
BigDecimal temp = new BigDecimal(l_value);
setValue(getValue().divide(temp, l_scale, l_round));
}
public double getResult() {
return getValue().doubleValue();
}
public BigDecimal getValue() {
return (this.value == null) ? new BigDecimal("0,0") : this.value;
}
public void movePointLeft(int n) {
setValue(getValue().movePointLeft(n));
}
public void movePointRight(int n) {
setValue(getValue().movePointRight(n));
}
public void multiply(double l_value) {
multiply(String.valueOf(l_value));
}
public void multiply(float l_value) {
multiply(String.valueOf(l_value));
}
public void multiply(int l_value) {
multiply(String.valueOf(l_value));
}
public void multiply(long l_value) {
multiply(String.valueOf(l_value));
}
public void multiply(DoubleOperator l_value) {
multiply(l_value.getResult());
}
private void multiply(String l_value) {
BigDecimal temp = new BigDecimal(l_value);
setValue(getValue().multiply(temp));
}
public static double round(double doubleValue) {
return round(doubleValue, 2, 5);
}
public static double round(double doubleValue, int decimalPlaces, int roundMethod) {
BigDecimal temp = new BigDecimal(String.valueOf(doubleValue));
temp = temp.movePointRight(decimalPlaces);
switch (roundMethod) {
case 5:
temp = temp.add(new BigDecimal(0.4D));
break;
}
temp = new BigDecimal(temp.longValue());
temp = temp.movePointLeft(2);
return temp.doubleValue();
}
public void setScale(int scale, int round) {
setValue(getValue().setScale(scale, round));
}
private void setValue(BigDecimal newValue) {
this.value = newValue;
}
public void subtract(double l_value) {
subtract(String.valueOf(l_value));
}
private void subtract(String l_value) {
BigDecimal temp = new BigDecimal(String.valueOf(l_value));
setValue(getValue().subtract(temp));
}
public void subtract(float l_value) {
subtract(String.valueOf(l_value));
}
public void subtract(long l_value) {
subtract(String.valueOf(l_value));
}
public void subtract(int l_value) {
subtract(String.valueOf(l_value));
}
public void subtract(DoubleOperator l_value) {
subtract(l_value.getResult());
}
}

View file

@ -0,0 +1,81 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import java.util.Vector;
public class FileDb extends File {
private boolean orderedFile;
public FileDb(File arg0, String arg1) {
super(arg0, arg1);
}
public FileDb(String arg0, String arg1) {
super(arg0, arg1);
}
public FileDb(String arg0) {
super(arg0);
}
public FileDb(URI arg0) {
super(arg0);
}
public Vector<String> findrecordByField(int numToken, String theField, long[] columns) {
Vector<String> result = new Vector<>();
try {
BufferedReader br = new BufferedReader(new FileReader(getAbsoluteFile()));
boolean foundField = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(currentLine, columns);
if (st.getToken(numToken).equals(theField)) {
foundField = true;
result.add(currentLine);
continue;
}
if (foundField && isOrderedFile())
break;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Vector<String> findrecordByField(int numToken, String theField, String delimiter) {
Vector<String> result = new Vector<>();
try {
BufferedReader br = new BufferedReader(new FileReader(getAbsoluteFile()));
boolean foundField = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(currentLine, delimiter);
if (st.getToken(numToken).equals(theField)) {
foundField = true;
result.add(currentLine);
continue;
}
if (foundField && isOrderedFile())
break;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean isOrderedFile() {
return this.orderedFile;
}
public void setOrderedFile(boolean orderedFile) {
this.orderedFile = orderedFile;
}
}

View file

@ -0,0 +1,300 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Date;
import java.sql.Time;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Locale;
public class FileFormatter {
private String fileName;
private StringBuffer message;
private String[] parametri;
private boolean questionMark = true;
private Hashtable<String, String> nameParms;
private SimpleDateFormat df;
private NumberFormat nf;
private String textMessage;
public FileFormatter(String l_fileName) {
this.fileName = l_fileName;
}
public FileFormatter(String l_fileName, boolean useQuestionMark) {
this.fileName = l_fileName;
setQuestionMark(useQuestionMark);
}
public FileFormatter(boolean useQuestionMark) {
setQuestionMark(useQuestionMark);
}
public String getMessage() {
loadMessage();
if (this.message != null) {
String s = this.message.toString();
if (isQuestionMark()) {
for (int i = 0; i < this.parametri.length; i++)
s = String.valueOf(s.substring(0, s.indexOf('?'))) + this.parametri[i] + s.substring(s.indexOf('?') + 1, s.length());
return s;
}
int currentIndex = 0;
String parmKey = "";
String parm = "";
int startIndex;
while ((startIndex = s.indexOf("<%=", currentIndex)) != -1) {
int endIndex = s.indexOf("%>", startIndex + 3);
parmKey = s.substring(startIndex + 3, endIndex).trim();
if (getNameParms().containsKey(parmKey) && !getNameParms().get(parmKey).isEmpty()) {
parm = getNameParms().get(parmKey);
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 2, s.length());
int i;
if ((i = s.indexOf("<ab:if " + parmKey + ">")) != -1) {
int endDelIndex = i + parmKey.length() + 8;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
i = s.indexOf("</ab:if>", i);
endDelIndex = i + 8;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
}
continue;
}
int startDelIndex;
if ((startDelIndex = s.indexOf("<ab:if " + parmKey + ">")) != -1) {
int endDelIndex = s.indexOf("</ab:if>", startIndex + 3);
s = String.valueOf(s.substring(0, startDelIndex)) + s.substring(endDelIndex + 8, s.length());
continue;
}
parm = "";
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 2, s.length());
}
return s;
}
return null;
}
public String getMessageForJsp() {
loadMessage();
if (this.message != null) {
String s = this.message.toString();
if (isQuestionMark()) {
for (int i = 0; i < this.parametri.length; i++)
s = String.valueOf(s.substring(0, s.indexOf('?'))) + this.parametri[i] + s.substring(s.indexOf('?') + 1, s.length());
return s;
}
int currentIndex = 0;
String parmKey = "";
String parm = "";
int startIndex;
while ((startIndex = s.indexOf("<?=", currentIndex)) != -1) {
int endIndex = s.indexOf("?>", startIndex + 3);
parmKey = s.substring(startIndex + 3, endIndex).trim();
if (getNameParms().containsKey(parmKey) && !getNameParms().get(parmKey).isEmpty()) {
parm = getNameParms().get(parmKey);
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 2, s.length());
int i;
if ((i = s.indexOf("<ab:if " + parmKey + ">")) != -1) {
int endDelIndex = i + parmKey.length() + 8;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
i = s.indexOf("</ab:if>", i);
endDelIndex = i + 8;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
}
continue;
}
int startDelIndex;
if ((startDelIndex = s.indexOf("<ab:if " + parmKey + ">")) != -1) {
int endDelIndex = s.indexOf("</ab:if>", startIndex + 3);
s = String.valueOf(s.substring(0, startDelIndex)) + s.substring(endDelIndex + 8, s.length());
continue;
}
parm = "";
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 2, s.length());
}
return s;
}
return null;
}
public boolean isQuestionMark() {
return this.questionMark;
}
public static void main(String[] args) {
FileFormatter mailmessageformatter = new FileFormatter("C:/Ablia/work/Spagnesi/web3/mailMessage/checkOut.txt");
mailmessageformatter.setString(1, "primo campo");
mailmessageformatter.setString(2, "secondo campo");
mailmessageformatter.setString(3, "terzo campo");
System.out.println(mailmessageformatter.getMessage());
}
private void readFileMessage() {
try {
BufferedReader bufferedreader = new BufferedReader(new FileReader(this.fileName));
this.message = new StringBuffer();
String s;
while ((s = bufferedreader.readLine()) != null) {
this.message.append(s);
this.message.append("\n");
}
bufferedreader.close();
if (isQuestionMark()) {
int i = 0;
for (int j = 0; j < this.message.length(); j++) {
if (this.message.charAt(j) == '?')
i++;
}
this.parametri = new String[i];
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
public void setQuestionMark(boolean newQuestionMark) {
this.questionMark = newQuestionMark;
}
public void setString(int i, String s) {
this.parametri[i - 1] = s;
}
public void setString(String attributeName, StringBuffer s) {
setString(attributeName, s.toString());
}
public void setString(int i, StringBuffer s) {
setString(i, s.toString());
}
public void setString(String attributeName, String s) {
getNameParms().put(attributeName, s);
}
public void setDate(String attributeName, Date d) {
setString(attributeName, getDf().format(d));
}
public void setTime(String attributeName, Time d) {
setString(attributeName, getDf().format(d));
}
public void setTime(String attributeName, Date d) {
if (d != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String temp = String.valueOf(cal.get(11)) + ":" + cal.get(12);
setString(attributeName, temp);
}
}
public void setLong(String attributeName, long d) {
setString(attributeName, String.valueOf(d));
}
public void setDouble(String attributeName, double d) {
setString(attributeName, getNf().format(d));
}
public SimpleDateFormat getDf() {
if (this.df == null)
this.df = new SimpleDateFormat("dd/MM/yyyy");
return this.df;
}
public NumberFormat getNf() {
if (this.nf == null) {
this.nf = NumberFormat.getInstance(Locale.ITALY);
this.nf.setMaximumFractionDigits(2);
this.nf.setMinimumFractionDigits(2);
}
return this.nf;
}
public String getFileName() {
return this.fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getTextMessage() {
return (this.textMessage == null) ? "" : this.textMessage;
}
public void setTextMessage(String textMessage) {
this.textMessage = textMessage;
}
private void loadMessage() {
if (this.message == null)
if (getFileName() != null) {
readFileMessage();
} else {
this.message = new StringBuffer(getTextMessage());
}
}
public void setDf(SimpleDateFormat df) {
this.df = df;
}
public Hashtable<String, String> getNameParms() {
if (this.nameParms == null)
this.nameParms = new Hashtable<>();
return this.nameParms;
}
public String getMessageGtLt() {
loadMessage();
if (this.message != null) {
String s = this.message.toString();
if (isQuestionMark()) {
for (int i = 0; i < this.parametri.length; i++)
s = String.valueOf(s.substring(0, s.indexOf('?'))) + this.parametri[i] + s.substring(s.indexOf('?') + 1, s.length());
return s;
}
int currentIndex = 0;
String parmKey = "";
String parm = "";
int startIndex;
while ((startIndex = s.indexOf("&lt;%=", currentIndex)) != -1) {
int endIndex = s.indexOf("%&gt;", startIndex + 6);
parmKey = s.substring(startIndex + 6, endIndex).trim();
if (getNameParms().containsKey(parmKey) && !getNameParms().get(parmKey).isEmpty()) {
parm = getNameParms().get(parmKey);
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 5, s.length());
int i;
if ((i = s.indexOf("&lt;ab:if " + parmKey + "&gt;")) != -1) {
int endDelIndex = i + parmKey.length() + 11;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
i = s.indexOf("&lt;/ab:if&gt;", i);
endDelIndex = i + 11;
s = String.valueOf(s.substring(0, i)) + s.substring(endDelIndex, s.length());
}
continue;
}
int startDelIndex;
if ((startDelIndex = s.indexOf("&lt;ab:if " + parmKey + "&gt;")) != -1) {
int endDelIndex = s.indexOf("&lt;/ab:if&gt;", startIndex + 5);
s = String.valueOf(s.substring(0, startDelIndex)) + s.substring(endDelIndex + 11, s.length());
continue;
}
parm = "";
s = String.valueOf(s.substring(0, startIndex)) + parm + s.substring(endIndex + 5, s.length());
}
return s;
}
return null;
}
}

View file

@ -0,0 +1,100 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Vector;
public class FileIniManager {
private String fileName;
private PrintWriter out;
public FileIniManager(String s) {
this.fileName = s;
}
public boolean deleteProperty(String s) {
return writeProperty(s, "");
}
private PrintWriter getOut() {
if (this.out == null)
try {
this.out = new PrintWriter(new BufferedWriter(new FileWriter(this.fileName)));
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
return this.out;
}
public static void main(String[] args) {
FileIniManager fileinimanager = new FileIniManager("c:/00/aa.ini");
System.out.println("LETTURA1 " + fileinimanager.readProperty("MaxDoc"));
fileinimanager.writeProperty("MaxDoc", "ANDREA");
System.out.println("LETTURA DOPO WRITE " + fileinimanager.readProperty("MaxDoc"));
fileinimanager.deleteProperty("MaxDoc");
System.out.println("Dopo cancella: " + fileinimanager.readProperty("MaxDoc"));
fileinimanager.writeProperty("MaxDoc", "111 riwrite");
System.out.println("Dopo riwrite: " + fileinimanager.readProperty("MaxDoc"));
}
private boolean outClose() {
try {
getOut().flush();
getOut().close();
this.out = null;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return false;
}
return true;
}
public String readProperty(String s) {
try {
BufferedReader bufferedreader = new BufferedReader(new FileReader(this.fileName));
String s1;
while ((s1 = bufferedreader.readLine()) != null) {
if (s1.startsWith(String.valueOf(s) + "="))
return s1.substring(s.length() + 1);
}
bufferedreader.close();
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
return "";
}
public boolean writeProperty(String s, String s1) {
try {
BufferedReader bufferedreader = new BufferedReader(new FileReader(this.fileName));
Vector<String> vector = new Vector();
boolean flag = false;
String s2;
while ((s2 = bufferedreader.readLine()) != null) {
if (s2.startsWith(String.valueOf(s) + "=")) {
if (!s1.isEmpty())
vector.addElement(String.valueOf(s) + "=" + s1);
flag = true;
continue;
}
vector.addElement(s2);
}
bufferedreader.close();
if (!flag && !s1.isEmpty())
vector.addElement(String.valueOf(s) + "=" + s1);
if (flag || !s1.isEmpty()) {
for (Enumeration<String> enumeration = vector.elements(); enumeration.hasMoreElements(); getOut().println(enumeration.nextElement()));
outClose();
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
return false;
}
}

View file

@ -0,0 +1,90 @@
package com.ablia.util;
import java.util.Hashtable;
import java.util.LinkedList;
public class FileLogger implements Runnable {
private static final long TIMEWAITMAX = 10000L;
private LinkedList<String> queue = new LinkedList<>();
private boolean active = true;
private String fileName;
private static Hashtable<String, FileLogger> ht_files;
private FileLogger(String fn) {
setFileName(fn);
}
public static synchronized FileLogger getInstance(String fn) {
if (getHt_files().containsKey(fn))
return getHt_files().get(fn);
FileLogger fl = new FileLogger(fn);
Thread thread = new Thread(fl);
thread.start();
getHt_files().put(fn, fl);
return fl;
}
public static synchronized void closeInstance(String fn) {
if (getHt_files().containsKey(fn)) {
FileLogger fl = getHt_files().get(fn);
fl.active = false;
fl.notify();
fl = null;
getHt_files().remove(fn);
}
}
public void writeMessage(String msg) {
synchronized (this.queue) {
this.queue.addLast(msg);
}
}
public synchronized void run() {
long t = 1000L;
while (this.active) {
while (this.queue.size() == 0) {
try {
wait(t);
if (t < 10000L)
t += 1000L;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writeLog(this.queue.removeFirst());
t = 1000L;
}
}
private void writeLog(String msg) {
try {
FileWr fw = new FileWr(getFileName());
fw.writeLine(msg);
fw.closeFile();
fw = null;
} catch (Exception e) {
System.out.println("Cannot write to " + getFileName() + ": " +
e.getMessage());
e.printStackTrace(System.out);
}
}
private static Hashtable<String, FileLogger> getHt_files() {
if (ht_files == null)
ht_files = new Hashtable<>();
return ht_files;
}
public String getFileName() {
return this.fileName;
}
private void setFileName(String fileName) {
this.fileName = fileName;
}
}

View file

@ -0,0 +1,201 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class FileMailingListManager extends Debug {
private static final int ACTION_ADD = 1;
private static final int ACTION_REMOVE = 2;
private static Hashtable ht_files;
private String fileName;
private PrintWriter out;
public static void main(String[] args) {}
private boolean active = true;
private static final int ACTION_REBUILD = 9;
private FileMailingListManager(String s) {
this.fileName = s;
}
public boolean addEmail(String email) {
return updateMailingListFile(email, 1);
}
public boolean rebuild(Vector vec) {
return updateMailingListFile(vec, 9);
}
private PrintWriter getOut() {
if (this.out == null)
try {
this.out = new PrintWriter(new BufferedWriter(new FileWriter(
this.fileName)));
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
return this.out;
}
private boolean outClose() {
try {
getOut().flush();
getOut().close();
this.out = null;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return false;
}
return true;
}
public boolean removeEmail(String email) {
return updateMailingListFile(email, 2);
}
private synchronized boolean updateMailingListFile(Object obj, int action) {
int numEmail = 0;
int numEmailDopo = 0;
if (action == 1) {
try {
String email = (String)obj;
boolean flag = false;
Vector<String> vector = new Vector();
if (new File(this.fileName).exists()) {
BufferedReader bufferedreader = new BufferedReader(
new FileReader(this.fileName));
String s2;
while ((s2 = bufferedreader.readLine()) != null &&
!flag) {
numEmail++;
if (s2.startsWith(email)) {
flag = true;
continue;
}
vector.addElement(s2);
}
bufferedreader.close();
}
if (!flag) {
vector.addElement(email);
Enumeration<String> enumeration = vector.elements();
for (; enumeration.hasMoreElements(); getOut().println(
enumeration.nextElement()))
numEmailDopo++;
outClose();
String msg = "MAILING LIST SUBSCRIBE:\nNum Email prima: " +
numEmail + "\nNum Email dopo: " + numEmailDopo +
"\nemail:" + email;
System.out.println(msg);
if (numEmail != numEmailDopo - 1) {
String msgE = "MAILING LIST SUBSCRIBE ERROR:\nNum Email prima: " +
numEmail +
"\nNum Email dopo: " +
numEmailDopo + "\nemail:" + email;
System.out.println(msgE);
handleDebug(msgE, 0);
}
}
} catch (Exception exception) {
handleDebug(exception, 0);
return false;
}
return true;
}
if (action == 2) {
try {
String email = (String)obj;
Vector<String> vector = new Vector();
boolean flag = false;
if (new File(this.fileName).exists()) {
BufferedReader bufferedreader = new BufferedReader(
new FileReader(this.fileName));
String s2;
while ((s2 = bufferedreader.readLine()) != null) {
numEmail++;
if (s2.startsWith(email)) {
flag = true;
continue;
}
vector.addElement(s2);
}
bufferedreader.close();
}
if (flag) {
Enumeration<String> enumeration = vector.elements();
for (; enumeration.hasMoreElements(); getOut().println(
enumeration.nextElement()))
numEmailDopo++;
outClose();
String msg = "MAILING LIST CANCELLAZIONE:\nNum Email prima: " +
numEmail +
"\nNum Email dopo: " +
numEmailDopo +
"\nemail:" + email;
System.out.println(msg);
if (numEmail != numEmailDopo + 1) {
String msgE = "MAILING LIST CANCELLAZIONE ERROR:\nNum Email prima: " +
numEmail +
"\nNum Email dopo: " +
numEmailDopo + "\nemail:" + email;
System.out.println(msgE);
handleDebug(msgE, 0);
}
}
} catch (Exception exception) {
handleDebug(exception, 0);
return false;
}
return true;
}
if (action == 9) {
Vector vector = (Vector)obj;
Enumeration<String> enumeration = vector.elements();
for (; enumeration.hasMoreElements(); getOut().println(
enumeration.nextElement()))
numEmailDopo++;
outClose();
return true;
}
return false;
}
public static synchronized void closeInstance(String fn) {
if (getHt_files().containsKey(fn)) {
FileMailingListManager fl = (FileMailingListManager)getHt_files()
.get(fn);
fl.active = false;
fl.notify();
fl = null;
getHt_files().remove(fn);
}
}
private static Hashtable getHt_files() {
if (ht_files == null)
ht_files = new Hashtable();
return ht_files;
}
public static synchronized FileMailingListManager getInstance(String fn) {
if (getHt_files().containsKey(fn))
return (FileMailingListManager)getHt_files().get(fn);
FileMailingListManager fl = new FileMailingListManager(fn);
getHt_files().put(fn, fl);
return fl;
}
}

View file

@ -0,0 +1,121 @@
package com.ablia.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
public class FileWr {
private static final String DOS_NL = "\r";
private PrintWriter out;
private String csn = "ISO-8859-1";
private String fileName;
private boolean append;
private boolean dosNl = false;
public FileWr(String s, String csn) {
this.append = true;
this.csn = csn;
this.fileName = s;
}
public FileWr(String s, boolean appendFlag) {
this.append = true;
setAppend(appendFlag);
if (!appendFlag)
new File(s).delete();
this.fileName = s;
}
public FileWr(String s) {
this.append = true;
this.fileName = s;
}
public FileWr(String s, String csn, boolean appendFlag) {
this.append = true;
setAppend(appendFlag);
this.csn = csn;
if (!appendFlag)
new File(s).delete();
this.fileName = s;
}
public void closeFile() {
try {
if (this.out != null) {
this.out.flush();
this.out.close();
this.out = null;
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
protected void finalize() throws Throwable {
if (this.out != null) {
this.out.flush();
this.out.close();
}
this.out = null;
}
private PrintWriter getOut() {
if (this.out == null)
try {
this.out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(this.fileName, true), Charset.forName(this.csn).newEncoder())));
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
return this.out;
}
public boolean isAppend() {
return this.append;
}
public void setAppend(boolean flag) {
this.append = flag;
}
public synchronized boolean writeLine(String s) {
try {
if (getOut() != null) {
if (this.dosNl) {
getOut().println(String.valueOf(s) + "\r");
} else {
getOut().println(s);
}
return true;
}
return false;
} catch (Exception exception) {
System.out.println("Errore FileWriter:" + exception.getMessage());
exception.printStackTrace(System.out);
closeFile();
return false;
}
}
public String getFileName() {
return this.fileName;
}
public boolean isDosNl() {
return this.dosNl;
}
public void setDosNl(boolean dosNl) {
this.dosNl = dosNl;
}
}

View file

@ -0,0 +1,9 @@
package com.ablia.util;
public class FixedValueRecord {
public FixedValueRecord(String l_record, String l_fixedValues) {}
public String getColumn(int n_col) {
return "";
}
}

View file

@ -0,0 +1,40 @@
package com.ablia.util;
import java.util.Hashtable;
public class FormFieldsProperty {
private Hashtable fieldPropertyHT;
public static final int FIELD_STD = 0;
public static final int FIELD_MANDATORY = 1;
public static final int FIELD_READONLY = 2;
private Hashtable getFieldPropertyHT() {
if (this.fieldPropertyHT == null)
this.fieldPropertyHT = new Hashtable();
return this.fieldPropertyHT;
}
public void putFieldProperty(String l_name, int l_value) {
getFieldPropertyHT().put(l_name, new Integer(l_value));
}
public int getFieldProperty(String l_name) {
if (getFieldPropertyHT().containsKey(l_name))
return (Integer)getFieldPropertyHT().get(l_name);
return 0;
}
public String getFieldClass(String l_name) {
int prop = getFieldProperty(l_name);
switch (prop) {
case 1:
return " class=\"mandatoryField\" ";
case 2:
return " class=\"readonlyField\" readonly ";
}
return "";
}
}

View file

@ -0,0 +1,45 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class GoogleTranslator {
private static final String GT_GS_URL = "https://script.google.com/macros/s/AKfycbwv9Qh0B_KbcoBeYDwxe9Am_4KH5AGBYymXS36-3e0RVzWv2xzQ/exec";
private static final String LOCALE_CN = "cn";
private static final String LOCALE_ZH_CN = "zh-cn";
public static final String translate(String sentence, String sourceLang, String targetLang) {
try {
if (targetLang.equals("cn"))
targetLang = "zh-cn";
StringBuilder urlStr = new StringBuilder("https://script.google.com/macros/s/AKfycbwv9Qh0B_KbcoBeYDwxe9Am_4KH5AGBYymXS36-3e0RVzWv2xzQ/exec");
urlStr.append("?q=");
urlStr.append(URLEncoder.encode(sentence, "UTF-8"));
urlStr.append("&target=");
urlStr.append(targetLang);
urlStr.append("&source=");
urlStr.append(sourceLang);
URL url = new URL(urlStr.toString());
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
System.out.println(translate("Oggi è una bella giornata perché sembra che tutto funzioni", "it", "zh-cn"));
}
}

View file

@ -0,0 +1,38 @@
package com.ablia.util;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class HashMapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return ((Comparable)o1.getValue()).compareTo(o2.getValue());
}
});
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
result.put(entry.getKey(), entry.getValue());
return result;
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortReverseByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return ((Comparable)o1.getValue()).compareTo(o2.getValue());
}
});
List<Map.Entry<K, V>> reverseList = Lists.reverse(list);
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : reverseList)
result.put(entry.getKey(), entry.getValue());
return result;
}
}

View file

@ -0,0 +1,108 @@
package com.ablia.util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageConverter {
public static final void whiteToTransparentPng(String sourceFile, String targetPngFile) {
try {
File in = new File(sourceFile);
BufferedImage source = ImageIO.read(in);
int color = source.getRGB(0, 0);
Image imageWithTransparency = makeColorTransparent(source, new Color(color));
BufferedImage transparentImage = imageToBufferedImage(imageWithTransparency);
File out = new File(targetPngFile);
ImageIO.write(transparentImage, "PNG", out);
} catch (Exception e) {
e.printStackTrace();
}
}
public static final void colorToGrayscale(String sourceFile, String targetFile) {
try {
File input = new File(sourceFile);
BufferedImage image = ImageIO.read(input);
int width = image.getWidth();
int height = image.getHeight();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color c = new Color(image.getRGB(j, i));
int red = (int)((double)c.getRed() * 0.21D);
int green = (int)((double)c.getGreen() * 0.72D);
int blue = (int)((double)c.getBlue() * 0.07D);
int sum = red + green + blue;
Color newColor = new Color(sum, sum, sum);
image.setRGB(j, i, newColor.getRGB());
}
}
File output = new File(targetFile);
ImageIO.write(image, "png", output);
} catch (Exception e) {
e.printStackTrace();
}
}
public static final void colorToBW(String sourceFile, String targetFile) {
try {
File input = new File(sourceFile);
BufferedImage image = ImageIO.read(input);
int width = image.getWidth();
int height = image.getHeight();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color newColor;
Color c = new Color(image.getRGB(j, i));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
int sum = red + green + blue;
if (sum <= 200) {
newColor = Color.black;
} else {
newColor = Color.white;
}
image.setRGB(j, i, newColor.getRGB());
}
}
File output = new File(targetFile);
ImageIO.write(image, "png", output);
} catch (Exception e) {
e.printStackTrace();
}
}
private static BufferedImage imageToBufferedImage(Image image) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), 2);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
return bufferedImage;
}
private static Image makeColorTransparent(BufferedImage im, Color color) {
ImageFilter filter = new RGBImageFilter(color) {
public int markerRGB;
{
this.markerRGB = this$0.getRGB() | 0xFFFFFFFF;
}
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == this.markerRGB)
return 0xFFFFFF & rgb;
return rgb;
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
}

View file

@ -0,0 +1,91 @@
package com.ablia.util;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageTool {
public static final boolean scaleImageW(String fullImageName, String scaledPrefix, int scaledWidth) {
return scaleImage(fullImageName, scaledPrefix, scaledWidth, 0);
}
private static final boolean isFileExist(String fileName) {
return new File(fileName).exists();
}
public boolean scaleImageFactor(String fullImageName, String scaledPrefix, int scaledFactor) {
return scaleImage(fullImageName, scaledPrefix, 0, scaledFactor);
}
private static final boolean scaleImage(String fullImageName, String scaledPrefix, int scaledWidth, int scaledFactor) {
try {
int sw, sh;
int imgIdx = fullImageName.lastIndexOf('/') + 1;
String fullImageNameScaled = String.valueOf(fullImageName.substring(0, imgIdx)) +
scaledPrefix +
fullImageName.substring(imgIdx, fullImageName.length());
if (isFileExist(fullImageNameScaled)) {
BufferedImage bufferedImage1 = ImageIO.read(new File(fullImageName));
BufferedImage scaledImage = ImageIO.read(new File(
fullImageNameScaled));
int i = bufferedImage1.getWidth();
h = bufferedImage1.getHeight();
sw = scaledImage.getWidth();
sh = scaledImage.getHeight();
if (scaledWidth == 0) {
int sf = 100 / scaledFactor;
if (i / sw == sf)
return true;
} else {
if (scaledWidth >= i)
return false;
if (scaledWidth == sw)
return true;
}
}
BufferedImage srcImage = ImageIO.read(new File(fullImageName));
int w = srcImage.getWidth(), h = srcImage.getHeight();
if (scaledWidth == 0) {
int sf = 100 / scaledFactor;
sw = w / sf;
sh = h / sf;
} else {
sw = scaledWidth;
sh = scaledWidth * h / w;
}
Image rescaled = srcImage.getScaledInstance(sw, sh,
16);
BufferedImage biRescaled = toBufferedImage(rescaled,
1);
File fullImageNameScaledDir = new File(String.valueOf(fullImageName.substring(0,
imgIdx)) +
scaledPrefix);
boolean dirOk = true;
if (!fullImageNameScaledDir.exists())
dirOk = fullImageNameScaledDir.mkdirs();
if (dirOk) {
ImageIO.write(biRescaled, "jpeg",
new File(fullImageNameScaled));
System.out.println("If_IMG immagine scalata creata: w=" +
sw + " h=" + sh + " imgname=" + fullImageNameScaled);
}
} catch (Exception e) {
System.out.println("If_IMG ECCEZIONE " + e.getMessage());
e.printStackTrace(System.out);
return false;
}
return true;
}
private static BufferedImage toBufferedImage(Image image, int type) {
int w = image.getWidth(null);
int h = image.getHeight(null);
BufferedImage result = new BufferedImage(w, h, type);
Graphics2D g = result.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
}

View file

@ -0,0 +1,69 @@
package com.ablia.util;
import com.ablia.db.ResParm;
import java.util.Hashtable;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LdapCredential {
private String serverUrl;
private long serverport;
private String domainName;
public LdapCredential(String serverUrl, String domainName) {
this.serverUrl = serverUrl;
this.domainName = domainName;
}
public ResParm checkDomainUser(String username, String password) {
ResParm rp = new ResParm(true, "Autenticazione ldap avvenuta correttamente");
try {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.provider.url", "ldap://" + getServerUrl() + ":" + getServerport());
env.put("java.naming.security.authentication", "simple");
env.put("java.naming.security.principal", String.valueOf(getDomainName()) + "\\" + username);
env.put("java.naming.security.credentials", password);
DirContext ctx = new InitialDirContext(env);
boolean result = (ctx != null);
if (ctx != null)
ctx.close();
if (!result) {
rp.setStatus(false);
rp.setMsg("Errore autenticazione ldap di " + username);
}
return rp;
} catch (Exception e) {
rp.setException(e);
rp.setStatus(false);
e.printStackTrace();
return rp;
}
}
public String getServerUrl() {
return this.serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public long getServerport() {
return (this.serverport == 0L) ? 389L : this.serverport;
}
public void setServerport(long serverport) {
this.serverport = serverport;
}
public String getDomainName() {
return this.domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}

View file

@ -0,0 +1,91 @@
package com.ablia.util;
import com.ablia.db.DBAdapter;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class NumbersToImage {
private String imageDir;
private static final String[] N_FILE = new String[] {
"0.png", "1.png", "2.png",
"3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png",
"piu.png", "spazio.png" };
private static final String PLUS_10 = "+";
private static final String SPACE_11 = " ";
private static BufferedImage[] img = new BufferedImage[N_FILE.length];
public static void main(String[] args) {
String imageDir = "/Users/acolzi/Downloads/numbers/";
String resultImg = "/Users/acolzi/Downloads/numbers/risultato.png";
NumbersToImage in = new NumbersToImage(imageDir);
in.getImage("+39 3232 23232323", resultImg);
}
public NumbersToImage(String imageNumberDir) {
setImageDir(imageNumberDir);
}
public boolean getImage(String theNumber, String imgFileName) {
try {
int width = img[0].getWidth(null);
int height = img[0].getHeight(null);
StringBuilder sb = new StringBuilder();
theNumber = theNumber.trim();
for (int i = 0; i < theNumber.length(); i++) {
String theChar = theNumber.substring(i, i + 1);
if (DBAdapter.isNumeric(theChar) || theChar.equals("+") ||
theChar.equals(" "));
sb.append(theChar);
}
String sNumber = sb.toString();
int imgWidth = width * sNumber.length();
BufferedImage targetImage = new BufferedImage(imgWidth, height,
img[0].getType());
Graphics2D g = targetImage.createGraphics();
int currentXPosition = 0;
for (int j = 0; j < sNumber.length(); j++) {
int currentNumber;
String theChar = sNumber.substring(j, j + 1);
if (theChar.equals("+")) {
currentNumber = 10;
} else if (theChar.equals(" ")) {
currentNumber = 11;
} else {
currentNumber =
Integer.valueOf(sNumber.substring(j, j + 1));
}
g.drawImage(img[currentNumber], currentXPosition, 0, null);
currentXPosition += width;
}
g.dispose();
g = null;
File resultFile = new File(imgFileName);
resultFile.delete();
ImageIO.write(targetImage, "png", resultFile);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private String getImageDir() {
return this.imageDir;
}
private void setImageDir(String imageDir) {
this.imageDir = imageDir;
try {
for (int i = 0; i < N_FILE.length; i++)
img[i] = ImageIO.read(new File(String.valueOf(getImageDir()) + N_FILE[i]));
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,27 @@
package com.ablia.util;
import java.io.OutputStream;
import java.io.PrintStream;
public class Out extends PrintStream {
private StringBuffer msg = new StringBuffer();
public Out(OutputStream arg0, boolean arg1) {
super(arg0, arg1);
}
public Out(OutputStream arg0) {
super(arg0);
}
public void println(String arg0) {
this.msg.append(arg0);
this.msg.append("\n");
}
public String getMsg() {
return this.msg.toString();
}
public void println(Object arg0) {}
}

View file

@ -0,0 +1,178 @@
package com.ablia.util;
import com.ablia.db.ApplParmFull;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import java.awt.Color;
import java.util.Locale;
public class PdfFontFactory {
private static PdfFontFactory pdfFontFactoryInstance;
private ApplParmFull apFull;
public static final Font PDF_fGrandissimo = new Font(2, 14.0F, 0);
public static final Font PDF_fGrandissimoXB = new Font(2, 16.0F, 1);
public static final String PATH_TTF_FONT_REL_DOCBASE = "admin/_V4/_font/";
private static final String FONT_CHINA = "arialuni.ttf";
public static final int SIZE_GRANDISSIMO = 14;
public static final int SIZE_GRANDE = 12;
public static final int SIZE_MEDIO = 10;
public static final int SIZE_PICCOLO = 8;
public static final int SIZE_PICCOLISSIMO = 7;
public static final int SIZE_PICOLISSIMO_X = 6;
public static final Font PDF_fGrandissimoX = new Font(2, 16.0F, 0);
public static final Font PDF_fGrandissimoB = new Font(2, 14.0F, 1);
public static final Font PDF_fGrandissimoBianco = new Font(2, 14.0F, 1, Color.white);
public static final Font PDF_fGrandissimoBlu = new Font(2, 14.0F, 1, Color.blue);
public static final Font PDF_fGrandissimoRouge = new Font(2, 14.0F, 1, Color.magenta);
public static final Font PDF_fGrande = new Font(2, 12.0F, 0);
public static final Font PDF_fGrandeB = new Font(2, 12.0F, 1);
public static final Font PDF_fGrandeBianco = new Font(2, 14.0F, 1, Color.white);
public static final Font PDF_fGrandeBlu = new Font(2, 12.0F, 1, Color.blue);
public static final Font PDF_fGrandeRouge = new Font(2, 12.0F, 1, Color.magenta);
public static final Font PDF_fIntestazione = new Font(2, 14.0F, 1);
public static final Font PDF_fMedio = new Font(2, 10.0F, 0);
public static final Font PDF_fMedioB = new Font(2, 10.0F, 1);
public static final Font PDF_fMedioBianco = new Font(2, 10.0F, 1, Color.white);
public static final Font PDF_fMedioBlu = new Font(2, 10.0F, 0, Color.blue);
public static final Font PDF_fMedioRosso = new Font(2, 10.0F, 0, Color.red);
public static final Font PDF_fMedioRouge = new Font(2, 10.0F, 0, Color.magenta);
public static final Font PDF_fPiccolissimo = new Font(2, 7.0F, 0);
public static final Font PDF_fPiccolissimo6 = new Font(2, 6.0F, 0);
public static final Font PDF_fPiccolissimoB = new Font(2, 7.0F, 1);
public static final Font PDF_fPiccolo = new Font(2, 8.0F, 0);
public static final Font PDF_fPiccoloB = new Font(2, 8.0F, 1);
public static final Font PDF_fPiccoloBianco = new Font(2, 8.0F, 1, Color.white);
public static final Font PDF_fPiccoloBlu = new Font(2, 8.0F, 0, Color.blue);
public static final Font PDF_fPiccoloRosso = new Font(2, 8.0F, 0, Color.red);
public static final Font PDF_H_Grandissimo = new Font(1, 14.0F, 0);
public static final Font PDF_H_GrandissimoB = new Font(1, 14.0F, 1);
public static final Font PDF_H_GrandissimoBianco = new Font(1, 14.0F, 1, Color.white);
public static final Font PDF_H_GrandissimoBlu = new Font(1, 14.0F, 1, Color.blue);
public static final Font PDF_H_GrandissimoRouge = new Font(1, 14.0F, 1, Color.magenta);
public static final Font PDF_H_Grande = new Font(1, 12.0F, 0);
public static final Font PDF_H_GrandeB = new Font(1, 12.0F, 1);
public static final Font PDF_H_GrandeBianco = new Font(1, 14.0F, 1, Color.white);
public static final Font PDF_H_GrandeBlu = new Font(1, 12.0F, 1, Color.blue);
public static final Font PDF_H_GrandeRouge = new Font(1, 12.0F, 1, Color.magenta);
public static final Font PDF_H_Intestazione = new Font(1, 14.0F, 1);
public static final Font PDF_H_Medio = new Font(1, 10.0F, 0);
public static final Font PDF_H_MedioB = new Font(1, 10.0F, 1);
public static final Font PDF_H_MedioBianco = new Font(1, 10.0F, 1, Color.white);
public static final Font PDF_H_MedioBlu = new Font(1, 10.0F, 0, Color.blue);
public static final Font PDF_H_MedioRosso = new Font(1, 10.0F, 0, Color.red);
public static final Font PDF_H_MedioRouge = new Font(1, 10.0F, 0, Color.magenta);
public static final Font PDF_H_Piccolissimo = new Font(1, 7.0F, 0);
public static final Font PDF_H_Piccolissimo6 = new Font(1, 6.0F, 0);
public static final Font PDF_A_PiccolissimoB = new Font(2, 7.0F, 1);
public static final Font PDF_A_Piccolo = new Font(2, 8.0F, 0);
public static final Font PDF_A_PiccoloB = new Font(2, 8.0F, 1);
public static final Font PDF_A_PiccoloBianco = new Font(2, 8.0F, 1, Color.white);
public static final Font PDF_A_PiccoloBlu = new Font(2, 8.0F, 0, Color.blue);
public static final Font PDF_A_PiccoloRosso = new Font(2, 8.0F, 0, Color.red);
public static final Font PDF_fMedioGrigio = new Font(2, 10.0F, 1, Color.GRAY);
public static final Font PDF_fPiccolissimo4B = new Font(2, 4.0F, 1);
public static final Font PDF_fPiccolissimo5 = new Font(2, 5.0F, 0);
public static final Font PDF_fPiccolissimo6B = new Font(2, 6.0F, 1);
public static final Font PDF_fPiccolissimo4 = new Font(2, 4.0F, 0);
public static final Font PDF_fPiccolissimo5B = new Font(2, 5.0F, 1);
private PdfFontFactory(ApplParmFull l_apFull) {
setApFull(l_apFull);
}
public final Font getPdfFont(Font font, String lang) {
if (lang.toUpperCase().equals(Locale.CHINA.getCountry()))
try {
BaseFont baseFont = BaseFont.createFont(
String.valueOf(getApFull().getParm("DOCBASE").getTesto()) + "admin/_V4/_font/" + "arialuni.ttf", "Identity-H",
true);
Font cnFont = new Font(baseFont, font.getSize(), font.getStyle());
return cnFont;
} catch (Exception e) {
e.printStackTrace();
return font;
}
return font;
}
public static synchronized PdfFontFactory getInstance(ApplParmFull ap) {
if (pdfFontFactoryInstance == null)
pdfFontFactoryInstance = new PdfFontFactory(ap);
return pdfFontFactoryInstance;
}
private ApplParmFull getApFull() {
return this.apFull;
}
private void setApFull(ApplParmFull apFull) {
this.apFull = apFull;
}
}

View file

@ -0,0 +1,50 @@
package com.ablia.util;
import java.security.SecureRandom;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
public class RandomString {
public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public String nextString() {
for (int idx = 0; idx < this.buf.length; idx++)
this.buf[idx] = this.symbols[this.random.nextInt(this.symbols.length)];
return new String(this.buf);
}
public static final String lower = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase(Locale.ROOT);
public static final String digits = "0123456789";
public static final String alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + lower + "0123456789";
private final Random random;
private final char[] symbols;
private final char[] buf;
public RandomString(int length, Random random, String symbols) {
if (length < 1)
throw new IllegalArgumentException();
if (symbols.length() < 2)
throw new IllegalArgumentException();
this.random = Objects.<Random>requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}
public RandomString(int length, Random random) {
this(length, random, alphanum);
}
public RandomString(int length) {
this(length, new SecureRandom());
}
public RandomString() {
this(21);
}
}

View file

@ -0,0 +1,197 @@
package com.ablia.util;
import com.ablia.db.DBAdapter;
import java.util.ArrayList;
public class ReturnItem {
private String returnItems;
private ArrayList<String> returnItemsAL;
private String riValues;
private static String nextField;
private String STND_DELIMIT_TOKEN = "|";
private String NEXT_SELECTED_FIELDS_PREFIX = "NSF";
private static String divList;
public ReturnItem() {}
public ReturnItem(String l_ri) {
setReturnItems(l_ri);
}
public ReturnItem(String l_ri, String l_nextField, String l_divList) {
setReturnItems(l_ri);
setNextField(l_nextField);
setDivList(l_divList);
}
public void addRiValues(double l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(float l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(long l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(Object l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(String l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + (l_values.isEmpty() ? " " : l_values));
}
}
public String getReturnItems() {
return this.returnItems;
}
public String getRi(int l_numb) {
if (l_numb < getReturnItemsAL().size())
return getReturnItemsAL().get(l_numb);
return "";
}
public String getRiValues() {
return (this.riValues == null) ? "" : this.riValues;
}
public String getSelectedKey() {
String res = "";
String temp = DBAdapter.prepareScriptString(getRiValues());
java.util.StringTokenizer st = new java.util.StringTokenizer(temp, this.STND_DELIMIT_TOKEN);
int i = 0;
while (st.hasMoreTokens()) {
String value = st.nextToken().trim();
String returnField = getRi(i).trim();
if (!returnField.isEmpty())
if (res.isEmpty()) {
res = "'" + value + "','" + returnField + "'";
} else {
res = String.valueOf(res) + ",'" + value + "','" + returnField + "'";
}
i++;
}
if (nextField != null && !nextField.equals(""))
res = String.valueOf(res) + ",'" + nextField + "'";
return res;
}
public String getSelectedKeyNoQuot() {
String res = "";
String temp = DBAdapter.prepareScriptString(getRiValues(), false);
java.util.StringTokenizer st = new java.util.StringTokenizer(temp, this.STND_DELIMIT_TOKEN);
int i = 0;
while (st.hasMoreTokens() && !getRi(i).isEmpty()) {
if (res.isEmpty()) {
res = "'" + st.nextToken() + "','" + getRi(i) + "'";
} else {
res = String.valueOf(res) + ",'" + st.nextToken() + "','" + getRi(i) + "'";
}
i++;
}
if (nextField != null && !nextField.equals(""))
res = String.valueOf(res) + ",'" + nextField + "'";
return res;
}
public void setReturnItems(String newReturnItems) {
if (newReturnItems != null && newReturnItems.indexOf(this.NEXT_SELECTED_FIELDS_PREFIX) > 0) {
int idx = newReturnItems.indexOf(this.NEXT_SELECTED_FIELDS_PREFIX);
int riL = newReturnItems.length();
if (idx == 0) {
int firstitemIdx = newReturnItems.indexOf(",");
this.returnItems = newReturnItems.substring(firstitemIdx + 1);
nextField = newReturnItems.substring(this.NEXT_SELECTED_FIELDS_PREFIX.length() + 1, firstitemIdx);
} else {
this.returnItems = newReturnItems.substring(0, idx - 1);
nextField = newReturnItems.substring(this.returnItems.length() + this.NEXT_SELECTED_FIELDS_PREFIX.length() + 2, riL);
}
} else {
this.returnItems = newReturnItems;
nextField = "";
}
}
public void setRiValues(String newRiValues) {
this.riValues = newRiValues;
}
public String getNextField() {
return (nextField == null) ? "" : nextField.trim();
}
public void setNextField(String nextField) {
ReturnItem.nextField = nextField;
}
public String getDivList() {
return (divList == null) ? "" : divList.trim();
}
public void setDivList(String divList) {
ReturnItem.divList = divList;
}
private ArrayList<String> getReturnItemsAL() {
if (this.returnItemsAL == null) {
String res = "";
if (getReturnItems() != null) {
this.returnItemsAL = new ArrayList<>();
StringTokenizer st = new StringTokenizer(getReturnItems(), ",");
int i = 0;
while (st.hasMoreTokens()) {
res = st.nextToken();
this.returnItemsAL.add(res);
i++;
}
}
}
return this.returnItemsAL;
}
public void setReturnItemsAL(ArrayList<String> returnItemsAL) {
this.returnItemsAL = returnItemsAL;
}
public String getRiOLD(int l_numb) {
String res = "";
if (getReturnItems() != null) {
java.util.StringTokenizer st = new java.util.StringTokenizer(getReturnItems().replace(",,", ", ,"), ",");
if (l_numb < st.countTokens())
for (int i = 0; i <= l_numb; i++)
res = st.nextToken();
} else {
System.err.println("ERROR!: returnItems is null");
}
return res;
}
}

View file

@ -0,0 +1,168 @@
package com.ablia.util;
import com.ablia.db.DBAdapter;
public class ReturnItemOld {
private String returnItems;
private String riValues;
private static String nextField;
private String STND_DELIMIT_TOKEN = "|";
private String NEXT_SELECTED_FIELDS_PREFIX = "NSF";
private static String divList;
public ReturnItemOld() {}
public ReturnItemOld(String l_ri) {
setReturnItems(l_ri);
}
public ReturnItemOld(String l_ri, String l_nextField, String l_divList) {
setReturnItems(l_ri);
setNextField(l_nextField);
setDivList(l_divList);
}
public void addRiValues(double l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(float l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(long l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(Object l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + String.valueOf(l_values));
}
}
public void addRiValues(String l_values) {
if (getRiValues().isEmpty()) {
setRiValues(String.valueOf(l_values));
} else {
setRiValues(String.valueOf(getRiValues()) + this.STND_DELIMIT_TOKEN + (l_values.isEmpty() ? " " : l_values));
}
}
public String getReturnItems() {
return this.returnItems;
}
public String getRi(int l_numb) {
String res = "";
if (getReturnItems() != null) {
java.util.StringTokenizer st = new java.util.StringTokenizer(getReturnItems(), ",");
if (l_numb < st.countTokens())
for (int i = 0; i <= l_numb; i++)
res = st.nextToken();
} else {
System.err.println("ERROR!: returnItems is null");
}
return res;
}
public String getRiValues() {
return (this.riValues == null) ? "" : this.riValues;
}
public String getSelectedKey() {
String res = "";
String temp = DBAdapter.prepareScriptString(getRiValues());
java.util.StringTokenizer st = new java.util.StringTokenizer(temp, this.STND_DELIMIT_TOKEN);
int i = 0;
while (st.hasMoreTokens()) {
String value = st.nextToken().trim();
if (!getRi(i).isEmpty()) {
if (res.isEmpty()) {
res = "'" + value + "','" + getRi(i) + "'";
} else {
res = String.valueOf(res) + ",'" + value + "','" + getRi(i) + "'";
}
System.out.println(String.valueOf(value) + " --- " + getRi(i));
}
i++;
}
if (nextField != null && !nextField.equals(""))
res = String.valueOf(res) + ",'" + nextField + "'";
return res;
}
public String getSelectedKeyNoQuot() {
String res = "";
String temp = DBAdapter.prepareScriptString(getRiValues(), false);
java.util.StringTokenizer st = new java.util.StringTokenizer(temp, this.STND_DELIMIT_TOKEN);
int i = 0;
while (st.hasMoreTokens() && !getRi(i).isEmpty()) {
if (res.isEmpty()) {
res = "'" + st.nextToken() + "','" + getRi(i) + "'";
} else {
res = String.valueOf(res) + ",'" + st.nextToken() + "','" + getRi(i) + "'";
}
i++;
}
if (nextField != null && !nextField.equals(""))
res = String.valueOf(res) + ",'" + nextField + "'";
return res;
}
public void setReturnItems(String newReturnItems) {
if (newReturnItems != null && newReturnItems.indexOf(this.NEXT_SELECTED_FIELDS_PREFIX) > 0) {
int idx = newReturnItems.indexOf(this.NEXT_SELECTED_FIELDS_PREFIX);
int riL = newReturnItems.length();
if (idx == 0) {
int firstitemIdx = newReturnItems.indexOf(",");
this.returnItems = newReturnItems.substring(firstitemIdx + 1);
nextField = newReturnItems.substring(this.NEXT_SELECTED_FIELDS_PREFIX.length() + 1, firstitemIdx);
} else {
this.returnItems = newReturnItems.substring(0, idx - 1);
nextField = newReturnItems.substring(this.returnItems.length() + this.NEXT_SELECTED_FIELDS_PREFIX.length() + 2, riL);
}
} else {
this.returnItems = newReturnItems;
nextField = "";
}
}
public void setRiValues(String newRiValues) {
this.riValues = newRiValues;
}
public String getNextField() {
return (nextField == null) ? "" : nextField.trim();
}
public void setNextField(String nextField) {
ReturnItemOld.nextField = nextField;
}
public String getDivList() {
return (divList == null) ? "" : divList.trim();
}
public void setDivList(String divList) {
ReturnItemOld.divList = divList;
}
}

View file

@ -0,0 +1,186 @@
package com.ablia.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SVFileReader {
private String fileName;
private int columnCount;
private String separator;
private String fixedColumn;
private BufferedReader reader;
private String[] currentRecord;
private int recordNumber = 0;
public SVFileReader(String l_fileName) {
setFileName(l_fileName);
}
public SVFileReader(String l_fileName, char l_separator) {
setSeparator(new Character(l_separator).toString());
setFileName(l_fileName);
}
public SVFileReader(String l_fileName, String l_fixedColumn) {
setFixedColumn(l_fixedColumn);
setFileName(l_fileName);
}
public void closeFile() {
try {
if (this.reader != null) {
getReader().close();
this.reader = null;
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
protected void finalize() throws Throwable {
closeFile();
}
public int getColumnCount() {
if (this.columnCount == 0) {
gotoFirstRecord();
setReader(null);
}
return this.columnCount;
}
private String[] getCurrentRecord() {
if (this.currentRecord == null)
this.currentRecord = new String[getColumnCount()];
return this.currentRecord;
}
public String getField(int l_column) {
return getCurrentRecord()[l_column];
}
public String getFileName() {
return this.fileName;
}
private BufferedReader getReader() throws IOException {
if (this.reader == null)
if (getFileName() != null) {
try {
if (getFixedColumn() == null) {
this.reader = new BufferedReader(new FileReader(
getFileName()));
String temp = "";
int cc = 0;
int fi = 0;
int nfi = 0;
if ((temp = this.reader.readLine()) != null) {
if (temp.indexOf(getSeparator()) == 0)
temp = temp.substring(1);
if (temp.lastIndexOf(getSeparator()) ==
temp.length() - 1)
temp = temp.substring(0, temp.length() - 1);
while ((nfi = temp.indexOf(getSeparator(), fi)) >= 0) {
cc++;
fi = nfi + 1;
}
cc++;
setColumnCount(cc);
}
this.reader.close();
this.reader = null;
}
this.reader = new BufferedReader(new FileReader(getFileName()));
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
} else {
throw new IOException("Filename not valid");
}
return this.reader;
}
public int getRecordNumber() {
return this.recordNumber;
}
public String getSeparator() {
return (this.separator == null) ? "|" : this.separator;
}
public boolean gotoFirstRecord() {
setReader(null);
return nextRecord();
}
public boolean nextRecord() {
try {
String temp = "";
if ((temp = getReader().readLine()) != null) {
if (getFixedColumn() == null) {
int beginIndex = 0;
int endIndex = 0;
int i = 0;
if (!temp.endsWith(getSeparator()))
temp = String.valueOf(temp) + getSeparator();
if (temp.indexOf(getSeparator()) == 0)
temp = temp.substring(1);
String temp2 = "";
while ((endIndex = temp.indexOf(getSeparator(), beginIndex)) > 0) {
temp2 = temp.substring(beginIndex, endIndex).trim();
getCurrentRecord()[i] = temp2;
beginIndex = endIndex + 1;
i++;
}
this.recordNumber++;
return true;
}
return false;
}
return false;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return false;
}
}
private void setColumnCount(int newColumnCount) {
this.columnCount = newColumnCount;
setCurrentRecord(null);
}
private void setCurrentRecord(String[] newCurrentRecord) {
this.currentRecord = newCurrentRecord;
}
public void setFileName(String newFileName) {
this.fileName = newFileName;
}
private void setReader(BufferedReader newReader) {
this.reader = newReader;
}
public void setRecordNumber(int newRecordNumber) {
this.recordNumber = newRecordNumber;
}
public void setSeparator(String newSeparator) {
this.separator = newSeparator;
}
public String getFixedColumn() {
return this.fixedColumn;
}
public void setFixedColumn(String fixedColumn) {
this.fixedColumn = fixedColumn;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,244 @@
package com.ablia.util;
import com.ablia.common.StatusMsg;
import com.ablia.db.ApplParmFull;
import com.ablia.db.ResParm;
import java.io.File;
import java.util.Date;
public class ScaleImages extends Thread {
public static final String TAG_SCALE_IMAGES = "SCALE_IMAGES";
private long scaledFactor;
private int scaledHeight;
private ApplParmFull apFull;
private String brandFileName;
private int scaledWidth;
private String imageDir;
private boolean checkScaled;
private boolean useTimestamp = true;
private String scaledPrefix;
private int dpi;
private float quality;
public ScaleImages(ApplParmFull apFull, String l_imageDir, String l_scaledPrefix, long l_scaledFactor, int l_scaledWidth, int l_scaledHeight, boolean l_checkScaled, boolean l_useTimestamp, String l_brandFileName) {
setApFull(apFull);
setImageDir(l_imageDir);
setScaledPrefix(l_scaledPrefix);
setScaledFactor(l_scaledFactor);
setScaledWidth(l_scaledWidth);
setCheckScaled(l_checkScaled);
setUseTimestamp(l_useTimestamp);
setBrandFileName(l_brandFileName);
start();
}
public ScaleImages(ApplParmFull apFull, String l_imageDir, String l_scaledPrefix, long l_scaledFactor, int l_scaledWidth, int l_scaledHeight, boolean l_checkScaled, boolean l_useTimestamp, String l_brandFileName, int dpi, float quality) {
setApFull(apFull);
setImageDir(l_imageDir);
setScaledPrefix(l_scaledPrefix);
setScaledFactor(l_scaledFactor);
setScaledWidth(l_scaledWidth);
setCheckScaled(l_checkScaled);
setUseTimestamp(l_useTimestamp);
setBrandFileName(l_brandFileName);
setDpi(dpi);
setQuality(quality);
start();
}
public static void main(String[] args) {
System.out.println("Scale Images Ver. 0.2");
if (args.length < 3) {
System.out.println("Utilizzare\nScaleImages dirImmagini scaledPrefix scaledWidth scaledHeight ");
System.exit(0);
}
String dirImg = args[0];
String scaledPrefix = args[1];
String scaledWidth = args[2];
String scaledHeight = args[3];
System.out.println("fine");
System.exit(0);
}
private final ResParm scaleDir(String l_imageDir, String l_scaledPrefix, long l_scaledFactor, int l_scaledWidth, int l_scaledHeight, boolean l_checkScaled, boolean l_useTimestamp) {
ResParm rp = new ResParm();
File dirTargetDir = new File(l_imageDir);
boolean status = true;
StringBuffer errMsg = new StringBuffer();
String prefix = String.valueOf(l_scaledPrefix) + "/";
int totFotoOk = 0, totFotoKO = 0;
if (new File(getRunFile()).exists()) {
status = false;
errMsg.append("Attenzione! Thread scale images attivo per " + l_imageDir + "/" + l_scaledPrefix);
} else {
if (!dirTargetDir.exists()) {
status = false;
errMsg.append("Directori " + l_imageDir + " non esiste!!");
} else {
FileWr fRun = new FileWr(getRunFile());
Date d = new Date(System.currentTimeMillis());
fRun.writeLine("*** Start thread: " + d.toString());
fRun.closeFile();
File[] fotos = dirTargetDir.listFiles();
File theFoto = null;
for (int i = 0; i < fotos.length; i++) {
theFoto = fotos[i];
try {
if (theFoto.getCanonicalPath().toLowerCase().endsWith("jpg")) {
ScaleImage si = new ScaleImage(theFoto.getCanonicalPath(), prefix, l_scaledFactor, l_scaledWidth,
l_scaledHeight, l_checkScaled, l_useTimestamp);
si.setAutoRotate(true);
si.setBrandFileName(getBrandFileName());
si.setDpi(getDpi());
si.setQuality(getQuality());
rp = si.scaleIt();
System.out.println(rp.getMsg());
if (!rp.getStatus()) {
errMsg.append("*** Errore foto " + theFoto.getCanonicalPath() + ": " + rp.getMsg() + "\n\r\n\r");
status = false;
totFotoKO++;
} else {
totFotoOk++;
}
}
} catch (Exception e) {
status = false;
errMsg.append(String.valueOf(e.getMessage()) + "\n\r\n\r");
totFotoKO++;
}
}
}
new File(getRunFile()).delete();
}
rp.setStatus(status);
rp.setMsg("\n\r\n\r ******** FINE CONVERSIONE FOTO ******* \n\r\n\rFoto convertite correttamente: " + totFotoOk +
"\n\r\n\rFoto NON CONVERTITE: " + totFotoKO + "\n\r\n\r TOT FOTO: " + (totFotoKO + totFotoOk));
if (!status)
rp.setMsg("\n\r\n\r ######## ELENCO ERRORI #######\n\r\n\r" + errMsg.toString());
StatusMsg.updateMsgByTag(getApFull(), "SCALE_IMAGES_" + hashCode(),
"Ridimensionamento immagini dir " + getImageDir() + " concluso. tot foto: " + (totFotoKO + totFotoOk));
try {
sleep(5000L);
} catch (Exception e) {}
StatusMsg.deleteMsgByTag(this.apFull, "SCALE_IMAGES_" + hashCode());
return rp;
}
public void run() {
StatusMsg.updateMsgByTag(getApFull(), "SCALE_IMAGES_" + hashCode(),
"Ridimensionamento immagini dir " + getImageDir() + " " + getScaledPrefix() + " in corso..");
ResParm rp = scaleDir(getImageDir(), getScaledPrefix(), getScaledFactor(), getScaledWidth(), getScaledHeight(), isCheckScaled(),
isUseTimestamp());
System.out.println(rp.getMsg());
FileWr logFile = new FileWr(getLogFile());
logFile.writeLine(rp.getMsg());
logFile.closeFile();
}
public long getScaledFactor() {
return this.scaledFactor;
}
public void setScaledFactor(long scaledFactor) {
this.scaledFactor = scaledFactor;
}
public int getScaledHeight() {
return this.scaledHeight;
}
public void setScaledHeight(int scaledHeight) {
this.scaledHeight = scaledHeight;
}
public String getScaledPrefix() {
return this.scaledPrefix;
}
public void setScaledPrefix(String scaledPrefix) {
this.scaledPrefix = scaledPrefix;
}
public int getScaledWidth() {
return this.scaledWidth;
}
public void setScaledWidth(int scaledWidth) {
this.scaledWidth = scaledWidth;
}
public String getImageDir() {
return (this.imageDir == null) ? "" : this.imageDir.trim();
}
public void setImageDir(String theImageDir) {
this.imageDir = theImageDir;
}
public boolean isCheckScaled() {
return this.checkScaled;
}
public void setCheckScaled(boolean checkScaled) {
this.checkScaled = checkScaled;
}
public String getRunFile() {
return String.valueOf(getImageDir()) + "/__RUN" + "_" + getScaledPrefix() + ".txt";
}
public String getLogFile() {
return String.valueOf(getImageDir()) + "/__LOG" + "_" + getScaledPrefix() + ".log";
}
public boolean isUseTimestamp() {
return this.useTimestamp;
}
public void setUseTimestamp(boolean useTimestamp) {
this.useTimestamp = useTimestamp;
}
public String getBrandFileName() {
return this.brandFileName;
}
public void setBrandFileName(String brandFileName) {
this.brandFileName = brandFileName;
}
public int getDpi() {
return this.dpi;
}
public void setDpi(int dpi) {
this.dpi = dpi;
}
public float getQuality() {
return this.quality;
}
public void setQuality(float quality) {
this.quality = quality;
}
public ApplParmFull getApFull() {
return this.apFull;
}
public void setApFull(ApplParmFull applParm) {
this.apFull = applParm;
}
}

View file

@ -0,0 +1,36 @@
package com.ablia.util;
import java.sql.Date;
import java.sql.Time;
import java.text.DateFormatSymbols;
import java.util.Locale;
public class SimpleDateFormat extends java.text.SimpleDateFormat {
private static final long serialVersionUID = 1L;
public SimpleDateFormat() {}
public SimpleDateFormat(String s) {
super(s);
}
public SimpleDateFormat(String s, DateFormatSymbols dateformatsymbols) {
super(s, dateformatsymbols);
}
public SimpleDateFormat(String s, Locale locale) {
super(s, locale);
}
public String format(Date date) {
if (date == null)
return "";
return format((java.util.Date)date);
}
public String format(Time time) {
if (time == null)
return "";
return time.toString().substring(0, 5);
}
}

View file

@ -0,0 +1,66 @@
package com.ablia.util;
public class Sitemap extends FileWr {
public static final String SM_START = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
public static final String SM_END = "</urlset>";
public static final String C_F_HOURLY = "hourly";
public static final String C_F_ALWAYS = "always";
public static final String C_F_DAILY = "daily";
public static final String C_F_WEEKLY = "weekly";
public static final String C_F_YEARLY = "yearly";
public static final String C_F_MONTHLY = "monthly";
public static final String C_F_NEVER = "never";
public static final String SM_START_xx = "<?xml version='1.0' encoding='UTF-8'?>\n<urlset\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n\t\turl=\"http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\"\n\t\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
public Sitemap(String s) {
super(s);
startSitemap();
}
public Sitemap(String s, boolean appendFlag) {
super(s, appendFlag);
startSitemap();
}
public boolean addUrl(String loc, String lastMod, String changeFreq, double priority) {
StringBuffer url = new StringBuffer();
url.append("\t<url>\n\t\t<loc>");
url.append(loc.replaceAll("&", "&amp;"));
url.append("</loc>\n");
if (lastMod != null) {
url.append("\t\t<lastmod>");
url.append(lastMod);
url.append("</lastmod>\n");
}
if (changeFreq != null) {
url.append("\t\t<changefreq>");
url.append(changeFreq);
url.append("</changefreq>\n");
}
if (priority != 0.0D) {
url.append("\t\t<priority>");
url.append(priority);
url.append("</priority>\n");
}
url.append("\t</url>");
return writeLine(url.toString());
}
private boolean startSitemap() {
return writeLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
}
public void closeFile() {
writeLine("</urlset>");
super.closeFile();
}
}

View file

@ -0,0 +1,7 @@
package com.ablia.util;
import com.ablia.db.ApplParmFull;
public interface SitemapI {
boolean buildSitemap(String paramString, ApplParmFull paramApplParmFull);
}

View file

@ -0,0 +1,34 @@
package com.ablia.util;
public class StringTable {
public int[] columnLength;
private int currentColumn;
private String formattedString;
public StringTable(int[] ai) {
this.currentColumn = 0;
this.formattedString = "";
this.columnLength = ai;
}
public void addColumn(String s) {
int i = this.columnLength[this.currentColumn];
this.formattedString = String.valueOf(this.formattedString) + (String.valueOf(s) + getSpacesString(i)).substring(0, i) + " ";
this.currentColumn++;
}
public String getFormattedString() {
return this.formattedString;
}
private String getSpacesString(int i) {
return " ".substring(0, i);
}
public void newRow() {
this.formattedString = String.valueOf(this.formattedString) + "\n";
this.currentColumn = 0;
}
}

View file

@ -0,0 +1,126 @@
package com.ablia.util;
public class StringTokenizer {
private static final char SPACE = ' ';
private String theString = "";
private Vectumerator<String> theTokens;
private char theQualificatoreTesto = ' ';
private long[] columnSizes;
private boolean useColumnSize = false;
private String theDelimiter = ";";
public StringTokenizer(String l_theString, String delimiter) {
this.theString = l_theString;
this.theDelimiter = delimiter;
}
public StringTokenizer(String l_theString, long[] l_columSizes) {
this.theString = l_theString;
this.columnSizes = l_columSizes;
}
public StringTokenizer(String l_theString, long[] l_columSizes, boolean l_useColumnSize) {
this.theString = l_theString;
this.columnSizes = l_columSizes;
this.useColumnSize = l_useColumnSize;
}
public StringTokenizer(String l_theString, String delimiter, char qualificatoreTesto) {
this.theString = l_theString;
this.theDelimiter = delimiter;
this.theQualificatoreTesto = qualificatoreTesto;
}
public boolean hasMoreTokens() {
return getTheTokens().hasMoreElements();
}
public int countToken() {
return getTheTokens().size();
}
public String nextToken() {
return getTheTokens().nextElement();
}
public String getToken(int tokenNumber) {
getTheTokens().setIndex(tokenNumber);
return nextToken();
}
public String getTokenCleaned(int tokenNumber) {
String temp = getTheTokens().elementAt(tokenNumber);
if (temp.isEmpty())
return "";
if (temp.charAt(0) == '"')
temp = temp.substring(1);
if (temp.charAt(temp.length() - 1) == '"')
temp = temp.substring(0, temp.length() - 1);
return temp;
}
private Vectumerator<String> getTheTokens() {
if (this.theTokens == null) {
this.theTokens = new Vectumerator<>();
if (this.columnSizes == null) {
int startIdx = 0;
String currentDelimeter = this.theDelimiter;
String qtDelimeter = String.valueOf(this.theQualificatoreTesto) + this.theDelimiter;
if (!this.theString.endsWith(this.theDelimiter))
this.theString = String.valueOf(this.theString) + this.theDelimiter;
if (this.theQualificatoreTesto != ' ' &&
this.theString.indexOf(this.theQualificatoreTesto) == 0) {
currentDelimeter = qtDelimeter;
startIdx++;
}
int endIdx;
while ((endIdx = this.theString.indexOf(currentDelimeter, startIdx)) != -1) {
String temp = this.theString.substring(startIdx, endIdx);
if (!this.theDelimiter.equals(" ") || !temp.equals(""))
this.theTokens.add(temp);
startIdx = endIdx + 1;
if (this.theQualificatoreTesto != ' ' &&
currentDelimeter.equals(qtDelimeter))
startIdx++;
if (this.theQualificatoreTesto != ' ' &&
this.theString.substring(startIdx).indexOf(
this.theQualificatoreTesto) == 0) {
startIdx++;
currentDelimeter = qtDelimeter;
continue;
}
currentDelimeter = this.theDelimiter;
}
} else if (this.useColumnSize) {
int startIdx = 0;
for (int i = 0; i < this.columnSizes.length; i++) {
int cs = (int)this.columnSizes[i];
if (cs <= this.theString.length() - startIdx) {
this.theTokens.add(this.theString.substring(startIdx,
startIdx + cs));
startIdx += cs;
} else {
this.theTokens.add(this.theString.substring(startIdx));
break;
}
}
} else {
int startIdx = 0;
for (int i = 0; i < this.columnSizes.length; i++) {
int cs = (int)this.columnSizes[i];
if (cs <= this.theString.length() && cs > startIdx) {
this.theTokens.add(this.theString.substring(startIdx, cs));
startIdx = cs;
}
}
}
}
return this.theTokens;
}
}

View file

@ -0,0 +1,117 @@
package com.ablia.util;
import com.ablia.db.ApplParm;
import com.ablia.db.DriversJdbc;
import com.ablia.db.JdbcStub;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
class TestJdbc {
private JdbcStub db;
private ConsoleInput ci;
private ConsoleInput getCi() {
if (this.ci == null)
this.ci = new ConsoleInput();
return this.ci;
}
public JdbcStub getDb() {
if (this.db == null)
try {
System.out.println("Connessione jdbc_odbc.....");
System.out.println("Inserire driver Jdbc:");
for (int i = 0; i < DriversJdbc.getTotNumberOfDrivers(); i++)
System.out.println(
"(" + i + ") " + DriversJdbc.getDriverDescription(i));
String s = getCi().readLine("Driver=");
String s1 = getCi().readLine("Inserire risorsa dati jdbc: ");
String s2 = getCi().readLine("Login: ");
String s3 = getCi().readLine("Password: ");
String s4 = "";
if (s.equals("11"))
s4 = getCi().readLine("DBPassword: ");
System.out.println(s);
ApplParm applparm = new ApplParm(Integer.parseInt(s), s1, s2, s3);
if (s.equals("11"))
applparm.setDbAtinavpasswd(s4);
applparm.setDebug(true);
this.db = new JdbcStub(applparm);
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
return this.db;
}
public static void main(String[] args) {
TestJdbc testjdbc = new TestJdbc();
do {
} while (testjdbc.queryDb());
System.out.println("bye");
}
public boolean queryDb() {
byte byte0 = 30;
String s2 = "";
try {
Statement statement = getDb().getConn().createStatement();
String s1 = getCi().readLine("Inserire query sql(" + s2 + "):");
if (s1.equals("quit"))
return false;
if (!s1.isEmpty())
s2 = s1;
if (statement.execute(s2)) {
ResultSet resultset = statement.getResultSet();
ResultSetMetaData resultsetmetadata = resultset.getMetaData();
int i = resultsetmetadata.getColumnCount();
int[] ai = new int[i + 1];
System.out.println("Numero Colonne: " + i);
for (int k = 1; k <= i; k++) {
if (resultsetmetadata.getColumnDisplaySize(k) < resultsetmetadata.getColumnName(k).length()) {
ai[k] = resultsetmetadata.getColumnName(k).length();
} else if (resultsetmetadata.getColumnDisplaySize(k) > byte0) {
ai[k] = byte0;
} else {
ai[k] = resultsetmetadata.getColumnDisplaySize(k);
}
String s4 = String.valueOf(resultsetmetadata.getColumnName(k)) + spaces(ai[k] - resultsetmetadata.getColumnName(k).length()) + " | ";
System.out.print(s4);
}
System.out.println();
int j = 0;
for (; resultset.next(); System.out.println()) {
j++;
for (int l = 1; l <= i; l++) {
Object obj1;
if ((obj1 = resultset.getObject(l)) == null) {
s5 = "null";
} else {
s5 = obj1.toString();
}
String s5 = String.valueOf(s5) + spaces(ai[l] - s5.length());
if (s5.length() > byte0)
s5 = s5.substring(0, byte0);
System.out.print(String.valueOf(s5) + " | ");
}
}
System.out.println("Numero di record; " + j + "\n");
} else {
System.out.println("Numero di record aggiornati: " + statement.getUpdateCount());
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
return true;
}
public String spaces(int i) {
String s = "";
for (int j = 0; j < i; j++)
s = String.valueOf(s) + " ";
return s;
}
}

View file

@ -0,0 +1,57 @@
package com.ablia.util;
import com.ablia.db.DBAdapter;
import java.sql.Time;
import java.sql.Timestamp;
public class Timer {
private Timestamp tStart = null;
private Timestamp tStop = null;
public void start() {
this.tStart = new Timestamp(System.currentTimeMillis());
}
public void stop() {
this.tStop = new Timestamp(System.currentTimeMillis());
}
public String getDurataSec() {
long secs = DBAdapter.getTimeDiff(new Time(this.tStart.getTime()), new Time(this.tStop.getTime()));
return String.valueOf(secs);
}
public String getDurataHourMin() {
long secs = DBAdapter.getTimeDiff(new Time(this.tStart.getTime()), new Time(this.tStop.getTime()));
String temp = secToTempoHourMin(secs);
return temp;
}
public static String secToTempoHourMin(long sec) {
long h = sec / 3600L;
long min = (sec - h * 60L) / 60L;
long secF = sec - h * 3660L - min * 60L;
return String.valueOf(h) + " h " + min + " min " + secF + " sec";
}
public Timestamp getTStart() {
return this.tStart;
}
public Timestamp getTStop() {
return this.tStop;
}
public String getDurata() {
long secs = DBAdapter.getTimeDiff(new Time(this.tStart.getTime()), new Time(this.tStop.getTime()));
String temp = "\n\n--------------------------------------------------\nPartenza: " + this.tStart + "\nFine: " + this.tStop + "\nDurata: " +
secToTempoHourMin(secs);
return temp;
}
public long getDurataMilliSec() {
long msecs = this.tStop.getTime() - this.tStart.getTime();
return msecs;
}
}

View file

@ -0,0 +1,44 @@
package com.ablia.util;
public class UnicodeFormatter {
public static int Asc(char c) {
String hex = charToHex(c);
int result = Character.getNumericValue(hex.charAt(0)) * 4096 +
Character.getNumericValue(hex.charAt(1)) * 256 +
Character.getNumericValue(hex.charAt(2)) * 16 +
Character.getNumericValue(hex.charAt(3));
return result;
}
public static String byteToHex(byte b) {
char[] hexDigit = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f' };
char[] array = { hexDigit[b >> 4 & 0xF], hexDigit[b & 0xF] };
return new String(array);
}
public static String charToHex(char c) {
byte hi = (byte)(c >>> 8);
byte lo = (byte)(c & 0xFF);
return String.valueOf(byteToHex(hi)) + byteToHex(lo);
}
public static char decToChar(int asciValue) {
return (char)asciValue;
}
}

View file

@ -0,0 +1,104 @@
package com.ablia.util;
import com.ablia.db.ResParm;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class UploadFile extends Debug {
private HttpURLConnection con;
public static void main(String[] str) {
try {
File srcFile = new File("/Users/acolzi/Downloads/numeri-promo.pdf");
String destPath = "/Users/acolzi/Downloads/xx/";
String urlServletRicevente = "http://127.0.0.1/feLte/ReceiveFile.abl";
ResParm rp = new UploadFile().transferFile(urlServletRicevente, srcFile, destPath, null);
System.out.println(rp.getMsg());
} catch (Exception e) {
System.out.println("Usage: sourcePath destPath");
System.exit(1);
}
}
public ResParm transferFile(String urlServletRicevente, File sourceFile, String destPath, String destFileName) {
ResParm rp = new ResParm(true);
try {
String fileName;
System.gc();
if (destFileName != null && !destFileName.isEmpty()) {
fileName = destFileName;
} else {
fileName = sourceFile.getName();
}
int bufferlength = getBufferLength(sourceFile);
FileInputStream fin = new FileInputStream(sourceFile);
URL url = new URL(String.valueOf(urlServletRicevente) + "?bs=" + bufferlength + "&name=" + URLEncoder.encode(fileName, "UTF-8") + "&path=" +
URLEncoder.encode(destPath, "UTF-8"));
this.con = (HttpURLConnection)url.openConnection();
this.con.setChunkedStreamingMode(bufferlength * 8);
this.con.setRequestProperty("REQUEST_METHOD", "POST");
this.con.setDoInput(true);
this.con.setDoOutput(true);
this.con.setUseCaches(true);
this.con.setRequestProperty("Content-Type", "multipart-formdata");
DataOutputStream dataOut = new DataOutputStream(this.con.getOutputStream());
int c = bufferlength;
byte[] b = new byte[c];
int cnt = 0;
while ((cnt = fin.read(b)) > -1)
dataOut.write(b, 0, cnt);
dataOut.flush();
dataOut.close();
fin.close();
BufferedReader read = new BufferedReader(new InputStreamReader(this.con.getInputStream()));
String line = read.readLine();
String html = "";
while (line != null) {
html = String.valueOf(html) + line;
line = read.readLine();
}
} catch (Exception e) {
handleDebug(e);
rp.setException(e);
long heapsize = Runtime.getRuntime().totalMemory();
System.out.println("heapsize is::" + heapsize);
rp.setStatus(false);
} finally {
this.con = null;
}
System.gc();
return rp;
}
public ResParm transferFile(String urlServletRicevente, String sourceFileS, String destPath) {
return transferFile(urlServletRicevente, new File(sourceFileS), destPath, null);
}
public ResParm transferFile(String urlServletRicevente, File sourceFile, String destPath) {
return transferFile(urlServletRicevente, sourceFile, destPath, null);
}
private int getBufferLength(File sourceFile) {
int kb = 1;
long lenK = sourceFile.length() / 1024L;
if (lenK / 32L > 2L) {
kb = 32;
} else if (lenK / 16L > 2L) {
kb = 16;
} else if (lenK / 8L > 2L) {
kb = 8;
}
System.out.println("Upload file getBufferLength: " + kb + "kb");
return kb * 1024;
}
public ResParm transferFile(String urlServletRicevente, String sourceFileS, String destPath, String destFileName) {
return transferFile(urlServletRicevente, new File(sourceFileS), destPath, destFileName);
}
}

View file

@ -0,0 +1,263 @@
package com.ablia.util;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class Vectumerator<E> extends Vector<E> implements Enumeration<E> {
private static final long serialVersionUID = 1L;
private static String COLUMN_DELIMITER = ";";
private static Double ZERO_DOUBLE = new Double(0.0D);
private Hashtable<String, Double> sumResults;
private Hashtable<String, Double> sumPartialResults;
private int i = 0;
private int totNumberOfRecords;
private boolean fetchedAllRows = true;
private int pageRow;
private String columnToSum;
private int pageNumber;
private boolean orderForward = true;
private String queryTime;
public Vectumerator() {}
public Vectumerator(int initialCapacity) {
super(initialCapacity);
}
public Vectumerator(int initialCapacity, int capacityIncrement) {
super(initialCapacity, capacityIncrement);
}
public Vectumerator(Enumeration<E> enu) {
while (enu.hasMoreElements())
add(enu.nextElement());
}
public int getIndex() {
return this.i;
}
public int getPageNumber() {
return (this.pageNumber == 0) ? 1 : this.pageNumber;
}
public int getPageRow() {
return this.pageRow;
}
private Vectumerator<E> getThis() {
if (capacity() > this.elementCount)
trimToSize();
return this;
}
public int getTotNumberOfPages() {
return (this.pageRow == 0) ? 1 : (int)Math.ceil((double)getTotNumberOfRecords() / (double)this.pageRow);
}
public int getTotNumberOfRecords() {
return (this.totNumberOfRecords == 0) ? size() : this.totNumberOfRecords;
}
public boolean hasMoreElements() {
if (this.i < (getThis()).elementCount)
return true;
return false;
}
public boolean hasMoreRecords() {
return (getTotNumberOfPages() > getPageNumber());
}
public boolean isEmpty() {
return !(getTotNumberOfRecords() > 0);
}
public void setOrderBackward() {
this.orderForward = false;
}
public void setOrderForward() {
this.orderForward = true;
}
public void moveFirst() {
setIndex(0);
}
public E nextElement() {
if (hasMoreElements()) {
E ret;
if (this.orderForward) {
ret = elementAt(this.i);
} else {
ret = elementAt(getTotNumberOfRecords() - this.i - 1);
}
this.i++;
if (getColumnToSum() != null && !getColumnToSum().isEmpty()) {
StringTokenizer st = new StringTokenizer(String.valueOf(getColumnToSum()) + COLUMN_DELIMITER, COLUMN_DELIMITER);
try {
while (st.hasMoreTokens()) {
String currentColumn = st.nextToken();
String getMethodName = "get" + currentColumn.substring(0, 1).toUpperCase() + currentColumn.substring(1);
Method getMth = ret.getClass().getMethod(getMethodName, null);
Object ctsObj = getMth.invoke(ret, null);
addSumResult(currentColumn, ctsObj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
return null;
}
public void setIndex(int newI) {
this.i = newI;
}
public void setPageNumber(int newPageNumber) {
this.pageNumber = newPageNumber;
}
public void setPageRow(int newPageRow) {
this.pageRow = newPageRow;
}
public void setTotNumberOfRecords(int newTotNumberOfRecords) {
this.totNumberOfRecords = newTotNumberOfRecords;
}
public String getColumnToSum() {
return this.columnToSum;
}
public void setColumnToSum(String string) {
this.columnToSum = string;
}
private Hashtable<String, Double> getSumResults() {
if (this.sumResults == null)
this.sumResults = new Hashtable<>();
return this.sumResults;
}
private Hashtable<String, Double> getSumPartialResults() {
if (this.sumPartialResults == null)
this.sumPartialResults = new Hashtable<>();
return this.sumPartialResults;
}
public double getSumResult(String theColumn) {
if (getSumResults().containsKey(theColumn))
return getSumResults().get(theColumn);
getSumResults().put(theColumn, ZERO_DOUBLE);
return 0.0D;
}
public double getSumPartialResult(String theColumn) {
if (getSumPartialResults().containsKey(theColumn))
return getSumPartialResults().get(theColumn);
getSumPartialResults().put(theColumn, ZERO_DOUBLE);
return 0.0D;
}
public void setSumResult(String theColumn, double theValue) {
getSumResults().put(theColumn, new Double(theValue));
}
public void setSumPartialResult(String theColumn, double theValue) {
getSumPartialResults().put(theColumn, new Double(theValue));
}
public void resetPartialResults(String theColumn) {
getSumPartialResults().remove(theColumn);
}
public void resetAllPartialResults() {
this.sumPartialResults = null;
Object ret = elementAt(this.i - 1);
StringTokenizer st = new StringTokenizer(String.valueOf(getColumnToSum()) + COLUMN_DELIMITER, COLUMN_DELIMITER);
try {
while (st.hasMoreTokens()) {
String currentColumn = st.nextToken();
String getMethodName = "get" + currentColumn.substring(0, 1).toUpperCase() + currentColumn.substring(1);
Method getMth = ret.getClass().getMethod(getMethodName, null);
Object ctsObj = getMth.invoke(ret, null);
if (ctsObj instanceof Double) {
setSumPartialResult(currentColumn, ((Double)ctsObj).doubleValue());
continue;
}
if (ctsObj instanceof Float) {
setSumPartialResult(currentColumn, ((Double)ctsObj).doubleValue());
continue;
}
if (ctsObj instanceof Long) {
long b = (Long)ctsObj;
setSumPartialResult(currentColumn, (double)b);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addSumResult(String currentColumn, Object ctsObj) {
if (ctsObj instanceof Double) {
DoubleOperator dop = new DoubleOperator(getSumResult(currentColumn));
dop.add(((Double)ctsObj).doubleValue());
setSumResult(currentColumn, dop.getResult());
dop = new DoubleOperator(getSumPartialResult(currentColumn));
dop.add(((Double)ctsObj).doubleValue());
setSumPartialResult(currentColumn, dop.getResult());
} else if (ctsObj instanceof Float) {
DoubleOperator dop = new DoubleOperator(getSumResult(currentColumn));
dop.add(((Float)ctsObj).floatValue());
setSumResult(currentColumn, dop.getResult());
dop = new DoubleOperator(getSumPartialResult(currentColumn));
dop.add(((Float)ctsObj).doubleValue());
setSumPartialResult(currentColumn, dop.getResult());
} else if (ctsObj instanceof Long) {
long a = (long)getSumResult(currentColumn);
long b = (Long)ctsObj;
setSumResult(currentColumn, (double)(a + b));
a = (long)getSumPartialResult(currentColumn);
setSumPartialResult(currentColumn, (double)(a + b));
}
}
public boolean isFetchedAllRows() {
return this.fetchedAllRows;
}
public void setFetchedAllRows(boolean b) {
this.fetchedAllRows = b;
}
public int getTotNumberFetchedRecord() {
return size();
}
public String getQueryTime() {
return (this.queryTime == null) ? "" : this.queryTime.trim();
}
public void setQueryTime(String queryTime) {
this.queryTime = queryTime;
}
}

View file

@ -0,0 +1,67 @@
package com.ablia.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.docx4j.Docx4J;
import org.docx4j.convert.in.Doc;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class Word2PdfConverter {
private String sourceFile;
private String targetFile;
public Word2PdfConverter(String sourceFile, String targetFile) {
this.sourceFile = sourceFile;
this.targetFile = targetFile;
}
public static void convert(String sourceFile, String targetFile, String cpFile) {
OutputStream out = null;
String ext = sourceFile.substring(sourceFile.lastIndexOf(".") + 1,
sourceFile.length());
String cpFileExt = String.valueOf(cpFile) + "." + ext;
try {
if (ext.equals("docx")) {
InputStream in = new FileInputStream(new File(sourceFile));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(in);
out = new FileOutputStream(new File(targetFile));
Docx4J.toPDF(wordMLPackage, out);
} else {
InputStream in = new FileInputStream(new File(sourceFile));
WordprocessingMLPackage wordMLPackage = Doc.convert(in);
out = new FileOutputStream(new File(targetFile));
Docx4J.toPDF(wordMLPackage, out);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getSourceFile() {
return this.sourceFile;
}
public void setSourceFile(String sourceFile) {
this.sourceFile = sourceFile;
}
public String getTargetFile() {
return this.targetFile;
}
public void setTargetFile(String targetFile) {
this.targetFile = targetFile;
}
}

View file

@ -0,0 +1,81 @@
package com.ablia.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
private String zipFileName;
private boolean saveOriginalPath = false;
private HashSet<String> hsFiles;
public ZipUtil(String zipFileName, boolean saveOriginalPath) {
this.zipFileName = zipFileName;
this.saveOriginalPath = saveOriginalPath;
}
public void addFile(String file) {
getHsFiles().add(file);
}
public String getZipFile() {
boolean ok = true;
currentFile = "";
if (new FileDb(this.zipFileName).exists())
new FileDb(this.zipFileName).delete();
OutputStream out = null;
ZipOutputStream zout = null;
try {
out = new FileOutputStream(this.zipFileName);
zout = new ZipOutputStream(out);
for (String currentFile : this.hsFiles) {
String currentEntry = currentFile.substring(currentFile.lastIndexOf('/') + 1);
zout.putNextEntry(new ZipEntry(currentEntry));
System.out.println("ZipDir: adding file" + currentFile);
InputStream in = new FileInputStream(new File(currentFile));
try {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0)
break;
zout.write(buffer, 0, readCount);
}
} finally {
in.close();
}
zout.closeEntry();
}
} catch (Exception e) {
ok = false;
e.printStackTrace();
} finally {
try {
if (zout != null)
zout.close();
} catch (Exception e2) {
ok = false;
e2.printStackTrace();
}
}
if (ok) {
System.out.println("ZipDir: ");
return this.zipFileName;
}
System.out.println("ZipDir: Error zipping on file " + currentFile);
return null;
}
private HashSet<String> getHsFiles() {
if (this.hsFiles == null)
this.hsFiles = new HashSet<>();
return this.hsFiles;
}
}