OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Compare Revisions

Regard whitespace Rev 56 → Rev 57

/trunk/OpenConcerto/src/org/openconcerto/erp/preferences/GenerationDocGlobalPreferencePanel.java
New file
0,0 → 1,40
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
/*
* Créé le 6 mars 2012
*/
package org.openconcerto.erp.preferences;
 
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.ui.preferences.JavaPrefPreferencePanel;
import org.openconcerto.ui.preferences.PrefView;
import org.openconcerto.utils.PrefType;
 
public class GenerationDocGlobalPreferencePanel extends JavaPrefPreferencePanel {
public static String HISTORIQUE = "HistoriqueDocument";
 
public GenerationDocGlobalPreferencePanel() {
super("Génération des documents", null);
setPrefs(new SQLPreferences(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()));
}
 
@Override
protected void addViews() {
PrefView<Boolean> view = new PrefView<Boolean>(PrefType.BOOLEAN_TYPE, "Archiver les documents dans un dossier historique", HISTORIQUE);
view.setDefaultValue(Boolean.TRUE);
this.addView(view);
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/config/InstallationPanel.java
33,6 → 33,8
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.DatabaseGraph;
import org.openconcerto.sql.model.graph.Link;
import org.openconcerto.sql.model.graph.SQLKey;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.utils.AlterTable;
import org.openconcerto.sql.utils.ChangeTable;
import org.openconcerto.sql.utils.DropTable;
52,8 → 54,12
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.swing.JButton;
65,6 → 71,7
import javax.swing.SwingUtilities;
 
public class InstallationPanel extends JPanel {
private static final boolean DEBUG_FK = false;
 
static private void insertUndef(final SQLCreateTable ct) {
final String insert = "INSERT into " + getTableName(ct).quote() + "(" + SQLBase.quoteIdentifier(SQLSyntax.ORDER_NAME) + ") VALUES(" + ReOrder.MIN_ORDER + ")";
83,9 → 90,10
setOpaque(false);
GridBagConstraints c = new DefaultGridBagConstraints();
JButton user = new JButton("Créer l'utilisateur");
 
user.setOpaque(false);
// JButton bd = new JButton("Créer la base de données");
final JButton up = new JButton("Mise à niveau de la base");
up.setOpaque(false);
up.addActionListener(new ActionListener() {
 
@Override
185,9 → 193,10
}
}
 
updateSocieteTable(conf.getRoot());
// ///////////// updateSocieteTable(conf.getRoot());
 
// we need to upgrade all roots
// ///////////////////////////
conf.getSystemRoot().getRootsToMap().clear();
conf.getSystemRoot().refetch();
 
227,7 → 236,12
}
}
 
if (childName.startsWith(conf.getAppName()) || childName.equalsIgnoreCase("Default")) {
if (DEBUG_FK) {
findBadForeignKey(root);
}
if (childName.equalsIgnoreCase("Common")) {
updateCommon(root);
} else if (childName.startsWith(conf.getAppName()) || childName.equalsIgnoreCase("Default")) {
SQLUtils.executeAtomic(ds, new SQLUtils.SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
436,12 → 450,16
c.insets = new Insets(10, 3, 2, 2);
this.add(new JLabelBold("Paramètrages de la base de données"), c);
c.gridy++;
c.insets = DefaultGridBagConstraints.getDefaultInsets();
this.add(new JLabel("Création des fonctions SQL nécessaires (plpgsql)."), c);
c.gridy++;
c.weightx = 0;
c.anchor = GridBagConstraints.EAST;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.insets = DefaultGridBagConstraints.getDefaultInsets();
 
JButton buttonPL = new JButton("Lancer");
buttonPL.setOpaque(false);
buttonPL.addActionListener(new ActionListener() {
 
@Override
473,6 → 491,11
c.insets = new Insets(10, 3, 2, 2);
this.add(new JLabelBold("Mise à niveau de la base OpenConcerto"), c);
c.gridy++;
c.insets = DefaultGridBagConstraints.getDefaultInsets();
this.add(new JLabel("Cette opération est nécessaire à chaque mise à jour du logiciel."), c);
c.gridy++;
this.add(new JLabel("La mise à niveau peut prendre plusieurs minutes."), c);
c.gridy++;
this.add(this.bar, c);
c.gridy++;
c.weightx = 0;
479,7 → 502,7
c.anchor = GridBagConstraints.EAST;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
c.insets = DefaultGridBagConstraints.getDefaultInsets();
 
this.add(up, c);
 
c.anchor = GridBagConstraints.WEST;
589,6 → 612,13
}
 
private void updateToV1Dot2(final DBRoot root) throws SQLException {
// bigint -> int ID_METRIQUE BON_DE_LIVRAISON_ELEMENT
final SQLTable tableLivraisonElement = root.getTable("BON_DE_LIVRAISON_ELEMENT");
AlterTable alter = new AlterTable(tableLivraisonElement);
alter.alterColumn("ID_METRIQUE_2", EnumSet.of(Properties.TYPE), "integer", null, null);
String req3 = alter.asString();
root.getDBSystemRoot().getDataSource().execute(req3);
 
final SQLTable tableDevis = root.getTable("DEVIS");
final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
if (!tableDevis.getFieldsName().contains("DATE_VALIDITE")) {
1334,6 → 1364,7
final SQLDataSource ds = sysRoot.getDataSource();
System.out.println("InstallationPanel.InstallationPanel() UPDATE COMMERCIAL " + root);
// Fix commercial Ordre
 
SQLTable tableCommercial = root.getTable("COMMERCIAL");
CorrectOrder orderCorrect = new CorrectOrder(sysRoot);
orderCorrect.change(tableCommercial);
1498,6 → 1529,136
}
}
 
private void findBadForeignKey(DBRoot root) {
Set<SQLTable> tables = root.getTables();
for (SQLTable table : tables) {
findBadForeignKey(root, table);
}
 
}
 
private void findBadForeignKey(DBRoot root, SQLTable table) {
System.out.println("====================================== " + table.getName());
Set<SQLField> ffields = table.getForeignKeys();
Set<SQLField> allFields = table.getFields();
 
Set<String> keysString = SQLKey.foreignKeys(table);
for (String string : keysString) {
ffields.add(table.getField(string));
}
 
if (ffields.size() == 0) {
System.out.println("No foreign fields");
}
System.out.println("Foreign field for table " + table.getName() + ":" + ffields);
// Map Champs-> Table sur lequel il pointe
Map<SQLField, SQLTable> map = new HashMap<SQLField, SQLTable>();
Set<SQLTable> extTables = new HashSet<SQLTable>();
for (SQLField sqlField : ffields) {
SQLTable t = null;
try {
t = SQLKey.keyToTable(sqlField);
} catch (Exception e) {
System.out.println("Ignoring field:" + sqlField.getName());
}
if (t == null) {
System.out.println("Unable to find table for ff " + sqlField.getName());
} else {
extTables.add(t);
map.put(sqlField, t);
}
}
// Verification des datas
System.out.println("Foreign table for table " + table.getName() + ":" + extTables);
// Recupere les ids de toutes les tables
Map<SQLTable, Set<Number>> ids = getIdsForTables(extTables);
 
//
SQLSelect s = new SQLSelect(root.getBase(), true);
if (table.getPrimaryKeys().size() != 1) {
return;
}
s.addSelect(table.getKey());
for (SQLField sqlField : map.keySet()) {
s.addSelect(sqlField);
}
List<Map> result = root.getDBSystemRoot().getDataSource().execute(s.asString());
for (Map resultRow : result) {
 
// Pour toutes les lignes
Set<String> fields = resultRow.keySet();
for (String field : fields) {
// Pour tous les champs
SQLField fField = table.getField(field);
if (table.getPrimaryKeys().contains(fField)) {
continue;
}
SQLTable fTable = map.get(fField);
if (fTable == null) {
System.out.println("Error: null table for field" + field);
continue;
}
Set<Number> values = ids.get(fTable);
 
final Object id = resultRow.get(field);
if (id == null) {
continue;
} else if (!values.contains((Number) id)) {
System.out.println("Checking row " + resultRow);
System.out.println("Error: No id found in table " + fTable.getName() + " for row " + field + "in table " + table.getName() + " " + resultRow + " knowns id:" + values);
}
}
}
System.out.println("======================================\n");
}
 
private Map<SQLTable, Set<Number>> getIdsForTables(Set<SQLTable> extTables) {
Map<SQLTable, Set<Number>> result = new HashMap<SQLTable, Set<Number>>();
for (SQLTable sqlTable : extTables) {
result.put(sqlTable, getIdsForTable(sqlTable));
}
return result;
}
 
private Set<Number> getIdsForTable(SQLTable table) {
final DBRoot dbRoot = table.getDBRoot();
SQLSelect s = new SQLSelect(dbRoot.getBase(), true);
s.addSelect(table.getKey());
List<Number> result = dbRoot.getDBSystemRoot().getDataSource().executeCol(s.asString());
return new HashSet<Number>(result);
}
 
private void updateCommon(DBRoot root) throws SQLException {
// rm ID 3 à 49 de EXERCICE_COMMON
final SQLTable tableExercice = root.getTable("EXERCICE_COMMON");
String req1a = "DELETE FROM " + tableExercice.getSQLName().quote() + " WHERE ";
req1a += new Where(tableExercice.getKey(), 3, 49).getClause();
root.getDBSystemRoot().getDataSource().execute(req1a);
// et 53-57
root.getDBSystemRoot().getDataSource().execute(req1a);
String req1b = "DELETE FROM " + tableExercice.getSQLName().quote() + " WHERE ";
req1b += new Where(tableExercice.getKey(), 53, 57).getClause();
root.getDBSystemRoot().getDataSource().execute(req1b);
//
 
// TACHE_COMMON, ID_USER_COMMON_*=0 -> 1
for (final String f : Arrays.asList("ID_USER_COMMON_TO", "ID_USER_COMMON_CREATE", "ID_USER_COMMON_ASSIGN_BY")) {
final SQLTable tableTache = root.getTable("TACHE_COMMON");
final UpdateBuilder updateBuilder = new UpdateBuilder(tableTache);
updateBuilder.set(f, "1").setWhere(new Where(tableTache.getField(f), "=", 0));
String req2 = updateBuilder.asString();
root.getDBSystemRoot().getDataSource().execute(req2);
}
// rm ID 43 - 47 de SOCIETE_COMMON
final SQLTable tableSociete = root.getTable("SOCIETE_COMMON");
String req3 = "DELETE FROM " + tableSociete.getSQLName().quote() + " WHERE ";
req3 += new Where(tableSociete.getKey(), 43, 47).getClause();
root.getDBSystemRoot().getDataSource().execute(req3);
 
// FK
new AddFK(root.getDBSystemRoot()).change(root);
}
 
private void updateSocieteTable(DBRoot root) throws SQLException {
SQLTable table = root.findTable("SOCIETE_COMMON");
boolean alter = false;
/trunk/OpenConcerto/src/org/openconcerto/erp/config/ComptaPropsConfiguration.java
157,7 → 157,6
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.ShowAs;
import org.openconcerto.sql.element.GlobalMapper;
import org.openconcerto.sql.element.RowItemViewMetadata;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.SharedSQLElement;
660,8 → 659,22
for (SQLElement sqlElement : elements) {
GlobalMapper.getInstance().map(sqlElement.getCode() + ".element", this);
}
 
String s = "";
for (SQLElement sqlElement : elements) {
try {
SQLElement e = dir.getElementForCode(sqlElement.getCode());
if (e == null) {
s += "Error while retrieving element from code " + sqlElement.getCode() + "\n";
}
} catch (Throwable e) {
s += "Error while retrieving element from code " + sqlElement.getCode() + " :\n " + e.getMessage() + "\n";
}
}
if (!s.trim().isEmpty()) {
JOptionPane.showMessageDialog(new JFrame(), s);
System.out.println(s);
}
}
 
private void setSocieteSQLInjector() {
final DBRoot rootSociete = getRootSociete();
819,12 → 832,7
new Thread() {
public void run() {
Configuration.getInstance().getSystemRoot().getGraph();
try {
metadata = new RowItemViewMetadata(getRootSociete());
} catch (SQLException e) {
ExceptionHandler.handle("Metadata error", e);
}
}
}.start();
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/modules/ModuleManager.java
101,6 → 101,10
return instance;
}
 
private static String getMDVariant(ModuleFactory f) {
return f.getID();
}
 
// only one version of each module
private final Map<String, ModuleFactory> factories;
private final Map<String, AbstractModule> runningModules;
782,15 → 786,24
throw new Exception("Couldn't install module " + module, e);
}
try {
final Set<SQLTable> tablesWithMD;
final String mdVariant = getMDVariant(module.getFactory());
final InputStream labels = module.getClass().getResourceAsStream("labels.xml");
if (labels != null) {
try {
getConf().getTranslator().load(getRoot(), labels);
// use module ID as variant to avoid overwriting
tablesWithMD = getConf().getTranslator().load(getRoot(), mdVariant, labels);
} finally {
labels.close();
}
} else {
tablesWithMD = Collections.emptySet();
}
this.registerSQLElements(module);
// insert just loaded labels into the search path
for (final SQLTable tableWithDoc : tablesWithMD) {
this.getDirectory().getElement(tableWithDoc).addToMDPath(mdVariant);
}
this.setupComponents(module);
module.start();
} catch (Exception e) {
846,6 → 859,12
final AbstractModule m = this.runningModules.remove(id);
m.stop();
this.tearDownComponents(m);
// perhaps record which element this module modified in start()
final String mdVariant = getMDVariant(f);
for (final SQLElement elem : this.getDirectory().getElements()) {
elem.removeFromMDPath(mdVariant);
}
getConf().getTranslator().removeDescFor(null, null, mdVariant, null);
if (persistent)
getRunningIDsPrefs().remove(m.getFactory().getID());
assert !this.isModuleRunning(id);
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationXML.java
723,7 → 723,7
pathDest.mkdirs();
}
 
fDest = SheetUtils.convertToOldFile(fileName, pathDest, fDest);
fDest = SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
 
// Sauvegarde
try {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeXML.java
485,7 → 485,7
pathDest.mkdirs();
}
 
SheetUtils.convertToOldFile(fileName, pathDest, fDest);
SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
 
// Sauvegarde
try {
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/AbstractJOOReportsSheet.java
13,7 → 13,6
package org.openconcerto.erp.generationDoc;
 
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStream;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.preferences.PrinterNXProps;
23,10 → 22,10
import org.openconcerto.odtemplate.engine.OGNLDataModel;
import org.jopendocument.link.Component;
import org.jopendocument.link.OOConnexion;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.Tuple2;
 
import java.io.BufferedInputStream;
import java.io.File;
91,10 → 90,10
if (this.askOverwriting) {
int answer = JOptionPane.showConfirmDialog(null, "Voulez vous écraser le document ?", "Remplacement d'un document", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
SheetUtils.convertToOldFile(fileName, outputDir, fileOutOO, ".odt");
SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, outputDir, fileOutOO, ".odt");
}
} else {
SheetUtils.convertToOldFile(fileName, outputDir, fileOutOO, ".odt");
SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, outputDir, fileOutOO, ".odt");
}
}
 
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/SheetUtils.java
13,6 → 13,9
package org.openconcerto.erp.generationDoc;
 
import org.openconcerto.erp.preferences.GenerationDocGlobalPreferencePanel;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.utils.ExceptionHandler;
 
import java.awt.Graphics2D;
38,9 → 41,9
 
public class SheetUtils {
 
public static File convertToOldFile(String fileName, File pathDest, File fDest) {
public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest) {
// FIXME: !!!!!!!!
return convertToOldFile(fileName, pathDest, fDest, ".ods");
return convertToOldFile(root, fileName, pathDest, fDest, ".ods");
}
 
/**
51,8 → 54,9
* @param fDest
* @return
*/
public static File convertToOldFile(String fileName, File pathDest, File fDest, String extension) {
if (fDest.exists()) {
public static File convertToOldFile(DBRoot root, String fileName, File pathDest, File fDest, String extension) {
SQLPreferences prefs = new SQLPreferences(root);
if (prefs.getBoolean(GenerationDocGlobalPreferencePanel.HISTORIQUE, true) && fDest.exists()) {
int i = 0;
String destName = fileName;
File pathOld = new File(pathDest, "Historique");
/trunk/OpenConcerto/src/org/openconcerto/erp/generationDoc/OOgenerationListeColumnXML.java
438,7 → 438,7
pathDest.mkdirs();
}
 
SheetUtils.convertToOldFile(fileName, pathDest, fDest);
SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
 
// Sauvegarde
try {
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/shipment/element/BonDeLivraisonItemSQLElement.java
111,4 → 111,8
 
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/credit/element/AvoirClientElementSQLElement.java
70,4 → 70,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/order/element/CommandeClientElementSQLElement.java
24,7 → 24,6
 
import javax.swing.JTextField;
 
 
public class CommandeClientElementSQLElement extends ComptaSQLConfElement {
 
public CommandeClientElementSQLElement() {
73,4 → 72,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/EcheanceClientSQLElement.java
155,4 → 155,9
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".commitment";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/invoice/element/SaisieVenteFactureItemSQLElement.java
164,4 → 164,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/EtatDevisSQLElement.java
64,4 → 64,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".state";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/quote/element/DevisItemSQLElement.java
82,4 → 82,8
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ReferenceArticleSQLElement.java
324,4 → 324,9
return (rowVals1.getObject("CODE").equals(rowVals2.getObject("CODE")) && rowVals1.getString("VALEUR_METRIQUE_1").equals(rowVals2.getString("VALEUR_METRIQUE_1"))
&& rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".ref";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleDesignationSQLElement.java
92,4 → 92,8
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".name";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ArticleTarifSQLElement.java
64,4 → 64,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".price";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/ModeVenteArticleSQLElement.java
76,4 → 76,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".sale";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/MetriqueSQLElement.java
77,4 → 77,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".quantity";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/product/element/FamilleArticleSQLElement.java
163,4 → 163,8
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".family";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/TicketCaisseSQLElement.java
56,4 → 56,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".ticket";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/sales/pos/element/SaisieVenteComptoirSQLElement.java
919,4 → 919,9
}
}
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".sale";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/ui/IListFilterDatePanel.java
45,10 → 45,10
private JDate dateDu, dateAu;
 
private Map<IListe, SQLField> mapList;
 
// Cache des transformers initiaux
private Map<IListe, ITransformer<SQLSelect, SQLSelect>> mapListTransformer;
// Liste des filtres
private Map<String, Tuple2<Date, Date>> map;
private ITransformer<SQLSelect, SQLSelect> t;
 
private final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
124,10 → 124,6
return m;
}
 
public void setITransformer(ITransformer<SQLSelect, SQLSelect> t) {
this.t = t;
}
 
public IListFilterDatePanel(IListe l, SQLField fieldDate, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
147,6 → 143,12
 
this.setBorder(BorderFactory.createTitledBorder("Période"));
this.mapList = mapList;
 
this.mapListTransformer = new HashMap<IListe, ITransformer<SQLSelect, SQLSelect>>();
for (IListe l : mapList.keySet()) {
this.mapListTransformer.put(l, l.getRequest().getSelectTransf());
}
 
this.dateDu = new JDate();
this.dateAu = new JDate();
this.map = m;
229,16 → 231,10
 
if (this.dateAu.getValue() == null && this.dateDu.getValue() == null) {
System.err.println("Null ");
if (this.t != null) {
for (IListe list : this.mapList.keySet()) {
 
list.getRequest().setSelectTransf(this.t);
list.getRequest().setSelectTransf(this.mapListTransformer.get(list));
}
} else {
for (IListe list : this.mapList.keySet()) {
list.getRequest().setSelectTransf(null);
}
}
return;
}
 
250,11 → 246,12
c.set(Calendar.MINUTE, 0);
c.set(Calendar.MILLISECOND, 1);
 
for (IListe list : this.mapList.keySet()) {
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
ITransformer<SQLSelect, SQLSelect> t = mapListTransformer.get(list);
if (t != null) {
input = t.transformChecked(input);
}
273,12 → 270,13
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.MILLISECOND, 59);
for (IListe list : this.mapList.keySet()) {
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
 
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
ITransformer<SQLSelect, SQLSelect> t = mapListTransformer.get(list);
if (t != null) {
input = t.transformChecked(input);
}
302,12 → 300,13
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.MILLISECOND, 1);
for (IListe list : this.mapList.keySet()) {
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
 
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
ITransformer<SQLSelect, SQLSelect> t = mapListTransformer.get(list);
if (t != null) {
input = t.transformChecked(input);
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/MoisSQLElement.java
75,4 → 75,9
}
};
}
 
@Override
protected String createCode() {
return "month";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/DepartementSQLElement.java
82,4 → 82,10
}
};
}
 
@Override
protected String createCode() {
return "department";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/ComptaSQLConfElement.java
73,6 → 73,10
 
@Override
protected String createCode() {
return createCodeFromPackage();
}
 
protected String createCodeFromPackage() {
String canonicalName = getClass().getName();
if (canonicalName.contains("erp.core") && canonicalName.contains(".element")) {
int i = canonicalName.indexOf("erp.core") + 9;
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/LangueSQLElement.java
74,4 → 74,9
}
};
}
 
@Override
protected String createCode() {
return "language";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/PaysSQLElement.java
90,4 → 90,9
}
};
}
 
@Override
protected String createCode() {
return "country";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/NumerotationAutoSQLElement.java
516,4 → 516,8
 
}
 
@Override
protected String createCode() {
return "autonumbering";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/TitrePersonnelSQLElement.java
84,4 → 84,9
}
};
}
 
@Override
protected String createCode() {
return "civility";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/AdresseCommonSQLElement.java
48,4 → 48,9
public SQLComponent createComponent() {
return new AdresseCommonSQLComponent(this);
}
 
@Override
protected String createCode() {
return "common.address";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/StyleSQLElement.java
74,4 → 74,8
};
}
 
@Override
protected String createCode() {
return "style";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/common/element/AdresseSQLElement.java
47,4 → 47,9
public SQLComponent createComponent() {
return new AdresseSQLComponent(this);
}
 
@Override
protected String createCode() {
return "address";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/reports/history/ui/ListeHistoriquePanel.java
149,15 → 149,6
liste.getListe().getRequest().setWhere(w);
}
liste.getListe().setSQLEditable(false);
liste.getListe().getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
 
@Override
public SQLSelect transformChecked(SQLSelect input) {
// TODO Raccord de méthode auto-généré
System.err.println(input);
return input;
}
});
// Set renderer
setRenderer(liste);
 
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/MouvementStockSQLElement.java
264,4 → 264,9
System.err.println("Aucun mouvement associé, impossible de modifier ou d'accéder à la source de cette ecriture!");
}
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".transaction";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/stock/element/ElementStockSQLElement.java
114,4 → 114,9
 
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/supplier/element/EcheanceFournisseurSQLElement.java
122,4 → 122,8
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".commitment";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/CommandeElementSQLElement.java
24,7 → 24,6
 
import javax.swing.JTextField;
 
 
public class CommandeElementSQLElement extends ComptaSQLConfElement {
 
public CommandeElementSQLElement() {
73,4 → 72,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/element/SaisieAchatSQLElement.java
61,4 → 61,8
return new SaisieAchatSQLComponent(this);
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".purchase";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/order/component/CommandeSQLComponent.java
32,6 → 32,8
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.JUniqueTextField;
import org.openconcerto.sql.users.UserManager;
137,6 → 139,38
this.addRequiredSQLObject(boxEnCours, "EN_COURS");
}
 
// Fournisseur
if (getTable().contains("ID_CONTACT_FOURNISSEUR")) {
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel(getLabelFor("ID_CONTACT_FOURNISSEUR"), SwingConstants.RIGHT), c);
 
c.gridx = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
final ElementComboBox boxContactFournisseur = new ElementComboBox();
final SQLElement contactElement = Configuration.getInstance().getDirectory().getElement("CONTACT_FOURNISSEUR");
boxContactFournisseur.init(contactElement, new ComboSQLRequest(contactElement.getComboRequest()));
this.add(boxContactFournisseur, c);
this.addView(boxContactFournisseur, "ID_CONTACT_FOURNISSEUR", REQ);
 
fourn.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent arg0) {
// TODO Raccord de méthode auto-généré
if (fourn.getSelectedRow() != null) {
boxContactFournisseur.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_FOURNISSEUR"), "=", fourn.getSelectedRow().getID()));
} else {
boxContactFournisseur.getRequest().setWhere(null);
}
}
});
}
// Adresse de livraison
if (getTable().getFieldsName().contains("ID_ADRESSE")) {
c.gridx = 0;
147,13 → 181,13
c.gridx++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridy++;
this.addView("ID_ADRESSE");
final DefaultElementSQLObject comp = (DefaultElementSQLObject) this.getView("ID_ADRESSE").getComp();
 
if (getTable().getFieldsName().contains("LIVRAISON_F")) {
final JCheckBox boxLivr = new JCheckBox("Livré par le fournisseur");
this.add(boxLivr, c);
this.addSQLObject(boxLivr, "LIVRAISON_F");
c.gridy++;
this.addView("ID_ADRESSE");
final DefaultElementSQLObject comp = (DefaultElementSQLObject) this.getView("ID_ADRESSE").getComp();
this.add(comp, c);
boxLivr.addActionListener(new ActionListener() {
 
@Override
172,10 → 206,12
comp.setCreated(false);
}
}
 
}
});
}
 
});
c.gridy++;
this.add(comp, c);
this.add(this.getView("ID_ADRESSE").getComp(), c);
}
c.gridwidth = 1;
322,6 → 358,7
c.weightx = 1;
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
 
panel.add(new TitledSeparator(getLabelFor("INFOS")), c);
 
c.gridy++;
362,8 → 399,34
} else {
addSQLObject(poids, "T_POIDS");
}
 
DeviseField textPortHT = new DeviseField();
 
if (getTable().contains("PORT_HT")) {
addRequiredSQLObject(textPortHT, "PORT_HT");
final JPanel panelPoids = new JPanel();
 
panelPoids.add(new JLabel(getLabelFor("PORT_HT")), c);
 
// textPortHT.setEnabled(false);
textPortHT.setHorizontalAlignment(JTextField.RIGHT);
// textPortHT.setDisabledTextColor(Color.BLACK);
 
panelPoids.add(textPortHT, c);
 
c.gridx++;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
c.gridwidth = 1;
c.gridheight = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.NORTHEAST;
panel.add(panelPoids, c);
DefaultGridBagConstraints.lockMinimumSize(panelPoids);
}
// Total
DeviseField textPortHT = new DeviseField();
 
DeviseField textRemiseHT = new DeviseField();
DeviseField fieldHT = new DeviseField();
DeviseField fieldTVA = new DeviseField();
377,6 → 440,7
addRequiredSQLObject(fieldDevise, "T_DEVISE");
addRequiredSQLObject(fieldHT, "T_HT");
addRequiredSQLObject(fieldTVA, "T_TVA");
 
addRequiredSQLObject(fieldTTC, "T_TTC");
addRequiredSQLObject(fieldService, "T_SERVICE");
final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/component/BonReceptionSQLComponent.java
41,6 → 41,7
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.TitledSeparator;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.preferences.DefaultProps;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.GestionDevise;
57,7 → 58,6
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
305,8 → 305,9
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
final JTextArea textInfos = new JTextArea(4, 4);
final ITextArea textInfos = new ITextArea(4, 4);
JScrollPane scrollPane = new JScrollPane(textInfos);
textInfos.setBorder(null);
DefaultGridBagConstraints.lockMinimumSize(scrollPane);
 
this.add(textInfos, c);
/trunk/OpenConcerto/src/org/openconcerto/erp/core/supplychain/receipt/element/BonReceptionElementSQLElement.java
24,7 → 24,6
 
import javax.swing.JTextField;
 
 
public class BonReceptionElementSQLElement extends ComptaSQLConfElement {
 
public BonReceptionElementSQLElement() {
73,4 → 72,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/TypeLettreRelanceSQLElement.java
22,7 → 22,6
 
import javax.swing.JTextField;
 
 
public class TypeLettreRelanceSQLElement extends ComptaSQLConfElement {
 
public TypeLettreRelanceSQLElement() {
54,4 → 53,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".chaseletter.type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ReferenceClientSQLElement.java
67,4 → 67,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".ref";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/ModeleCourrierClientSQLElement.java
27,7 → 27,6
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
 
public class ModeleCourrierClientSQLElement extends ComptaSQLConfElement {
 
public ModeleCourrierClientSQLElement() {
86,4 → 85,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".mailtemplate";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/CourrierClientSQLElement.java
351,4 → 351,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".mail";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/customerrelationship/customer/element/RelanceSQLElement.java
267,4 → 267,9
 
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".chaseletter";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AxeAnalytiqueSQLElement.java
47,4 → 47,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".analytic.axis";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/JournalSQLElement.java
103,4 → 103,9
return -1;
}
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".book";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AnalytiqueSQLElement.java
905,4 → 905,9
}
}
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".analytic";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCESQLElement.java
319,4 → 319,9
final String numeroDefault = getComptePceDefault(name);
return getId(numeroDefault);
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".code.enterprise";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/MouvementSQLElement.java
223,4 → 223,10
return id;
 
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".entry";
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AssociationCompteAnalytiqueSQLElement.java
249,4 → 249,9
table.getTableHeader().setReorderingAllowed(false);
return table;
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".analytic.account.relation";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ComptePCGSQLElement.java
165,33 → 165,8
};
}
 
/*
* public static final void supprimePointInterrogation() { SQLTable compteTable =
* Configuration.getInstance().getBase().getTable("COMPTE_PCG");
*
* SQLSelect selCompte = new SQLSelect(Configuration.getInstance().getBase());
*
* selCompte.addSelect(compteTable.getField("ID"));
*
* String req = selCompte.asString();
*
* Object obj = Configuration.getInstance().getBase().getDataSource().execute(req, new
* ArrayListHandler());
*
* List myList = (List) obj; SQLRowValues vals = new SQLRowValues(compteTable);
*
* for (int i = 0; i < myList.size(); i++) {
*
* Object[] tmp = (Object[]) myList.get(i);
*
* SQLRow row = compteTable.getRow(new Integer(tmp[0].toString()).intValue());
*
* String nom = row.getString("NOM"); String infos = row.getString("INFOS");
*
* vals.put("NOM", nom.trim().replace('?', '\'')); vals.put("INFOS", infos.trim().replace('?',
* '\''));
*
* try { vals.update(new Integer(tmp[0].toString()).intValue()); } catch (NumberFormatException
* e) { e.printStackTrace(); } catch (SQLException e) { // e.printStackTrace(); } } }
*/
@Override
protected String createCode() {
return createCodeFromPackage() + ".code.national";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/ClasseCompteSQLElement.java
50,4 → 50,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".accountclass";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/EcritureSQLElement.java
595,4 → 595,9
});
frameSaisieKm.setVisible(true);
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".entry.item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/TypeComptePCGSQLElement.java
48,4 → 48,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".account.type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmItemSQLElement.java
57,4 → 57,8
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".userentry.item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/PieceSQLElement.java
57,4 → 57,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".piece";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/PosteAnalytiqueSQLElement.java
62,4 → 62,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".analytic.set";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/RepartitionAnalytiqueSQLElement.java
52,4 → 52,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".distribution";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/SaisieKmSQLElement.java
686,4 → 686,9
}
 
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".userentry";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/NatureCompteSQLElement.java
52,4 → 52,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".account.kind";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/RepartitionAnalytiqueElementSQLElement.java
49,4 → 49,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".distributionitem";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/element/AssociationAnalytiqueSQLElement.java
52,4 → 52,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".analytic.relation";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/accounting/ui/ComptaPrefTreeNode.java
21,6 → 21,7
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.modules.ModulePreferencePanelDesc;
import org.openconcerto.erp.preferences.GenerationDeclarationDocPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocGlobalPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocumentComptaPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocumentGestCommPreferencePanel;
import org.openconcerto.erp.preferences.GenerationDocumentPayePreferencePanel;
102,6 → 103,8
final PrefTreeNode nNum = new PrefTreeNode(NumerotationPreferencePanel.class, "Numérotation", new String[] { "numérotation" });
nsGlobale.add(nNum);
 
nsGlobale.add(new PrefTreeNode(GenerationDocGlobalPreferencePanel.class, "Génération des Documents", new String[] { "documents" }));
 
// Impression
final PrefTreeNode nPrint = new PrefTreeNode(EmptyPreferencePanel.class, "Impression", new String[] { "Impressions" });
final PrefTreeNode nPrintGestComm = new PrefTreeNode(ImpressionGestCommPreferencePanel.class, "Gestion commerciale", new String[] { "impression" });
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/EncaisserMontantElementSQLElement.java
56,4 → 56,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ChequeAEncaisserSQLElement.java
123,4 → 123,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".cheque";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ChequeAvoirClientSQLElement.java
107,4 → 107,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".cheque.due";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ChequeFournisseurSQLElement.java
104,4 → 104,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".cheque.supplier";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ModeDeReglementSQLElement.java
119,4 → 119,9
}
return cal.getTime();
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".mode";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/ReglerMontantSQLElement.java
300,4 → 300,9
}
};
};
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".regulation";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/finance/payment/element/TypeReglementSQLElement.java
105,4 → 105,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/component/RubriqueSQLComponent.java
New file
0,0 → 1,161
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.humanresources.payroll.component;
 
import org.openconcerto.erp.core.humanresources.payroll.element.VariablePayeSQLElement;
import org.openconcerto.sql.element.BaseSQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.warning.JLabelWarning;
import org.openconcerto.utils.checks.ValidState;
import org.openconcerto.utils.text.SimpleDocumentListener;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
 
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
 
public abstract class RubriqueSQLComponent extends BaseSQLComponent {
 
private final JTextField textCode;
private final JLabel labelWarningBadName;
private final JTextField textLibelle = new JTextField();
private ValidState validCode = ValidState.getTrueInstance();
 
public RubriqueSQLComponent(SQLElement element) {
super(element);
this.textCode = new JTextField();
this.textCode.getDocument().addDocumentListener(new SimpleDocumentListener() {
@Override
public void update(DocumentEvent e) {
updateCodeValidity();
}
});
this.labelWarningBadName = new JLabelWarning("Code déjà attribué");
}
 
@Override
public final void addViews() {
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
 
// Code
JLabel labelCode = new JLabel(getLabelFor("CODE"));
labelCode.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelCode, c);
 
c.gridx++;
c.weightx = 1;
this.add(this.textCode, c);
c.weightx = 0;
 
c.gridx++;
this.add(this.labelWarningBadName, c);
this.labelWarningBadName.setVisible(false);
 
// Libelle
c.gridy++;
c.gridx = 0;
JLabel labelNom = new JLabel(getLabelFor("NOM"));
labelNom.setHorizontalAlignment(SwingConstants.RIGHT);
this.add(labelNom, c);
 
final boolean nl = this.newline();
c.gridx++;
c.gridwidth = nl ? GridBagConstraints.REMAINDER : 1;
c.weightx = 1;
this.add(this.textLibelle, c);
c.weightx = 0;
c.gridwidth = 1;
if (nl)
c.gridy++;
 
this.addRequiredSQLObject(this.textCode, "CODE");
this.addSQLObject(this.textLibelle, "NOM");
 
this.addViews(c);
}
 
// new line after Libellé ?
protected boolean newline() {
return true;
}
 
protected abstract void addViews(GridBagConstraints c);
 
private ValidState computeCodeValidity() {
final String code = this.textCode.getText().trim();
 
if (VariablePayeSQLElement.isForbidden(code))
return ValidState.createCached(false, "Code réservé");
 
// on vérifie que la variable n'existe pas déja
final SQLSelect selAllCodeName = new SQLSelect(getTable().getBase());
 
selAllCodeName.addSelectFunctionStar("count");
selAllCodeName.setWhere(new Where(getTable().getField("CODE"), "=", code));
 
final int idSelected = this.getSelectedID();
if (idSelected >= SQLRow.MIN_VALID_ID) {
selAllCodeName.andWhere(new Where(getTable().getField("ID"), "!=", idSelected));
}
 
final Number rubCount = (Number) getTable().getDBSystemRoot().getDataSource().executeScalar(selAllCodeName.asString());
if (rubCount.intValue() > 0)
return ValidState.createCached(false, "Code déjà attribué");
 
final SQLSelect selAllVarName = new SQLSelect(getTable().getBase());
final SQLTable tableVar = getTable().getTable("VARIABLE_PAYE");
selAllVarName.addSelectFunctionStar("count");
selAllVarName.setWhere(new Where(tableVar.getField("NOM"), "=", code));
final Number payVarCount = (Number) getTable().getDBSystemRoot().getDataSource().executeScalar(selAllVarName.asString());
 
return ValidState.createCached(payVarCount.intValue() == 0, "Code déjà attribué à une variable de paye");
}
 
private void updateCodeValidity() {
this.setValidCode(this.computeCodeValidity());
}
 
private final void setValidCode(ValidState state) {
if (!state.equals(this.validCode)) {
this.validCode = state;
final boolean visible = !this.validCode.isValid();
this.labelWarningBadName.setVisible(visible);
if (visible)
this.labelWarningBadName.setText(this.validCode.getValidationText());
this.fireValidChange();
}
}
 
@Override
public synchronized ValidState getValidState() {
return super.getValidState().and(this.validCode);
}
 
@Override
public void select(SQLRowAccessor r) {
super.select(r);
updateCodeValidity();
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ProfilPayeElementSQLElement.java
52,4 → 52,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.template.item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/VariableSalarieSQLElement.java
22,7 → 22,6
 
import javax.swing.JTextField;
 
 
public class VariableSalarieSQLElement extends ComptaSQLConfElement {
 
public VariableSalarieSQLElement() {
74,4 → 73,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".employe.variable";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CumulsPayeSQLElement.java
26,7 → 26,6
import javax.swing.JLabel;
import javax.swing.JTextField;
 
 
public class CumulsPayeSQLElement extends ComptaSQLConfElement {
public CumulsPayeSQLElement() {
super("CUMULS_PAYE", "un cumul de paye", "cumuls de paye");
118,4 → 117,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".total";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeContratTravailSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeContratTravailSQLElement extends AbstractCodeSQLElement {
 
public CodeContratTravailSQLElement() {
20,4 → 19,8
super("CODE_CONTRAT_TRAVAIL", "un code contrat travail", "codes contrats travail");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".contract.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/TypeRubriqueBrutSQLElement.java
19,4 → 19,8
super("TYPE_RUBRIQUE_BRUT", "un type de rubrique brut", "types de rubrique brut");
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category.type.raw";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/InfosSalariePayeSQLElement.java
365,4 → 365,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".info";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ClassementConventionnelSQLElement.java
27,7 → 27,6
import javax.swing.JTextField;
import javax.swing.SwingConstants;
 
 
public class ClassementConventionnelSQLElement extends ComptaSQLConfElement {
 
public ClassementConventionnelSQLElement() {
138,5 → 137,11
this.addSQLObject(textIndice, "INDICE");
}
};
 
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".convention";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ReglementPayeSQLElement.java
236,4 → 236,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".payment";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeRegimeSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeRegimeSQLElement extends AbstractCodeSQLElement {
 
public CodeRegimeSQLElement() {
20,4 → 19,8
super("CODE_REGIME", "un code régime", "codes régimes");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".governement.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RegimeBaseSQLElement.java
121,4 → 121,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".base";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ImpressionRubriqueSQLElement.java
53,4 → 53,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.print";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/TypeRubriqueNetSQLElement.java
19,4 → 19,8
super("TYPE_RUBRIQUE_NET", "un type de rubrique net", "types de rubrique net");
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category.type.net";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ProfilPayeSQLElement.java
219,4 → 219,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.template";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueCommSQLElement.java
15,6 → 15,7
 
import org.openconcerto.erp.core.common.ui.SQLJavaEditor;
import org.openconcerto.erp.core.humanresources.payroll.component.FormuleTreeNode;
import org.openconcerto.erp.core.humanresources.payroll.component.RubriqueSQLComponent;
import org.openconcerto.erp.core.humanresources.payroll.component.VariableTree;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.ElementSQLObject;
341,4 → 342,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category.comment";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeStatutCategorielSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeStatutCategorielSQLElement extends AbstractCodeSQLElement {
 
public CodeStatutCategorielSQLElement() {
20,4 → 19,8
super("CODE_STATUT_CATEGORIEL", "un code statut catégoriel", "codes statuts catégoriels");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".convention.category.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeStatutCategorielConventionnelSQLElement.java
19,4 → 19,8
super("CODE_STATUT_CAT_CONV", "un code statut catégoriel conventionnel", "codes statuts catégoriels conventionnel");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".convention.status.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeCaractActiviteSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeCaractActiviteSQLElement extends AbstractCodeSQLElement {
 
public CodeCaractActiviteSQLElement() {
20,4 → 19,8
super("CODE_CARACT_ACTIVITE", "un code caractéristique activité", "codes caractéristiques activités");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".convention.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/AcompteSQLElement.java
92,7 → 92,6
c.weightx = 0;
this.add(this.textMontant, c);
 
this.addRequiredSQLObject(this.comboSelSal, "ID_SALARIE");
this.addRequiredSQLObject(this.textMontant, "MONTANT");
}
128,4 → 127,9
 
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".advance";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueCotisationSQLElement.java
15,6 → 15,7
 
import org.openconcerto.erp.core.common.ui.SQLJavaEditor;
import org.openconcerto.erp.core.humanresources.payroll.component.FormuleTreeNode;
import org.openconcerto.erp.core.humanresources.payroll.component.RubriqueSQLComponent;
import org.openconcerto.erp.core.humanresources.payroll.component.VariableTree;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.ElementSQLObject;
314,4 → 315,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category.subscription";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueBrutSQLElement.java
15,6 → 15,7
 
import org.openconcerto.erp.core.common.ui.SQLJavaEditor;
import org.openconcerto.erp.core.humanresources.payroll.component.FormuleTreeNode;
import org.openconcerto.erp.core.humanresources.payroll.component.RubriqueSQLComponent;
import org.openconcerto.erp.core.humanresources.payroll.component.VariableTree;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.ElementSQLObject;
358,4 → 359,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category.raw";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/FichePayeSQLElement.java
1038,4 → 1038,9
int annee = rowFiche.getInt("ANNEE");
return ((anneeClot == 0) ? true : annee > anneeClot) || ((moisClot == 0 || moisClot == 13) ? true : mois > moisClot);
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".payslip";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeIdccSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeIdccSQLElement extends AbstractCodeSQLElement {
 
public CodeIdccSQLElement() {
20,4 → 19,8
super("IDCC", "un code de convention", "codes de conventions");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".conventions.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CaisseCotisationSQLElement.java
199,4 → 199,5
}
};
}
 
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/VariablePayeSQLElement.java
112,7 → 112,7
return l;
}
 
static final boolean isForbidden(final String code) {
public static final boolean isForbidden(final String code) {
final List<String> l = getForbiddenVarName();
for (int i = 0; i < l.size(); i++) {
if (l.get(i).trim().equalsIgnoreCase(code)) {
640,4 → 640,9
super.archive(getTable().getRow(id), true);
}
}
 
@Override
protected String createCode() {
return "humanresources.payroll.payment.variable";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/RubriqueNetSQLElement.java
15,6 → 15,7
 
import org.openconcerto.erp.core.common.ui.SQLJavaEditor;
import org.openconcerto.erp.core.humanresources.payroll.component.FormuleTreeNode;
import org.openconcerto.erp.core.humanresources.payroll.component.RubriqueSQLComponent;
import org.openconcerto.erp.core.humanresources.payroll.component.VariableTree;
import org.openconcerto.sql.element.ConfSQLElement;
import org.openconcerto.sql.element.ElementSQLObject;
349,4 → 350,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.category";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ModeReglementPayeSQLElement.java
22,7 → 22,6
 
import javax.swing.JTextField;
 
 
public class ModeReglementPayeSQLElement extends ComptaSQLConfElement {
public ModeReglementPayeSQLElement() {
super("MODE_REGLEMENT_PAYE", "un mode de règlement de paye", "modes de règlement de paye");
54,4 → 53,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".payment.type";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeStatutProfSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeStatutProfSQLElement extends AbstractCodeSQLElement {
 
public CodeStatutProfSQLElement() {
20,4 → 19,8
super("CODE_STATUT_PROF", "un code statut professionnel", "codes statuts professionnels");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".convention.job.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/FichePayeElementSQLElement.java
22,7 → 22,6
 
import javax.swing.JTextField;
 
 
public class FichePayeElementSQLElement extends ComptaSQLConfElement {
public FichePayeElementSQLElement() {
super("FICHE_PAYE_ELEMENT", "un élément de fiche de paye", "éléments de fiche de paye");
75,4 → 74,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".payslip.item";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeDroitContratSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeDroitContratSQLElement extends AbstractCodeSQLElement {
 
public CodeDroitContratSQLElement() {
20,4 → 19,8
super("CODE_DROIT_CONTRAT", "un code emploi", "codes emplois");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".rights.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CumulsCongesSQLElement.java
26,7 → 26,6
import javax.swing.JLabel;
import javax.swing.JTextField;
 
 
public class CumulsCongesSQLElement extends ComptaSQLConfElement {
public CumulsCongesSQLElement() {
super("CUMULS_CONGES", "un cumul de congés", "cumuls de congés");
85,4 → 84,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".vacation.total";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/PeriodeValiditeSQLElement.java
187,4 → 187,9
}
};
}
 
@Override
protected String createCode() {
return "humanresources.payroll.validity";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/ContratSalarieSQLElement.java
254,4 → 254,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".contract.employe";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/SalarieSQLElement.java
328,4 → 328,9
}
};
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".employe";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/payroll/element/CodeEmploiSQLElement.java
13,7 → 13,6
package org.openconcerto.erp.core.humanresources.payroll.element;
 
 
public class CodeEmploiSQLElement extends AbstractCodeSQLElement {
 
public CodeEmploiSQLElement() {
20,4 → 19,8
super("CODE_EMPLOI", "un code emploi", "codes emplois");
}
 
@Override
protected String createCode() {
return createCodeFromPackage() + ".job.code";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/EtatCivilSQLElement.java
333,4 → 333,9
};
 
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".info";
}
}
/trunk/OpenConcerto/src/org/openconcerto/erp/core/humanresources/employe/element/CommercialSQLElement.java
290,4 → 290,9
}
};
}
 
@Override
protected String createCode() {
return super.createCodeFromPackage() + ".salesman";
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/Diff.java
113,7 → 113,7
private String[] output(String file) throws JDOMException, IOException {
final File f = new File(file);
if (f.exists()) {
final ODSingleXMLDocument oodoc = ODSingleXMLDocument.createFromFile(f);
final ODSingleXMLDocument oodoc = ODSingleXMLDocument.createFromPackage(f);
// don't compare settings
oodoc.getChild("settings").detach();
String contentS = OUTPUTTER.outputString(oodoc.getDocument());
/trunk/OpenConcerto/src/org/openconcerto/openoffice/ODPackage.java
25,10 → 25,13
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.StreamUtils;
import org.openconcerto.utils.StringInputStream;
import org.openconcerto.utils.StringUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.Tuple3;
import org.openconcerto.utils.Zip;
import org.openconcerto.utils.ZippedFilesProcessor;
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.io.DataInputStream;
import org.openconcerto.xml.JDOMUtils;
import org.openconcerto.xml.Validator;
 
207,6 → 210,103
return pkg;
}
 
/**
* Read from the input stream into memory and close it.
*
* @param ins the package or flat XML.
* @param name the name, can be <code>null</code>.
* @return a package containing the document.
* @throws IOException if an error occurs.
*/
public static ODPackage createFromStream(final InputStream ins, final String name) throws IOException {
try {
return create(null, ins, name);
} finally {
ins.close();
}
}
 
public static ODPackage createFromFile(final File f) throws IOException {
final FileInputStream ins = new FileInputStream(f);
try {
return create(f, ins, f.getName());
} finally {
ins.close();
}
}
 
private static final int mimetypeZipEndOffset = 250;
 
// ATTN ins is *not* always closed
private static ODPackage create(final File f, InputStream ins, final String name) throws IOException {
// first use extension
final Tuple2<ContentTypeVersioned, Boolean> fromExt = name != null ? ContentTypeVersioned.fromExtension(FileUtils.getExtension(name)) : Tuple2.<ContentTypeVersioned, Boolean> nullInstance();
ContentTypeVersioned contentType = fromExt.get0();
Boolean flat = fromExt.get1();
// then content
if (flat == null) {
ins = new BufferedInputStream(ins);
final String xmlStart = "<?xml";
if (ins.markSupported())
ins.mark(Math.max(xmlStart.length(), mimetypeZipEndOffset));
else
throw new IllegalStateException("Mark unsupported on " + ins);
final byte[] buffer = new byte[xmlStart.length()];
ins.read(buffer);
if (xmlStart.equals(new String(buffer, StringUtils.ASCII))) {
// would have to parse the whole document
contentType = null;
flat = true;
} else {
ins.reset();
contentType = getType(ins);
if (contentType != null)
flat = false;
}
ins.reset();
}
final ODPackage res;
if (flat == null) {
res = null;
} else if (flat) {
try {
res = (f != null ? ODSingleXMLDocument.createFromFile(f) : ODSingleXMLDocument.createFromStream(ins)).getPackage();
} catch (JDOMException e) {
throw new IOException(e);
}
} else {
res = f != null ? new ODPackage(f) : new ODPackage(ins);
}
assert contentType == null || contentType == res.getContentType();
return res;
}
 
private static ContentTypeVersioned getType(final InputStream in) throws IOException {
final DataInputStream ins = new DataInputStream(in, true);
if (ins.read() != 'P' || ins.read() != 'K')
return null;
if (ins.skip(16) != 16)
return null;
final int compressedSize = ins.readInt();
final int uncompressedSize = ins.readInt();
// not a valid package and beyond that we would need to actually inflate the data
if (compressedSize != uncompressedSize)
return null;
final short fnameLength = ins.readShort();
if (fnameLength != MIMETYPE_ENTRY.length())
return null;
final short extraLength = ins.readShort();
final byte[] array = new byte[Math.max(fnameLength, compressedSize)];
ins.read(array, 0, fnameLength);
if (!new String(array, 0, fnameLength, StringUtils.ASCII).equals(MIMETYPE_ENTRY))
return null;
if (ins.skip(extraLength) != extraLength)
return null;
ins.read(array, 0, compressedSize);
final String data = new String(array, 0, compressedSize, MIMETYPE_ENC);
return ContentTypeVersioned.fromMime(data);
}
 
static private XMLVersion getVersion(final XMLFormatVersion fv, final ContentTypeVersioned ct) {
final XMLVersion v;
if (ct == null && fv == null)
247,6 → 347,12
this.doc = null;
}
 
/**
* Read from the input stream into memory and close it.
*
* @param ins the package.
* @throws IOException if <code>ins</code> couldn't be read.
*/
public ODPackage(InputStream ins) throws IOException {
this();
 
/trunk/OpenConcerto/src/org/openconcerto/openoffice/ODSingleXMLDocument.java
25,6 → 25,7
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
125,7 → 126,7
}
 
/**
* Create a document from a file.
* Create a document from a package.
*
* @param f an OpenDocument package file.
* @return the merged file.
132,12 → 133,30
* @throws JDOMException if the file is not a valid OpenDocument file.
* @throws IOException if the file can't be read.
*/
public static ODSingleXMLDocument createFromFile(File f) throws JDOMException, IOException {
public static ODSingleXMLDocument createFromPackage(File f) throws JDOMException, IOException {
// this loads all linked files
return new ODPackage(f).toSingle();
}
 
/**
* Create a document from a flat XML.
*
* @param f an OpenDocument XML file.
* @return the created file.
* @throws JDOMException if the file is not a valid OpenDocument file.
* @throws IOException if the file can't be read.
*/
public static ODSingleXMLDocument createFromFile(File f) throws JDOMException, IOException {
final ODSingleXMLDocument res = new ODSingleXMLDocument(OOUtils.getBuilder().build(f));
res.getPackage().setFile(f);
return res;
}
 
public static ODSingleXMLDocument createFromStream(InputStream ins) throws JDOMException, IOException {
return new ODSingleXMLDocument(OOUtils.getBuilder().build(ins));
}
 
/**
* fix bug when a SingleXMLDoc is used to create a document (for example with P2 and 1_P2), and
* then create another instance s2 with the previous document and add a second file (also with
* P2 and 1_P2) => s2 will contain P2, 1_P2, 1_P2, 1_1_P2.
/trunk/OpenConcerto/src/org/openconcerto/openoffice/ContentTypeVersioned.java
15,6 → 15,7
 
import static java.util.Arrays.asList;
import org.openconcerto.openoffice.ODPackage.RootElement;
import org.openconcerto.utils.Tuple2;
 
import org.jdom.Document;
import org.jdom.Element;
105,6 → 106,12
return this.extension;
}
 
public final String getFlatExtension() {
if (this.getVersion() == XMLVersion.OOo)
return null;
return 'f' + this.getExtension();
}
 
public final boolean isTemplate() {
return this.getMimeType().endsWith(TEMPLATE_SUFFIX);
}
271,4 → 278,17
return t;
return null;
}
 
// Boolean : is flat
static Tuple2<ContentTypeVersioned, Boolean> fromExtension(final String extension) {
if (extension != null && extension.length() != 0) {
for (final ContentTypeVersioned t : ContentTypeVersioned.values()) {
if (extension.equals(t.getExtension()))
return Tuple2.create(t, false);
if (extension.equals(t.getFlatExtension()))
return Tuple2.create(t, true);
}
}
return Tuple2.nullInstance();
}
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/generation/generator/ExtractGenerator.java
50,7 → 50,7
this.fireStatusChange(0);
try {
this.fireStatusChange(20);
ODSingleXMLDocument xml = ODSingleXMLDocument.createFromFile(this.fname);
ODSingleXMLDocument xml = ODSingleXMLDocument.createFromPackage(this.fname);
this.fireStatusChange(100);
return xml;
} catch (JDOMException exn) {
/trunk/OpenConcerto/src/org/openconcerto/openoffice/generation/ReportGeneration.java
312,7 → 312,7
final DocumentGenerator templateGenerator = this.getCommon().getStyleTemplateGenerator(this.type.getTemplate());
if (templateGenerator == null)
try {
f = ODSingleXMLDocument.createFromFile(this.type.getTemplate());
f = ODSingleXMLDocument.createFromPackage(this.type.getTemplate());
} catch (JDOMException e) {
throw new IOException("invalid template " + this.type.getTemplate(), e);
}
/trunk/OpenConcerto/src/org/openconcerto/openoffice/spreadsheet/MutableCell.java
159,8 → 159,15
if (currentType != null && currentType.canFormat(obj.getClass())) {
type = currentType;
} else {
type = ODValueType.forObject(obj);
final ODValueType tmp = ODValueType.forObject(obj);
// allow any Object
if (allowTypeChange && tmp == null) {
type = ODValueType.STRING;
obj = String.valueOf(obj);
} else {
type = tmp;
}
}
if (type == null) {
throw new IllegalArgumentException("Couldn't infer type of " + obj);
}
/trunk/OpenConcerto/src/org/openconcerto/ui/FormLayouter.java
94,10 → 94,11
*
* @param desc le label du champ
* @param comp le composant graphique d'edition ou null si titre
* @return the created label.
*/
public void add(String desc, Component comp) {
public JLabel add(String desc, Component comp) {
if (comp != null) {
this.add(desc, comp, this.defaultWidth);
return this.add(desc, comp, this.defaultWidth);
} else {
this.newLine();
final JLabel lab = new JLabel(desc);
105,6 → 106,7
this.layout.setRowSpec(this.getY() - 1, new RowSpec("10dlu"));
this.co.add(lab, this.constraints.xyw(this.getLabelX(), this.getY(), this.width * CELL_WIDTH - 1));
this.endLine();
return lab;
}
}
 
114,17 → 116,20
* @param desc le label du champ.
* @param comp le composant graphique d'edition.
* @param w la largeur, entre 1 et la largeur de ce layout, ou 0 pour toute la largeur.
* @return the created label.
* @throws NullPointerException if comp is <code>null</code>.
* @throws IllegalArgumentException if w is less than 1.
*/
public void add(String desc, Component comp, int w) {
public JLabel add(String desc, Component comp, int w) {
w = this.checkArgs(comp, w);
 
final int realWidth = this.getRealFieldWidth(w);
// Guillaume : right alignment like the Mac ; vertically centred for checkboxes
this.co.add(new JLabel(desc), this.constraints.xy(this.getLabelX(), this.getY(), CellConstraints.RIGHT, CellConstraints.CENTER));
final JLabel lab = new JLabel(desc);
this.co.add(lab, this.constraints.xy(this.getLabelX(), this.getY(), CellConstraints.RIGHT, CellConstraints.CENTER));
this.co.add(comp, this.constraints.xyw(this.getFieldX(), this.getY(), realWidth));
this.x += w;
return lab;
}
 
// assure that comp & w are valid, and do a newLine if necessary
142,11 → 147,11
return res;
}
 
public void addBordered(String desc, Component comp) {
this.addBordered(desc, comp, this.defaultWidth);
public JPanel addBordered(String desc, Component comp) {
return this.addBordered(desc, comp, this.defaultWidth);
}
 
public void addBordered(String desc, Component comp, int w) {
public JPanel addBordered(String desc, Component comp, int w) {
w = this.checkArgs(comp, w);
 
final int realWidth = w * CELL_WIDTH - 1;
158,6 → 163,7
 
this.co.add(p, this.constraints.xyw(this.getLabelX(), this.getY(), realWidth));
this.x += w;
return p;
}
 
private final int getRealFieldWidth(int w) {
194,11 → 200,12
this.x = this.width;
}
 
public void addRight(String desc, Component comp) {
public JLabel addRight(String desc, Component comp) {
this.newLine();
this.x = this.width - 1;
this.add(desc, comp);
final JLabel res = this.add(desc, comp);
this.endLine();
return res;
}
 
public void add(JButton btn) {
/trunk/OpenConcerto/src/org/openconcerto/odtemplate/statements/Include.java
143,7 → 143,7
final ODSingleXMLDocument res;
final CacheResult<ODSingleXMLDocument> cached = this.cache.check(ref);
if (cached.getState() == CacheResult.State.NOT_IN_CACHE) {
res = ODSingleXMLDocument.createFromFile(ref);
res = ODSingleXMLDocument.createFromPackage(ref);
this.cache.put(ref, res, Collections.<File> emptySet());
} else {
res = cached.getRes();
/trunk/OpenConcerto/src/org/openconcerto/sql/request/SQLFieldTranslator.java
14,10 → 14,22
package org.openconcerto.sql.request;
 
import org.openconcerto.sql.Log;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.SQLElementDirectory.DirectoryListener;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSchema;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLSyntax;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
import org.openconcerto.utils.CollectionUtils;
 
import java.io.File;
25,9 → 37,17
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.Preferences;
 
import org.jdom.Document;
import org.jdom.Element;
44,19 → 64,51
 
private static final RowItemDesc NULL_DESC = new RowItemDesc(null, null);
 
private static final String METADATA_TABLENAME = SQLSchema.FWK_TABLENAME_PREFIX + "RIV_METADATA";
private static final String ELEM_FIELDNAME = "ELEMENT_CODE";
private static final String COMP_FIELDNAME = "COMPONENT_CODE";
private static final String ITEM_FIELDNAME = "ITEM";
 
private static final String DOC_FIELDNAME = "DOCUMENTATION";
private static final String COL_TITLE_FIELDNAME = "COLUMN_TITLE";
private static final String LABEL_FIELDNAME = "LABEL";
 
private static final String CORE_VARIANT = "CORE";
private static final String DB_VARIANT = "DB";
 
static public SQLTable getMetaTable(final DBRoot root) throws SQLException {
if (!root.contains(METADATA_TABLENAME)) {
final SQLCreateTable createValueT = new SQLCreateTable(root, METADATA_TABLENAME);
createValueT.setPlain(true);
createValueT.addColumn(SQLSyntax.ID_NAME, createValueT.getSyntax().getPrimaryIDDefinition());
final String nullableVarChar = "varchar(" + Preferences.MAX_KEY_LENGTH + ")";
createValueT.addColumn(ELEM_FIELDNAME, nullableVarChar);
createValueT.addColumn(COMP_FIELDNAME, nullableVarChar);
createValueT.addColumn(ITEM_FIELDNAME, nullableVarChar + " NOT NULL");
createValueT.addUniqueConstraint("uniq", Arrays.asList(ELEM_FIELDNAME, COMP_FIELDNAME, ITEM_FIELDNAME));
createValueT.addVarCharColumn(LABEL_FIELDNAME, 256);
createValueT.addVarCharColumn(COL_TITLE_FIELDNAME, 256);
createValueT.addVarCharColumn(DOC_FIELDNAME, Math.min(8192, Preferences.MAX_VALUE_LENGTH));
root.createTable(createValueT);
}
return root.getTable(METADATA_TABLENAME);
}
 
// Instance members
 
private final Map<SQLTable, Map<String, RowItemDesc>> translation;
 
// { SQLTable -> { compCode, variant, item -> RowItemDesc }}
private final Map<SQLTable, Map<List<String>, RowItemDesc>> translation;
private final SQLTable table;
private final SQLElementDirectory dir;
private final Set<String> unknownCodes;
 
{
this.translation = new HashMap<SQLTable, Map<String, RowItemDesc>>();
this.translation = new HashMap<SQLTable, Map<List<String>, RowItemDesc>>();
this.unknownCodes = new HashSet<String>();
}
 
public SQLFieldTranslator(DBRoot base, File file) {
this.load(base, file);
this.dir = null;
public SQLFieldTranslator(DBRoot base) {
this(base, null);
}
 
public SQLFieldTranslator(DBRoot base, InputStream inputStream) {
67,13 → 119,33
* Create a new instance.
*
* @param root the default root for tables.
* @param inputStream the xml.
* @param inputStream the XML, can be <code>null</code>.
* @param dir the directory where to look for tables not in <code>root</code>, can be
* <code>null</code>.
*/
public SQLFieldTranslator(DBRoot root, InputStream inputStream, SQLElementDirectory dir) {
try {
this.table = getMetaTable(root);
} catch (SQLException e) {
throw new IllegalStateException("Couldn't get the meta table", e);
}
this.dir = dir;
this.dir.addListener(new DirectoryListener() {
@Override
public void elementRemoved(SQLElement elem) {
// nothing, SQLElement is not required (only needed for code)
}
 
@Override
public void elementAdded(SQLElement elem) {
if (SQLFieldTranslator.this.unknownCodes.remove(elem.getCode())) {
fetch(Collections.singleton(elem.getCode()));
}
}
});
if (inputStream != null)
this.load(root, inputStream);
fetchAndPut(this.table, null);
}
 
/**
103,11 → 175,16
* Load more translations.
*
* @param b the default root for tables.
* @param inputStream the xml.
* @param inputStream the XML.
*/
public void load(DBRoot b, InputStream inputStream) {
this.load(b, CORE_VARIANT, inputStream);
}
 
public Set<SQLTable> load(DBRoot b, final String variant, InputStream inputStream) {
if (inputStream == null)
throw new NullPointerException("inputStream is null");
final Set<SQLTable> res = new HashSet<SQLTable>();
try {
final Document doc = new SAXBuilder().build(inputStream);
// System.out.println("Base de donnée:"+base);
114,11 → 191,11
for (final Element elem : getChildren(doc.getRootElement())) {
final String elemName = elem.getName().toLowerCase();
if (elemName.equals("table")) {
load(b, elem);
res.add(load(b, variant, elem));
} else if (elemName.equals("root")) {
final DBRoot root = b.getDBSystemRoot().getRoot(elem.getAttributeValue("name"));
for (final Element tableElem : getChildren(elem)) {
load(root, tableElem);
res.add(load(root, variant, tableElem));
}
}
}
127,9 → 204,10
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
 
private void load(DBRoot b, final Element tableElem) {
private SQLTable load(DBRoot b, final String variant, final Element tableElem) {
final String tableName = tableElem.getAttributeValue("name");
SQLTable table = b.getTable(tableName);
if (table == null && this.dir != null && this.dir.getElement(tableName) != null)
137,49 → 215,170
if (table == null) {
Log.get().info("unknown table " + tableName);
} else {
for (final Element fieldElem : getChildren(tableElem)) {
for (final Element elem : getChildren(tableElem)) {
final String elemName = elem.getName().toLowerCase();
if (elemName.equals("field")) {
this.load(table, SQLElement.DEFAULT_COMP_ID, variant, elem);
} else if (elemName.equals("component")) {
final String compCode = elem.getAttributeValue("code");
for (final Element fieldElem : getChildren(elem)) {
this.load(table, compCode, variant, fieldElem);
}
}
}
}
return table;
}
 
private void load(final SQLTable table, final String compCode, final String variant, final Element fieldElem) {
final String name = fieldElem.getAttributeValue("name");
final String label = fieldElem.getAttributeValue("label");
final String title = fieldElem.getAttributeValue("titlelabel", label);
final String documentation = fieldElem.getText();
this.putTranslation(table, name, new RowItemDesc(label, title, documentation));
this.setDescFor(table, compCode, variant, name, new RowItemDesc(label, title, documentation));
}
 
public final void fetch(final Set<String> codes) {
this.fetchAndPut(this.table, codes);
}
 
private List<SQLRow> fetchOnly(final SQLTable table, final Where w) {
return SQLRowListRSH.execute(new SQLSelect(table.getBase()).addSelectStar(table).setWhere(w));
}
 
private final Map<String, RowItemDesc> getMap(SQLTable t) {
Map<String, RowItemDesc> m = this.translation.get(t);
if (m == null) {
m = new HashMap<String, RowItemDesc>();
this.translation.put(t, m);
private void fetchAndPut(final SQLTable table, final Set<String> codes) {
final Where w;
if (codes == null) {
w = null;
this.removeTranslation((SQLTable) null, null, DB_VARIANT, null);
} else {
w = new Where(table.getField(ELEM_FIELDNAME), codes);
for (final String elementCode : codes)
this.removeTranslation(this.dir.getElementForCode(elementCode).getTable(), null, DB_VARIANT, null);
}
return m;
for (final SQLRow r : fetchOnly(table, w)) {
final String elementCode = r.getString(ELEM_FIELDNAME);
if (!this.unknownCodes.contains(elementCode)) {
// needed since tables can be loaded at any time in SQLElementDirectory
// MAYBE use code as the map key instead of SQLTable
final SQLElement elem = this.dir.getElementForCode(elementCode);
if (elem != null) {
final String componentCode = r.getString(COMP_FIELDNAME);
final String item = r.getString(ITEM_FIELDNAME);
final RowItemDesc desc = new RowItemDesc(r.getString(LABEL_FIELDNAME), r.getString(COL_TITLE_FIELDNAME), r.getString(DOC_FIELDNAME));
putTranslation(elem.getTable(), componentCode, DB_VARIANT, item, desc);
} else {
this.unknownCodes.add(elementCode);
}
}
}
}
 
private final void putTranslation(SQLTable t, String name, RowItemDesc desc) {
this.getMap(t).put(name, desc);
private final Map<List<String>, RowItemDesc> getMap(final SQLTable t) {
Map<List<String>, RowItemDesc> elemMap = this.translation.get(t);
if (elemMap == null) {
elemMap = new HashMap<List<String>, RowItemDesc>();
this.translation.put(t, elemMap);
}
return elemMap;
}
 
private final RowItemDesc getTranslation(SQLTable t, String name) {
return this.getMap(t).get(name);
private final void putTranslation(SQLTable t, String compCode, String variant, String item, RowItemDesc desc) {
if (t == null)
throw new IllegalArgumentException("Table cannot be null");
// needed by remove()
if (compCode == null || variant == null || item == null)
throw new IllegalArgumentException("Values cannot be null");
this.getMap(t).put(Arrays.asList(compCode, variant, item), desc);
}
 
private final void removeTranslation(SQLTable t, String compCode, String variant, String name) {
// null means match everything, OK since we test in putTranslation() that we don't contain
// null values
if (t == null) {
for (final Map<List<String>, RowItemDesc> m : this.translation.values()) {
this.removeTranslation(m, compCode, variant, name);
}
} else {
this.removeTranslation(this.translation.get(t), compCode, variant, name);
}
}
 
private void removeTranslation(Map<List<String>, RowItemDesc> m, String compCode, String variant, String name) {
if (m == null)
return;
 
if (compCode == null && variant == null && name == null) {
m.clear();
} else if (compCode != null && variant != null && name != null) {
m.remove(Arrays.asList(compCode, variant, name));
} else {
final Iterator<List<String>> iter = m.keySet().iterator();
while (iter.hasNext()) {
final List<String> l = iter.next();
if ((compCode == null || compCode.equals(l.get(0))) && (variant == null || variant.equals(l.get(1))) && (name == null || name.equals(l.get(2))))
iter.remove();
}
}
}
 
private final RowItemDesc getTranslation(SQLTable t, String compCode, String variant, String item) {
return this.getMap(t).get(Arrays.asList(compCode, variant, item));
}
 
private final RowItemDesc getTranslation(SQLTable t, String compCodeArg, List<String> variants, String name) {
final LinkedList<String> ll = new LinkedList<String>(variants);
ll.addFirst(DB_VARIANT);
ll.addLast(CORE_VARIANT);
 
final String[] compCodes;
if (compCodeArg == SQLElement.DEFAULT_COMP_ID)
compCodes = new String[] { SQLElement.DEFAULT_COMP_ID };
else
compCodes = new String[] { compCodeArg, SQLElement.DEFAULT_COMP_ID };
for (final String compCode : compCodes) {
for (final String variant : ll) {
final RowItemDesc labeledField = this.getTranslation(t, compCode, variant, name);
if (labeledField != null)
return labeledField;
}
}
return null;
}
 
public RowItemDesc getDescFor(SQLTable t, String name) {
final String fullName = t.getName() + "." + name;
final RowItemDesc labeledField = this.getTranslation(t, name);
return getDescFor(t, SQLElement.DEFAULT_COMP_ID, name);
}
 
public RowItemDesc getDescFor(SQLTable t, String compCode, String name) {
return getDescFor(t, compCode, Collections.<String> emptyList(), name);
}
 
public RowItemDesc getDescFor(final String elementCode, String compCode, String name) {
return this.getDescFor(elementCode, compCode, Collections.<String> emptyList(), name);
}
 
public RowItemDesc getDescFor(final String elementCode, String compCode, List<String> variants, String name) {
return this.getDescFor(this.dir.getElementForCode(elementCode).getTable(), compCode, variants, name);
}
 
public RowItemDesc getDescFor(SQLTable t, String compCodeArg, List<String> variants, String name) {
RowItemDesc labeledField = this.getTranslation(t, compCodeArg, variants, name);
// if nothing found, re-fetch from the DB
if (labeledField == null) {
String l = name.replaceAll("ID_", "").replaceAll("_", " de ");
if (l.length() > 1) {
l = l.substring(0, 1).toUpperCase() + l.substring(1).toLowerCase();
this.fetchAndPut(this.table, Collections.singleton(this.dir.getElement(t).getCode()));
labeledField = this.getTranslation(t, compCodeArg, variants, name);
}
l = l.trim();
System.err.println("No translation for:" + fullName + "\n please add: <FIELD name=\"" + name + "\" label=\"" + l + "\" titlelabel=\"" + l + "\"/>");
if (labeledField == null) {
Log.get().info("unknown item " + name + " in " + t);
return NULL_DESC;
} else {
return labeledField;
}
return labeledField == null ? NULL_DESC : labeledField;
}
 
private RowItemDesc getDescFor(SQLField f) {
return this.getDescFor(f.getTable(), f.getName());
return this.getDescFor(f.getTable(), SQLElement.DEFAULT_COMP_ID, this.dir.getElement(f.getTable()).getMDPath(), f.getName());
}
 
public String getLabelFor(SQLField f) {
190,4 → 389,63
return this.getDescFor(f).getTitleLabel();
}
 
public final void setDescFor(final SQLTable table, final String componentCode, final String variant, final String name, final RowItemDesc desc) {
if (DB_VARIANT.equals(variant))
throw new IllegalArgumentException("Use storeDescFor()");
putTranslation(table, componentCode, variant, name, desc);
}
 
public final void removeDescFor(SQLTable t, String compCode, String variant, String name) {
if (DB_VARIANT.equals(variant))
throw new IllegalArgumentException("Cannot remove DB values, use deleteDescFor()");
this.removeTranslation(t, compCode, variant, name);
}
 
public final void storeDescFor(final String elementCode, final String componentCode, final String name, final RowItemDesc desc) throws SQLException {
this.storeDescFor(this.dir.getElementForCode(elementCode).getTable(), componentCode, name, desc);
}
 
public final void storeDescFor(final SQLTable table, final String componentCode, final String name, final RowItemDesc desc) throws SQLException {
final String elementCode = this.dir.getElement(table).getCode();
final Map<String, Object> m = new HashMap<String, Object>();
m.put(ELEM_FIELDNAME, elementCode);
m.put(COMP_FIELDNAME, componentCode);
m.put(ITEM_FIELDNAME, name);
final SQLTable mdT = this.table;
SQLUtils.executeAtomic(this.table.getDBSystemRoot().getDataSource(), new SQLFactory<Object>() {
@Override
public Object create() throws SQLException {
final List<SQLRow> existing = fetchOnly(mdT, Where.and(mdT, m));
assert existing.size() <= 1 : "Unique constraint failed for " + m;
final SQLRowValues vals;
if (existing.size() == 0)
vals = new SQLRowValues(mdT, m);
else
vals = existing.get(0).asRowValues();
vals.put(LABEL_FIELDNAME, desc.getLabel());
vals.put(COL_TITLE_FIELDNAME, desc.getTitleLabel());
vals.put(DOC_FIELDNAME, desc.getDocumentation());
vals.commit();
putTranslation(table, componentCode, DB_VARIANT, name, desc);
return null;
}
});
}
 
public final void deleteDescFor(final SQLTable elemTable, final String componentCode, final String name) throws SQLException {
Where w = null;
if (elemTable != null)
w = new Where(this.table.getField(ELEM_FIELDNAME), "=", this.dir.getElement(elemTable).getCode()).and(w);
if (componentCode != null)
w = new Where(this.table.getField(COMP_FIELDNAME), "=", componentCode).and(w);
if (name != null)
w = new Where(this.table.getField(ITEM_FIELDNAME), "=", name).and(w);
final String whereString = w == null ? "" : " where " + w.getClause();
try {
this.table.getDBSystemRoot().getDataSource().execute("DELETE FROM " + this.table.getSQLName().quote() + whereString);
} catch (Exception e) {
throw new SQLException(e);
}
this.removeTranslation(elemTable, componentCode, DB_VARIANT, name);
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/element/DocumentationEditorFrame.java
13,6 → 13,7
package org.openconcerto.sql.element;
 
import org.openconcerto.sql.request.RowItemDesc;
import org.openconcerto.ui.DefaultGridBagConstraints;
 
import java.awt.Dimension;
22,8 → 23,8
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
31,30 → 32,42
 
public class DocumentationEditorFrame extends JFrame {
 
public DocumentationEditorFrame(final GroupSQLComponent groupSQLComponent, final String id, String doc) {
public DocumentationEditorFrame(final BaseSQLComponent sqlComponent, final String itemName) {
this.setTitle("Documentation");
if (doc == null) {
doc = "";
}
JPanel p = new JPanel();
JComponent label = groupSQLComponent.createLabel(id);
p.setLayout(new GridBagLayout());
final JPanel p = new JPanel(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
 
c.weightx = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.NONE;
p.add(label, c);
p.add(new JLabel(itemName), c);
 
final RowItemDesc rivDesc = sqlComponent.getRIVDesc(itemName);
 
// TODO JLabel for each field
 
// Label Editor
final JTextField labelTxt = new JTextField();
c.weighty = 1;
c.gridy++;
c.fill = GridBagConstraints.BOTH;
labelTxt.setText(rivDesc.getLabel());
p.add(labelTxt, c);
// Title Editor
final JTextField titleTxt = new JTextField();
c.weighty = 1;
c.gridy++;
c.fill = GridBagConstraints.BOTH;
titleTxt.setText(rivDesc.getTitleLabel());
p.add(titleTxt, c);
// Editor
final JTextArea txt = new JTextArea();
txt.setFont(new JTextField().getFont());
txt.setText(doc);
final JTextArea docTxt = new JTextArea();
docTxt.setFont(new JTextField().getFont());
c.weighty = 1;
c.gridy++;
c.fill = GridBagConstraints.BOTH;
txt.setText(groupSQLComponent.getDocumentation(id));
final JScrollPane comp = new JScrollPane(txt);
docTxt.setText(rivDesc.getDocumentation());
final JScrollPane comp = new JScrollPane(docTxt);
comp.setMinimumSize(new Dimension(400, 300));
comp.setPreferredSize(new Dimension(400, 300));
p.add(comp, c);
77,7 → 90,7
bOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
groupSQLComponent.saveDocumentation(id, txt.getText());
sqlComponent.setRIVDesc(itemName, new RowItemDesc(labelTxt.getText(), titleTxt.getText(), docTxt.getText()));
dispose();
}
});
/trunk/OpenConcerto/src/org/openconcerto/sql/element/GroupSQLComponent.java
13,10 → 13,9
package org.openconcerto.sql.element;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLType;
import org.openconcerto.sql.request.RowItemDesc;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
52,7 → 51,6
private final boolean forceViewOnly = true;
private final Map<String, JComponent> labels = new HashMap<String, JComponent>();
private final Map<String, JComponent> editors = new HashMap<String, JComponent>();
private final Map<String, String> docs = new HashMap<String, String>();
 
public GroupSQLComponent(final SQLElement element, final Group group) {
super(element);
220,21 → 218,10
 
}
 
public JComponent createLabel(final String id) {
final String fieldLabel = super.getLabelFor(id);
JLabel jLabel;
if (fieldLabel == null) {
jLabel = new JLabel(id);
jLabel.setForeground(Color.RED.darker());
 
} else {
jLabel = new JLabel(fieldLabel);
}
protected JComponent createLabel(final String id) {
final JLabel jLabel = new JLabel();
jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
registerPopupMenu(jLabel, id);
final String doc = ((PropsConfiguration) Configuration.getInstance()).getMetadata().getDocumentation(this.getCode(), this.group.getId(), id);
setDocumentation(jLabel, id, doc);
jLabel.setToolTipText(doc);
return jLabel;
}
 
256,7 → 243,7
 
@Override
public void actionPerformed(final ActionEvent e) {
new DocumentationEditorFrame(GroupSQLComponent.this, id, getDocumentation(id)).setVisible(true);
new DocumentationEditorFrame(GroupSQLComponent.this, id).setVisible(true);
 
}
});
271,31 → 258,18
 
}
 
public void setDocumentation(final JComponent jLabel, final String id, final String text) {
this.docs.put(id, text);
if (text != null) {
jLabel.setToolTipText(text);
@Override
protected void updateUI(String id, RowItemDesc desc) {
super.updateUI(id, desc);
updateUI(id, getLabel(id), desc, Color.RED.darker());
}
}
 
public void setDocumentation(final String id, final String text) {
setDocumentation(getLabel(id), id, text);
}
 
public void saveDocumentation(final String id, final String text) {
setDocumentation(id, text);
((PropsConfiguration) Configuration.getInstance()).getMetadata().setDocumentation(this.getElement().getCode(), this.getCode(), this.group.getId(), id, text);
}
 
public String getDocumentation(final String id) {
return this.docs.get(id);
}
 
public JComponent getLabel(final String id) {
JComponent label = this.labels.get(id);
if (label == null) {
label = createLabel(id);
this.labels.put(id, label);
updateUI(id, getRIVDesc(id));
}
return label;
}
/trunk/OpenConcerto/src/org/openconcerto/sql/element/SQLElement.java
128,6 → 128,7
 
private final Map<String, JComponent> additionalFields;
private final List<SQLTableModelColumn> additionalListCols;
private List<String> mdPath;
 
public SQLElement(String singular, String plural, SQLTable primaryTable) {
this(singular, plural, primaryTable, null);
155,6 → 156,7
// the components should always be in the same order
this.additionalFields = new LinkedHashMap<String, JComponent>();
this.additionalListCols = new ArrayList<SQLTableModelColumn>();
this.mdPath = Collections.emptyList();
}
 
/**
1478,6 → 1480,22
*/
protected abstract SQLComponent createComponent();
 
public final void addToMDPath(String mdVariant) {
final LinkedList<String> newL = new LinkedList<String>(this.mdPath);
newL.addFirst(mdVariant);
this.mdPath = Collections.unmodifiableList(newL);
}
 
public final void removeFromMDPath(String mdVariant) {
final LinkedList<String> newL = new LinkedList<String>(this.mdPath);
if (newL.remove(mdVariant))
this.mdPath = Collections.unmodifiableList(newL);
}
 
public final List<String> getMDPath() {
return this.mdPath;
}
 
/**
* Allows a module to add a view for a field to this element.
*
/trunk/OpenConcerto/src/org/openconcerto/sql/element/BaseSQLComponent.java
24,6 → 24,7
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLType;
import org.openconcerto.sql.request.MutableRowItemView;
import org.openconcerto.sql.request.RowItemDesc;
import org.openconcerto.sql.request.RowNotFound;
import org.openconcerto.sql.request.SQLForeignRowItemView;
import org.openconcerto.sql.request.SQLRowItemView;
47,6 → 48,7
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.cc.Transformer;
import org.openconcerto.utils.checks.EmptyListener;
56,6 → 58,7
import org.openconcerto.utils.checks.ValidState;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
74,10 → 77,12
 
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.text.JTextComponent;
 
/**
493,11 → 498,15
return ValidState.create(res, CollectionUtils.join(pbs, "\n"));
}
 
protected static final String getDesc(final SQLRowItemView obj) {
final String desc = obj.getDescription();
return desc == null ? obj.getSQLName() : desc;
protected final String getDesc(final SQLRowItemView obj) {
return getDesc(obj.getSQLName(), getRIVDesc(obj.getSQLName())).get0();
}
 
static protected final Tuple2<String, Boolean> getDesc(final String itemName, final RowItemDesc desc) {
final boolean emptyLabel = desc.getLabel() == null || desc.getLabel().trim().length() == 0;
return Tuple2.create(emptyLabel ? itemName : desc.getLabel(), !emptyLabel);
}
 
/*
* (non-Javadoc)
*
677,9 → 686,47
}
 
public final String getLabelFor(String field) {
return Configuration.getTranslator(this.getTable()).getDescFor(this.getTable(), field).getLabel();
return getDesc(field, getRIVDesc(field)).get0();
}
 
public final RowItemDesc getRIVDesc(String field) {
return Configuration.getInstance().getTranslator().getDescFor(this.getTable(), getCode(), getElement().getMDPath(), field);
}
 
public final void setRIVDesc(String itemName, RowItemDesc desc) {
try {
Configuration.getTranslator(this.getTable()).storeDescFor(this.getTable(), getCode(), itemName, desc);
updateUI(itemName, desc);
} catch (SQLException e) {
ExceptionHandler.handle(this, "Impossible d'enregistrer la documentation de " + itemName, e);
}
}
 
protected void updateUI(final String itemName, final RowItemDesc desc) {
}
 
static protected void updateUI(final String itemName, final JComponent label, final RowItemDesc desc) {
updateUI(itemName, label, desc, null);
}
 
static protected void updateUI(final String itemName, final JComponent label, final RowItemDesc desc, final Color emptyLabelColor) {
label.setToolTipText(desc.getDocumentation().trim().length() == 0 ? null : desc.getDocumentation());
final Tuple2<String, Boolean> tuple = getDesc(itemName, desc);
final String s = tuple.get0();
if (label instanceof JLabel) {
((JLabel) label).setText(s);
} else if (label instanceof JTextComponent) {
((JTextComponent) label).setText(s);
} else if (label.getBorder() instanceof TitledBorder) {
((TitledBorder) label.getBorder()).setTitle(s);
} else {
Log.get().warning("Couldn't change label for " + itemName);
}
if (emptyLabelColor != null && !tuple.get1())
label.setForeground(emptyLabelColor);
label.repaint();
}
 
public void doNotShow(SQLField f) {
this.hide.add(f);
}
/trunk/OpenConcerto/src/org/openconcerto/sql/element/UISQLComponent.java
16,16 → 16,26
*/
package org.openconcerto.sql.element;
 
import org.openconcerto.sql.request.RowItemDesc;
import org.openconcerto.sql.request.SQLRowItemView;
import org.openconcerto.ui.FormLayouter;
import org.openconcerto.ui.PopupMouseListener;
 
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.LayoutFocusTraversalPolicy;
import javax.swing.WindowConstants;
 
public abstract class UISQLComponent extends BaseSQLComponent {
 
35,6 → 45,7
private static final String REQ_SUFFIX = System.getProperty(REQUIRED_SUFFIX_PROP, " *");
 
private FormLayouter autoLayouter;
private final Map<String, JComponent> labels;
private JPanel currentPanel;
private JTabbedPane tabbedPane;
// default values for the layouter
60,29 → 71,55
// ne pas instancier le layouter tout de suite
// car on ne sait pas encore si tab ou pas
this.autoLayouter = null;
this.labels = new HashMap<String, JComponent>();
}
 
protected void addToUI(SQLRowItemView obj, String where) {
String desc = getDesc(obj);
protected void addToUI(final SQLRowItemView obj, String where) {
final RowItemDesc rivDesc = getRIVDesc(obj.getSQLName());
String desc = rivDesc.getLabel();
if (this.getRequired().contains(obj))
desc += REQ_SUFFIX;
if (where == null)
where = this.getDefaultWhere(obj);
final JComponent added;
if (where == null)
this.getLayouter().add(desc, obj.getComp());
added = this.getLayouter().add(desc, obj.getComp());
else if (where.equals("bordered")) {
this.getLayouter().addBordered(desc, obj.getComp(), 0);
added = this.getLayouter().addBordered(desc, obj.getComp(), 0);
} else if (where.equals("left")) {
this.getLayouter().newLine();
this.getLayouter().add(desc, obj.getComp(), this.getLayouter().getWidth() / 2);
added = this.getLayouter().add(desc, obj.getComp(), this.getLayouter().getWidth() / 2);
} else if (where.equals("right"))
this.getLayouter().add(desc, obj.getComp(), (this.getLayouter().getWidth() + 1) / 2);
added = this.getLayouter().add(desc, obj.getComp(), (this.getLayouter().getWidth() + 1) / 2);
else {
final int aWidth = Integer.parseInt(where);
this.getLayouter().add(desc, obj.getComp(), aWidth);
added = this.getLayouter().add(desc, obj.getComp(), aWidth);
}
this.labels.put(obj.getSQLName(), added);
updateUI(obj.getSQLName(), rivDesc);
final JPopupMenu menu = new JPopupMenu();
menu.add(new AbstractAction("Modifier la documentation") {
@Override
public void actionPerformed(ActionEvent e) {
final DocumentationEditorFrame frame = new DocumentationEditorFrame(UISQLComponent.this, obj.getSQLName());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
});
added.addMouseListener(new PopupMouseListener() {
@Override
protected JPopupMenu createPopup(MouseEvent e) {
return e.isControlDown() ? menu : null;
}
});
}
 
@Override
protected void updateUI(String itemName, RowItemDesc desc) {
super.updateUI(itemName, desc);
updateUI(itemName, this.labels.get(itemName), desc);
}
 
private String getDefaultWhere(SQLRowItemView obj) {
if (getElement().getPrivateForeignFields().contains(obj.getField().getName()))
return "bordered";
/trunk/OpenConcerto/src/org/openconcerto/sql/utils/Diff.java
216,12 → 216,18
alterTable.addForeignConstraint(link, false);
}
for (final String common : CollectionUtils.inter(aFKs, bFKs)) {
final SQLName aPath = graph.getForeignLink(aT.getField(common)).getContextualName();
final SQLName bPath = bGraph.getForeignLink(bT.getField(common)).getContextualName();
final Link aLink = graph.getForeignLink(aT.getField(common));
final Link bLink = bGraph.getForeignLink(bT.getField(common));
final SQLName aPath = aLink.getContextualName();
final SQLName bPath = bLink.getContextualName();
if (!aPath.equals(bPath))
throw new UnsupportedOperationException(common + " is different: " + aPath + " != " + bPath);
if (aLink.getUpdateRule() != bLink.getUpdateRule() || aLink.getDeleteRule() != bLink.getDeleteRule()) {
alterTable.dropForeignConstraint(aLink.getName());
alterTable.addForeignConstraint(bLink, false);
}
}
}
 
// indexes
try {
/trunk/OpenConcerto/src/org/openconcerto/sql/utils/ChangeTable.java
22,6 → 22,7
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTable.Index;
import org.openconcerto.sql.model.graph.Link;
import org.openconcerto.sql.model.graph.Link.Rule;
import org.openconcerto.sql.model.graph.SQLKey;
import org.openconcerto.utils.CollectionMap;
import org.openconcerto.utils.CollectionUtils;
146,8 → 147,9
private final List<String> cols;
private final SQLName refTable;
private final List<String> refCols;
private final Rule updateRule, deleteRule;
 
public FCSpec(List<String> cols, SQLName refTable, List<String> refCols) {
public FCSpec(List<String> cols, SQLName refTable, List<String> refCols, final Rule updateRule, final Rule deleteRule) {
super();
if (refTable.getItemCount() == 0)
throw new IllegalArgumentException(refTable + " is empty.");
154,6 → 156,8
this.cols = Collections.unmodifiableList(new ArrayList<String>(cols));
this.refTable = refTable;
this.refCols = Collections.unmodifiableList(new ArrayList<String>(refCols));
this.updateRule = updateRule;
this.deleteRule = deleteRule;
}
 
public final List<String> getCols() {
167,8 → 171,16
public final List<String> getRefCols() {
return this.refCols;
}
 
public final Rule getUpdateRule() {
return this.updateRule;
}
 
public final Rule getDeleteRule() {
return this.deleteRule;
}
}
 
private String name;
private final SQLSyntax syntax;
private final List<FCSpec> fks;
301,7 → 313,7
}
 
public final T addForeignConstraint(Link l, boolean createIndex) {
return this.addForeignConstraint(l.getCols(), l.getContextualName(), createIndex, l.getRefCols());
return this.addForeignConstraint(new FCSpec(l.getCols(), l.getContextualName(), l.getRefCols(), l.getUpdateRule(), l.getDeleteRule()), createIndex);
}
 
public final T addForeignConstraint(String fieldName, SQLName refTable, String refCols) {
319,7 → 331,7
* @return this.
*/
public final T addForeignConstraint(final List<String> fieldName, SQLName refTable, boolean createIndex, List<String> refCols) {
return this.addForeignConstraint(new FCSpec(fieldName, refTable, refCols), createIndex);
return this.addForeignConstraint(new FCSpec(fieldName, refTable, refCols, null, null), createIndex);
}
 
public final T addForeignConstraint(final FCSpec fkSpec, boolean createIndex) {
514,7 → 526,7
// resolve relative path, a table is identified by root.table
final SQLName relRefTable = fk.getRefTable();
final SQLName refTable = relRefTable.getItemCount() == 1 ? new SQLName(rootName, relRefTable.getName()) : relRefTable;
res.add(getConstraintPrefix() + this.getSyntax().getFK(this.name + "_", fk.getCols(), refTable, fk.getRefCols()));
res.add(getConstraintPrefix() + this.getSyntax().getFK(this.name + "_", fk.getCols(), refTable, fk.getRefCols(), fk.getUpdateRule(), fk.getDeleteRule()));
}
return res;
}
/trunk/OpenConcerto/src/org/openconcerto/sql/model/graph/Link.java
25,6 → 25,7
import org.openconcerto.utils.CollectionUtils;
 
import java.io.PrintWriter;
import java.sql.DatabaseMetaData;
import java.util.ArrayList;
import java.util.List;
 
39,11 → 40,48
*/
public class Link extends DirectedEdge<SQLTable> {
 
public static enum Rule {
 
SET_NULL("SET NULL"), SET_DEFAULT("SET DEFAULT"), CASCADE("CASCADE"), RESTRICT("RESTRICT"), NO_ACTION("NO ACTION");
 
private final String sql;
 
private Rule(final String sql) {
this.sql = sql;
}
 
public static Rule fromShort(short s) {
switch (s) {
case DatabaseMetaData.importedKeyCascade:
return CASCADE;
case DatabaseMetaData.importedKeySetNull:
return SET_NULL;
case DatabaseMetaData.importedKeySetDefault:
return SET_DEFAULT;
case DatabaseMetaData.importedKeyRestrict:
return RESTRICT;
case DatabaseMetaData.importedKeyNoAction:
return NO_ACTION;
default:
throw new IllegalArgumentException("Unknown rule " + s);
}
}
 
public static Rule fromName(String n) {
return n == null ? null : valueOf(n);
}
 
public String asString() {
return this.sql;
}
}
 
private final List<SQLField> cols;
private final List<String> colsNames;
private final List<SQLField> refCols;
private final List<String> refColsNames;
private final String name;
private final Rule updateRule, deleteRule;
 
/**
* Creates a link between two tables.
51,8 → 89,10
* @param keys foreign fields of the source table.
* @param referredCols fields of the destination table.
* @param foreignKeyName the name of the constraint, can be <code>null</code>.
* @param updateRule what happens to a foreign key when the primary key is updated.
* @param deleteRule what happens to the foreign key when primary is deleted.
*/
public Link(List<SQLField> keys, List<SQLField> referredCols, String foreignKeyName) {
public Link(List<SQLField> keys, List<SQLField> referredCols, String foreignKeyName, Rule updateRule, Rule deleteRule) {
super(keys.get(0).getTable(), referredCols.get(0).getTable());
if (keys.size() != referredCols.size())
throw new IllegalArgumentException("size mismatch: " + keys + " != " + referredCols);
67,6 → 107,8
this.refColsNames.add(f.getName());
}
this.name = foreignKeyName;
this.updateRule = updateRule;
this.deleteRule = deleteRule;
}
 
public final List<SQLField> getFields() {
111,18 → 153,29
return this.getTarget().getContextualSQLName(this.getSource());
}
 
public final Rule getUpdateRule() {
return this.updateRule;
}
 
public final Rule getDeleteRule() {
return this.deleteRule;
}
 
@Override
public String toString() {
return "<" + this.getFields() + " -> " + this.getTarget() + (this.getName() != null ? " '" + this.getName() + "'" : "") + ">";
}
 
@Override
public boolean equals(Object other) {
if (!(other instanceof Link)) {
return false;
}
Link o = (Link) other;
return this.getFields().equals(o.getFields()) && this.getRefFields().equals(o.getRefFields());
return this.getFields().equals(o.getFields()) && this.getRefFields().equals(o.getRefFields()) && this.getUpdateRule() == o.getUpdateRule() && this.getDeleteRule() == o.getDeleteRule();
}
 
@Override
public int hashCode() {
return this.getFields().hashCode() + this.getRefFields().hashCode();
}
131,6 → 184,10
pWriter.print(" <link to=\"" + OUTPUTTER.escapeAttributeEntities(this.getTarget().getSQLName().toString()) + "\" ");
if (this.getName() != null)
pWriter.print("name=\"" + OUTPUTTER.escapeAttributeEntities(this.getName()) + "\" ");
if (this.getUpdateRule() != null)
pWriter.print("updateRule=\"" + OUTPUTTER.escapeAttributeEntities(this.getUpdateRule().name()) + "\" ");
if (this.getDeleteRule() != null)
pWriter.print("deleteRule=\"" + OUTPUTTER.escapeAttributeEntities(this.getDeleteRule().name()) + "\" ");
if (this.getFields().size() == 1) {
toXML(pWriter, 0);
pWriter.println("/>");
157,6 → 214,8
final SQLName to = SQLName.parse(linkElem.getAttributeValue("to"));
final SQLTable foreignTable = t.getDBSystemRoot().getDesc(to, SQLTable.class);
final String linkName = linkElem.getAttributeValue("name");
final Rule updateRule = Rule.fromName(linkElem.getAttributeValue("updateRule"));
final Rule deleteRule = Rule.fromName(linkElem.getAttributeValue("deleteRule"));
@SuppressWarnings("unchecked")
final List<Element> lElems = linkElem.getAttribute("col") != null ? singletonList(linkElem) : linkElem.getChildren("l");
final List<SQLField> cols = new ArrayList<SQLField>();
165,6 → 224,6
cols.add(t.getField(l.getAttributeValue("col")));
refcols.add(foreignTable.getField(l.getAttributeValue("refCol")));
}
return new Link(cols, refcols, linkName);
return new Link(cols, refcols, linkName, updateRule, deleteRule);
}
}
/trunk/OpenConcerto/src/org/openconcerto/sql/model/graph/DatabaseGraph.java
32,6 → 32,7
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Link.Rule;
import org.openconcerto.utils.CompareUtils;
import org.openconcerto.utils.ExceptionUtils;
import org.openconcerto.utils.FileUtils;
70,7 → 71,14
*/
public class DatabaseGraph extends BaseGraph {
 
private static final String XML_VERSION = "20090210-1530";
/**
* Whether to infer foreign constraints from fields' names.
*
* @see SQLKey
*/
public static final String INFER_FK = "org.openconcerto.sql.graph.inferFK";
 
private static final String XML_VERSION = "20120228-1810";
private static final String FILENAME = "graph.xml";
 
private final DBSystemRoot base;
161,8 → 169,8
return res;
}
 
private final void addLink(final List<SQLField> from, final List<SQLField> to, String foreignKeyName) {
addLink(new Link(from, to, foreignKeyName));
private final void addLink(final List<SQLField> from, final List<SQLField> to, String foreignKeyName, Rule updateRule, Rule deleteRule) {
addLink(new Link(from, to, foreignKeyName, updateRule, deleteRule));
}
 
private final void addLink(final Link l) {
181,6 → 189,8
// accumulators for multi-field foreign key
final List<SQLField> from = new ArrayList<SQLField>();
final List<SQLField> to = new ArrayList<SQLField>();
Rule updateRule = null;
Rule deleteRule = null;
String name = null;
final Iterator ikIter = importedKeys.iterator();
while (ikIter.hasNext()) {
224,17 → 234,23
if (seq == 1) {
// if we start a new link add the current one
if (from.size() > 0)
addLink(from, to, name);
addLink(from, to, name, updateRule, deleteRule);
from.clear();
to.clear();
}
from.add(key);
to.add(foreignTable.getField(foreignTableColName));
// "UPDATE_RULE"
updateRule = Rule.fromShort(((Number) m[9]).shortValue());
// "DELETE_RULE"
deleteRule = Rule.fromShort(((Number) m[10]).shortValue());
name = foreignKeyName;
// MAYBE DEFERRABILITY
}
if (from.size() > 0)
addLink(from, to, name);
addLink(from, to, name, updateRule, deleteRule);
 
if (Boolean.getBoolean(INFER_FK)) {
final Set<String> lexicalFKs = SQLKey.foreignKeys(table);
// already done
lexicalFKs.removeAll(metadataFKs);
241,9 → 257,10
// MAYBE option to print out foreign keys w/o constraint
for (final String keyName : lexicalFKs) {
final SQLField key = table.getField(keyName);
addLink(singletonList(key), singletonList(SQLKey.keyToTable(key).getKey()), null);
addLink(singletonList(key), singletonList(SQLKey.keyToTable(key).getKey()), null, null, null);
}
}
}
 
private final SQLTable getTableIgnoringCase(final SQLSchema s, String tablename) {
for (final String tname : s.getTableNames())
/trunk/OpenConcerto/src/org/openconcerto/sql/model/graph/SQLKey.java
45,7 → 45,7
* @param table la table.
* @return l'ensemble des noms des clés étrangères.
*/
static Set<String> foreignKeys(SQLTable table) {
public static Set<String> foreignKeys(SQLTable table) {
// we used to name the primary key ID_TABLE, so we must not interpret it as a self reference
// getSole() so we can have join tables (e.g. ID_CONTENU and ID_SITE are the primary key)
final String pkeyName = CollectionUtils.getSole(table.getPKsNames());
73,7 → 73,7
* @throws IllegalStateException si la table ne peut être déterminée.
* @see #isKey(String)
*/
static SQLTable keyToTable(SQLField key) {
public static SQLTable keyToTable(SQLField key) {
SQLTable table = key.getTable();
String keyName = key.getName();
if (isKey(keyName)) {
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLTable.java
1263,6 → 1263,10
return "unequal path size : " + thisPath + " != " + oPath;
if (!thisPath.getName().equals(oPath.getName()))
return "unequal referenced table name : " + thisPath.getName() + " != " + oPath.getName();
if (!l.getUpdateRule().equals(ol.getUpdateRule()))
return "unequal update rule for " + l + ": " + l.getUpdateRule() + " != " + ol.getUpdateRule();
if (!l.getDeleteRule().equals(ol.getDeleteRule()))
return "unequal delete rule for " + l + ": " + l.getDeleteRule() + " != " + ol.getDeleteRule();
}
 
// indexes
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLSyntaxMySQL.java
15,6 → 15,7
 
import org.openconcerto.sql.model.SQLField.Properties;
import org.openconcerto.sql.model.SQLTable.Index;
import org.openconcerto.sql.model.graph.Link.Rule;
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
import org.openconcerto.sql.utils.ChangeTable.OutsideClause;
import org.openconcerto.sql.utils.SQLUtils;
158,6 → 159,13
}
 
@Override
protected String getRuleSQL(Rule r) {
if (r == Rule.SET_DEFAULT)
throw new UnsupportedOperationException(r + " isn't supported");
return super.getRuleSQL(r);
}
 
@Override
public String getDropConstraint() {
// in MySQL there's only 2 types of constraints : foreign keys and unique
// fk are handled by getDropFK(), so this is just for unique
/trunk/OpenConcerto/src/org/openconcerto/sql/model/SQLSyntax.java
17,6 → 17,7
import org.openconcerto.sql.Log;
import org.openconcerto.sql.model.SQLField.Properties;
import org.openconcerto.sql.model.SQLTable.Index;
import org.openconcerto.sql.model.graph.Link.Rule;
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
import org.openconcerto.sql.utils.ChangeTable.OutsideClause;
import org.openconcerto.utils.CollectionMap;
210,16 → 211,24
* @param fk the name of the foreign keys, eg ["ID_SITE"].
* @param refTable the name of the referenced table, eg CTech.SITE.
* @param referencedFields the fields in the foreign table, eg ["ID"].
* @param updateRule the update rule, <code>null</code> means use DB default.
* @param deleteRule the delete rule, <code>null</code> means use DB default.
* @return a String declaring that <code>fk</code> points to <code>referencedFields</code>.
*/
public String getFK(final String constraintPrefix, final List<String> fk, final SQLName refTable, final List<String> referencedFields) {
public String getFK(final String constraintPrefix, final List<String> fk, final SQLName refTable, final List<String> referencedFields, final Rule updateRule, final Rule deleteRule) {
final String onUpdate = updateRule == null ? "" : " ON UPDATE " + getRuleSQL(updateRule);
final String onDelete = deleteRule == null ? "" : " ON DELETE " + getRuleSQL(deleteRule);
// a prefix for the constraint name, since in psql constraints are db wide not table wide
return SQLSelect.quote("CONSTRAINT %i FOREIGN KEY ( " + quoteIdentifiers(fk) + " ) REFERENCES %i ", constraintPrefix + join(fk, "__") + "_fkey", refTable) + "( "
// don't put ON DELETE CASCADE since it's dangerous, plus MS SQL only supports 1 fk with
// cascade : http://support.microsoft.com/kb/321843/en-us
+ quoteIdentifiers(referencedFields) + " )";
+ quoteIdentifiers(referencedFields) + " )" + onUpdate + onDelete;
}
 
protected String getRuleSQL(final Rule r) {
return r.asString();
}
 
public String getDropFK() {
return getDropConstraint();
}
/trunk/OpenConcerto/src/org/openconcerto/sql/changer/convert/AddFK.java
16,13 → 16,21
*/
package org.openconcerto.sql.changer.convert;
 
import static java.util.Collections.singletonList;
import org.openconcerto.sql.changer.Changer;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLName;
import org.openconcerto.sql.model.SQLSystem;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.SQLTable.Index;
import org.openconcerto.sql.model.graph.Link;
import org.openconcerto.sql.model.graph.SQLKey;
import org.openconcerto.sql.utils.AlterTable;
import org.openconcerto.sql.utils.ChangeTable;
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
import org.openconcerto.sql.utils.ChangeTable.DeferredClause;
 
import java.sql.SQLException;
import java.util.HashSet;
44,7 → 52,17
 
for (final SQLTable t : tables) {
final Set<Link> foreignLinks = t.getDBSystemRoot().getGraph().getForeignLinks(t);
if (foreignLinks.size() > 0) {
final Set<List<String>> realFKs = new HashSet<List<String>>();
for (final Link link : foreignLinks) {
// if name is null, link is virtual
if (link.getName() != null)
realFKs.add(link.getCols());
}
final Set<List<String>> allFKs = new HashSet<List<String>>(realFKs);
for (final String virtualFK : SQLKey.foreignKeys(t))
allFKs.add(singletonList(virtualFK));
 
if (allFKs.size() > 0) {
// indexes already created
final Set<List<String>> indexes = new HashSet<List<String>>();
for (final Index i : t.getIndexes()) {
51,27 → 69,40
indexes.add(i.getCols());
}
 
for (final Link link : foreignLinks) {
if (link.getName() == null) {
final String s = this.getAddFK(link);
System.err.println(s);
this.getDS().execute(s);
} else {
System.err.println("pas besoin pour " + link);
final AlterTable alter = new AlterTable(t);
for (final List<String> cols : allFKs) {
if (!realFKs.contains(cols)) {
final SQLField key = t.getField(cols.get(0));
final SQLTable foreignT = SQLKey.keyToTable(key);
alter.addForeignConstraint(cols, new SQLName(foreignT.getName()), false, singletonList(t.getKey().getName()));
System.err.println("ajout de " + key);
}
// MySQL automatically creates an index with a foreign key,
// but ours replace it
if (!indexes.contains(link.getCols())) {
final String s = this.getSyntax().getCreateIndex("_fki", link.getSource().getSQLName(), link.getCols());
System.err.println(s);
this.getDS().execute(s);
if (!indexes.contains(cols)) {
alter.addOutsideClause(new DeferredClause() {
@Override
public String asString(ChangeTable<?> ct, SQLName tableName) {
return getSyntax().getCreateIndex("_fki", tableName, cols);
}
 
@Override
public ClauseType getType() {
return ClauseType.ADD_INDEX;
}
});
System.err.println("ajout d'index pour " + cols);
} else {
System.err.println("pas besoin d'index pour " + link);
System.err.println("pas besoin d'index pour " + cols);
}
}
if (!alter.isEmpty()) {
this.getDS().execute(alter.asString());
t.getSchema().updateVersion();
}
}
}
}
 
private void toInno(Set<SQLTable> tables) {
for (final SQLTable t : tables) {
/trunk/OpenConcerto/src/org/openconcerto/sql/PropsConfiguration.java
13,7 → 13,6
package org.openconcerto.sql;
 
import org.openconcerto.sql.element.RowItemViewMetadata;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.SQLElementDirectory.DirectoryListener;
177,8 → 176,6
private Session conn;
private boolean isUsingSSH;
 
protected RowItemViewMetadata metadata;
 
public PropsConfiguration() throws IOException {
this(new File("fwk_SQL.properties"), DEFAULTS);
}
890,8 → 887,4
private final void setWD(final File dir) {
this.wd = dir;
}
 
public RowItemViewMetadata getMetadata() {
return metadata;
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/io/DataInputStream.java
New file
0,0 → 1,66
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.utils.io;
 
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
 
public class DataInputStream extends FilterInputStream {
 
private Boolean littleEndian;
 
public DataInputStream(final InputStream in) {
this(in, null);
}
 
public DataInputStream(final InputStream in, final Boolean littleEndian) {
super(in);
this.littleEndian = littleEndian;
}
 
public final void setLittleEndian(Boolean littleEndian) {
this.littleEndian = littleEndian;
}
 
public final int readInt() throws IOException {
return this.readInt(this.littleEndian);
}
 
public int readInt(final boolean littleEndian) throws IOException {
final int ch1 = this.in.read();
final int ch2 = this.in.read();
final int ch3 = this.in.read();
final int ch4 = this.in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
if (littleEndian)
return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1;
else
return (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4;
}
 
public final short readShort() throws IOException {
return this.readShort(this.littleEndian);
}
 
public short readShort(final boolean littleEndian) throws IOException {
final int ch1 = this.in.read();
final int ch2 = this.in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short) (littleEndian ? (ch2 << 8) + ch1 : (ch1 << 8) + ch2);
}
}
/trunk/OpenConcerto/src/org/openconcerto/utils/FileUtils.java
767,6 → 767,17
}
 
/**
* Return the string after the last dot.
*
* @param fname a name, e.g. "test.odt" or "sans".
* @return the extension, e.g. "odt" or <code>null</code>.
*/
public static final String getExtension(String fname) {
final int lastIndex = fname.lastIndexOf('.');
return lastIndex < 0 ? null : fname.substring(lastIndex + 1);
}
 
/**
* Chars not valid in filenames.
*/
public static final Collection<Character> INVALID_CHARS;
/trunk/OpenConcerto/src/org/openconcerto/utils/NetUtils.java
59,13 → 59,14
}
}
 
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
};
 
public static final String getHTTPContent(String address, boolean useCustomVerifier) {
public static final String getHTTPContent(String address, final boolean dontVerify) {
String content = "";
OutputStream out = null;
HttpsURLConnection conn = null;
75,8 → 76,8
out = new ByteArrayOutputStream();
conn = (HttpsURLConnection) url.openConnection();
// Sur la connexion
if (useCustomVerifier) {
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
if (dontVerify) {
conn.setHostnameVerifier(HostnameNonVerifier);
// ou globalement
// HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
}
/trunk/OpenConcerto/src/org/openconcerto/utils/Tuple2.java
25,7 → 25,13
* @param <B> type of second value.
*/
public class Tuple2<A, B> {
private static final Tuple2<Object, Object> NULL = new Tuple2<Object, Object>(null, null);
 
@SuppressWarnings("unchecked")
public static final <A, B> Tuple2<A, B> nullInstance() {
return (Tuple2<A, B>) NULL;
}
 
// just to make the code shorter
public static final <A, B> Tuple2<A, B> create(A a, B b) {
return new Tuple2<A, B>(a, b);
/trunk/OpenConcerto/src/product.properties
1,2 → 1,2
NAME=OpenConcerto
VERSION=1.2b2
VERSION=1.2b3