Search in sources :

Example 6 with Element

use of ch.interlis.ili2c.metamodel.Element in project ili2db by claeis.

the class MetaAttrUtility method addMetaAttrsFromToml.

/**
 * Read meta-attributes from a toml file and add them to the ili2c metamodel.
 * @param td ili-model as read by the ili compiler
 * @param tomlFile
 * @throws Ili2dbException
 */
public static void addMetaAttrsFromToml(TransferDescription td, FileReader tomlFile) throws Ili2dbException {
    Toml toml = new Toml().read(tomlFile);
    for (java.util.Map.Entry<String, Object> entry : toml.entrySet()) {
        Object entryO = entry.getValue();
        if (entryO instanceof Toml) {
            String iliQName = stripQuotes(entry.getKey());
            Element element = td.getElement(iliQName);
            // known element?
            if (element != null) {
                Toml config = (Toml) entryO;
                for (java.util.Map.Entry<String, Object> configEntry : config.entrySet()) {
                    String paramName = configEntry.getKey();
                    if (configEntry.getValue() instanceof String) {
                        String paramValue = (String) configEntry.getValue();
                        // meta attr not yet defined?
                        if (element.getMetaValue(paramName) == null) {
                            // define/set it
                            element.setMetaValue(paramName, paramValue);
                        }
                    }
                }
            }
        }
    }
}
Also used : Element(ch.interlis.ili2c.metamodel.Element) Toml(com.moandjiezana.toml.Toml) Map(java.util.Map)

Example 7 with Element

use of ch.interlis.ili2c.metamodel.Element in project ili2db by claeis.

the class ReduceToBaseModel method translateObject.

private void translateObject(IomObject iomObj) {
    Element modelElement = (Element) tag2class.get(iomObj.getobjecttag());
    Element destModelEle = getTranslatedElement(modelElement);
    if (destModelEle == modelElement) {
        // no translation required
        return;
    }
    Viewable aclass = (Viewable) modelElement;
    Viewable destClass = (Viewable) destModelEle;
    String destName = destClass.getScopedName();
    iomObj.setobjecttag(destName);
    // handle attrs
    Iterator iter = aclass.getAttributesAndRoles2();
    while (iter.hasNext()) {
        ViewableTransferElement srcProp = (ViewableTransferElement) iter.next();
        ViewableTransferElement destProp = (ViewableTransferElement) srctag2destElement.get(((Element) srcProp.obj).getScopedName());
        if (destProp == null) {
            iomObj.setattrundefined(((Element) srcProp.obj).getName());
        } else {
            if (srcProp.obj instanceof AttributeDef) {
                AttributeDef attr = (AttributeDef) srcProp.obj;
                if (!attr.isTransient()) {
                    Type proxyType = attr.getDomain();
                    if (proxyType != null && (proxyType instanceof ObjectType)) {
                    // skip implicit particles (base-viewables) of views
                    } else {
                        translateAttrValue(iomObj, attr);
                    }
                }
            }
        }
    }
}
Also used : ViewableTransferElement(ch.interlis.ili2c.metamodel.ViewableTransferElement) ObjectType(ch.interlis.ili2c.metamodel.ObjectType) SurfaceType(ch.interlis.ili2c.metamodel.SurfaceType) CompositionType(ch.interlis.ili2c.metamodel.CompositionType) Type(ch.interlis.ili2c.metamodel.Type) EnumerationType(ch.interlis.ili2c.metamodel.EnumerationType) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) ObjectType(ch.interlis.ili2c.metamodel.ObjectType) ViewableTransferElement(ch.interlis.ili2c.metamodel.ViewableTransferElement) Element(ch.interlis.ili2c.metamodel.Element) Viewable(ch.interlis.ili2c.metamodel.Viewable) Iterator(java.util.Iterator) AttributeDef(ch.interlis.ili2c.metamodel.AttributeDef)

Example 8 with Element

use of ch.interlis.ili2c.metamodel.Element in project ili2db by claeis.

the class TransferFromIli method doit.

public DbSchema doit(TransferDescription td1, java.util.List<Element> modelEles, ch.ehi.ili2db.mapping.NameMapping ili2sqlName, ch.ehi.ili2db.gui.Config config, DbIdGen idGen, TrafoConfig trafoConfig, Viewable2TableMapping class2wrapper1, CustomMapping customMapping1) throws Ili2dbException {
    this.ili2sqlName = ili2sqlName;
    createEnumTable = config.getCreateEnumDefs();
    createStdCols = config.CREATE_STD_COLS_ALL.equals(config.getCreateStdCols());
    createFk = config.CREATE_FK_YES.equals(config.getCreateFk());
    createFkIdx = config.CREATE_FKIDX_YES.equals(config.getCreateFkIdx());
    colT_ID = config.getColT_ID();
    if (colT_ID == null) {
        colT_ID = DbNames.T_ID_COL;
    }
    deleteExistingData = config.DELETE_DATA.equals(config.getDeleteMode());
    if (deleteExistingData) {
        EhiLogger.logState("delete existing data...");
    }
    createIliTidCol = config.TID_HANDLING_PROPERTY.equals(config.getTidHandling());
    createBasketCol = config.BASKET_HANDLING_READWRITE.equals(config.getBasketHandling());
    createDatasetCol = config.CREATE_DATASET_COL.equals(config.getCreateDatasetCols());
    isIli1Model = td1.getIli1Format() != null;
    createItfLineTables = isIli1Model && config.getDoItfLineTables();
    customMapping = customMapping1;
    customMapping.fromIliInit(config);
    schema = new DbSchema();
    schema.setName(config.getDbschema());
    visitedElements = new HashSet<Element>();
    class2wrapper = class2wrapper1;
    visitedEnums = new HashSet();
    td = td1;
    recConv = new FromIliRecordConverter(td, ili2sqlName, config, schema, customMapping, idGen, visitedEnums, trafoConfig, class2wrapper, metaInfo);
    visitedWrapper = new HashSet<ViewableWrapper>();
    generatModelEles(modelEles, 1);
    visitedWrapper = new HashSet<ViewableWrapper>();
    generatModelEles(modelEles, 2);
    // sys_interlisnames
    // interlis LONGVARCHAR(767)
    // db VARCHAR(30)
    customMapping.fromIliEnd(config);
    return schema;
}
Also used : DbSchema(ch.ehi.sqlgen.repository.DbSchema) Element(ch.interlis.ili2c.metamodel.Element) ViewableWrapper(ch.ehi.ili2db.mapping.ViewableWrapper) HashSet(java.util.HashSet)

Example 9 with Element

use of ch.interlis.ili2c.metamodel.Element in project ili2db by claeis.

the class Ili2db method runSchemaImport.

public static void runSchemaImport(Config config, String appHome) throws Ili2dbException {
    ch.ehi.basics.logging.FileListener logfile = null;
    if (config.getLogfile() != null) {
        logfile = new FileLogger(new java.io.File(config.getLogfile()));
        EhiLogger.getInstance().addListener(logfile);
    }
    StdLogger logStderr = new StdLogger(config.getLogfile());
    EhiLogger.getInstance().addListener(logStderr);
    EhiLogger.getInstance().removeListener(StdListener.getInstance());
    try {
        boolean connectionFromExtern = config.getJdbcConnection() != null;
        logGeneralInfo(config);
        Ili2dbLibraryInit ao = null;
        try {
            ao = getInitStrategy(config);
            ao.init();
            ch.interlis.ili2c.config.Configuration modelv = new ch.interlis.ili2c.config.Configuration();
            String xtffile = config.getXtffile();
            String ilifile = null;
            if (xtffile != null && xtffile.endsWith(".ili")) {
                ilifile = xtffile;
                modelv.addFileEntry(new ch.interlis.ili2c.config.FileEntry(ilifile, ch.interlis.ili2c.config.FileEntryKind.ILIMODELFILE));
            }
            String models = config.getModels();
            if (models != null) {
                String[] modelnames = models.split(";");
                for (int modeli = 0; modeli < modelnames.length; modeli++) {
                    String m = modelnames[modeli];
                    if (m != null) {
                        if (m.equals(XTF)) {
                        // ignore it
                        } else {
                            modelv.addFileEntry(new ch.interlis.ili2c.config.FileEntry(m, ch.interlis.ili2c.config.FileEntryKind.ILIMODELFILE));
                        }
                    }
                }
            }
            if (modelv.getSizeFileEntry() == 0) {
                throw new Ili2dbException("no models given");
            }
            String dburl = config.getDburl();
            String dbusr = config.getDbusr();
            String dbpwd = config.getDbpwd();
            if (!connectionFromExtern && dburl == null) {
                throw new Ili2dbException("no dburl given");
            }
            if (dbusr == null) {
                // EhiLogger.logError("no dbusr given");
                // return;
                dbusr = "";
            }
            if (dbpwd == null) {
                // EhiLogger.logError("no dbpwd given");
                // return;
                dbpwd = "";
            }
            String dbschema = config.getDbschema();
            if (dbschema != null) {
                EhiLogger.logState("dbschema <" + dbschema + ">");
            }
            String geometryConverter = config.getGeometryConverter();
            if (geometryConverter == null) {
                throw new Ili2dbException("no geoemtry converter given");
            }
            String ddlGenerator = config.getDdlGenerator();
            if (ddlGenerator == null) {
                throw new Ili2dbException("no DDL generator given");
            }
            String idGenerator = config.getIdGenerator();
            if (idGenerator == null) {
                throw new Ili2dbException("no ID generator given");
            }
            if (!connectionFromExtern) {
                String jdbcDriver = config.getJdbcDriver();
                if (jdbcDriver == null) {
                    throw new Ili2dbException("no JDBC driver given");
                }
                try {
                    Class.forName(jdbcDriver);
                } catch (Exception ex) {
                    throw new Ili2dbException("failed to load JDBC driver", ex);
                }
            }
            CustomMapping customMapping = getCustomMappingStrategy(config);
            // open db connection
            Connection conn = null;
            String url = dburl;
            try {
                if (connectionFromExtern) {
                    conn = config.getJdbcConnection();
                } else {
                    conn = connect(url, dbusr, dbpwd, config, customMapping);
                }
                customMapping.postConnect(conn, config);
                logDBVersion(conn);
                if (!connectionFromExtern) {
                    // switch off auto-commit
                    conn.setAutoCommit(false);
                }
            } catch (SQLException ex) {
                throw new Ili2dbException(ex);
            }
            // run pre-script
            if (config.getPreScript() != null) {
                try {
                    EhiLogger.logState("run schemaImport pre-script...");
                    DbUtility.executeSqlScript(conn, new java.io.FileReader(config.getPreScript()));
                } catch (FileNotFoundException e) {
                    throw new Ili2dbException("schemaImport pre-script statements failed", e);
                }
            }
            // setup ilidirs+pathmap for ili2c
            setupIli2cPathmap(config, appHome, ilifile, conn);
            Ili2cMetaAttrs ili2cMetaAttrs = new Ili2cMetaAttrs();
            setupIli2cMetaAttrs(ili2cMetaAttrs, config, modelv);
            // compile required ili files
            EhiLogger.logState("compile models...");
            TransferDescription td;
            modelv.setAutoCompleteModelList(true);
            modelv.setGenerateWarnings(false);
            td = ch.interlis.ili2c.Main.runCompiler(modelv, config, ili2cMetaAttrs);
            if (td == null) {
                throw new Ili2dbException("compiler failed");
            }
            // an INTERLIS 1 model?
            if (td.getIli1Format() != null) {
                config.setItfTransferfile(true);
            }
            Generator gen = null;
            try {
                gen = (Generator) Class.forName(ddlGenerator).newInstance();
            } catch (Exception ex) {
                throw new Ili2dbException("failed to load/create DDL generator", ex);
            }
            // create db schema
            if (config.getDbschema() != null) {
                if (!DbUtility.schemaExists(conn, config.getDbschema())) {
                    DbUtility.createSchema(conn, config.getDbschema());
                }
            }
            DbIdGen idGen = null;
            try {
                idGen = (DbIdGen) Class.forName(idGenerator).newInstance();
            } catch (Exception ex) {
                throw new Ili2dbException("failed to load/create ID generator", ex);
            }
            idGen.init(config.getDbschema(), config);
            // read mapping file
            NameMapping mapping = new NameMapping(config);
            if (DbUtility.tableExists(conn, new DbTableName(config.getDbschema(), DbNames.CLASSNAME_TAB))) {
                // read mapping from db
                mapping.readTableMappingTable(conn, config.getDbschema());
            }
            if (DbUtility.tableExists(conn, new DbTableName(config.getDbschema(), DbNames.ATTRNAME_TAB))) {
                // read mapping from db
                mapping.readAttrMappingTable(conn, config.getDbschema());
            }
            TrafoConfig trafoConfig = new TrafoConfig();
            trafoConfig.readTrafoConfig(conn, config.getDbschema());
            ModelElementSelector ms = new ModelElementSelector();
            ArrayList<String> modelNames = new ArrayList<String>();
            if (models != null) {
                String[] modelnames = models.split(";");
                for (int modeli = 0; modeli < modelnames.length; modeli++) {
                    String m = modelnames[modeli];
                    if (m != null) {
                        if (m.equals(XTF)) {
                        // ignore it
                        } else {
                            modelNames.add(m);
                        }
                    }
                }
            }
            // use models explicitly given by user (or last model of given ili-file)
            java.util.List<Element> eles = ms.getModelElements(modelNames, td, td.getIli1Format() != null && config.getDoItfLineTables(), Config.CREATE_ENUM_DEFS_MULTI.equals(config.getCreateEnumDefs()), config);
            Viewable2TableMapping class2wrapper = Viewable2TableMapper.getClass2TableMapping(config, trafoConfig, eles, mapping);
            SqlColumnConverter geomConverter = null;
            try {
                geomConverter = (SqlColumnConverter) Class.forName(geometryConverter).newInstance();
            } catch (Exception ex) {
                throw new Ili2dbException("failed to load/create geometry converter", ex);
            }
            geomConverter.setup(conn, config);
            if (config.getDefaultSrsCode() != null && config.getDefaultSrsAuthority() != null) {
                try {
                    if (geomConverter.getSrsid(config.getDefaultSrsAuthority(), config.getDefaultSrsCode(), conn) == null) {
                        throw new Ili2dbException(config.getDefaultSrsAuthority() + "/" + config.getDefaultSrsCode() + " does not exist");
                    }
                } catch (ConverterException ex) {
                    throw new Ili2dbException("failed to query existence of SRS", ex);
                }
            }
            // create table structure
            EhiLogger.logState("create table structure...");
            try {
                TransferFromIli trsfFromIli = new TransferFromIli();
                // map ili-classes to sql-tables
                // TODO move default SRS to config
                DbSchema schema;
                try {
                    schema = trsfFromIli.doit(td, eles, mapping, config, idGen, trafoConfig, class2wrapper, customMapping);
                } catch (Ili2dbException e) {
                    throw new Ili2dbException("mapping of ili-classes to sql-tables failed", e);
                }
                if (schema == null) {
                    return;
                }
                if (!(conn instanceof GeodbConnection)) {
                    trsfFromIli.addBasketsTable(schema);
                    trsfFromIli.addImportsTable(schema);
                    TransferFromIli.addInheritanceTable(schema, Integer.parseInt(config.getMaxSqlNameLength()));
                    TransferFromIli.addSettingsTable(schema);
                    TransferFromIli.addTrafoConfigTable(schema);
                    TransferFromIli.addModelsTable(schema, config);
                    trsfFromIli.addEnumTable(schema);
                    TransferFromIli.addTableMappingTable(schema);
                    TransferFromIli.addAttrMappingTable(schema);
                    DbExtMetaInfo.addMetaInfoTables(schema);
                    idGen.addMappingTable(schema);
                    if (config.getCreateMetaInfo()) {
                        MetaAttrUtility.addMetaAttributesTable(schema);
                    }
                }
                // TODO create geodb domains
                if (conn instanceof GeodbConnection) {
                }
                GeneratorDriver drv = new GeneratorDriver(gen);
                idGen.initDb(conn, dbusr);
                idGen.initDbDefs(gen);
                drv.visitSchema(config, schema);
                // is a create script requested by user?
                String createscript = config.getCreatescript();
                if (createscript != null && (gen instanceof GeneratorJdbc)) {
                    writeScript(createscript, ((GeneratorJdbc) gen).iteratorCreateLines());
                }
                // is a drop script requested by user?
                String dropscript = config.getDropscript();
                if (dropscript != null && (gen instanceof GeneratorJdbc)) {
                    writeScript(dropscript, ((GeneratorJdbc) gen).iteratorDropLines());
                }
                if (!(conn instanceof GeodbConnection)) {
                    // update mapping table
                    mapping.updateTableMappingTable(conn, config.getDbschema());
                    mapping.updateAttrMappingTable(conn, config.getDbschema());
                    trafoConfig.updateTrafoConfig(conn, config.getDbschema());
                    // update inheritance table
                    trsfFromIli.updateInheritanceTable(conn, config.getDbschema());
                    // update enum table
                    trsfFromIli.updateEnumTable(conn);
                    trsfFromIli.updateMetaInfoTables(conn);
                    TransferFromIli.addModels(conn, td, config.getDbschema());
                    if (!config.isConfigReadFromDb()) {
                        TransferFromIli.updateSettings(conn, config, config.getDbschema());
                    }
                    // import meta-attributes from .toml file
                    if (config.getIliMetaAttrsFile() != null) {
                        if (config.getCreateMetaInfo()) {
                            try {
                                EhiLogger.logState("run import meta-attributes from toml file");
                                MetaAttrUtility.addMetaAttrsFromToml(td, new java.io.FileReader(config.getIliMetaAttrsFile()));
                            } catch (FileNotFoundException e) {
                                throw new Ili2dbException("import meta-attributes failed", e);
                            }
                        } else {
                            throw new Ili2dbException("import meta-attributes requires --createMetaInfo option");
                        }
                    }
                    if (config.getCreateMetaInfo()) {
                        // update meta-attributes table
                        MetaAttrUtility.updateMetaAttributesTable(conn, config.getDbschema(), td);
                        // set elements' meta-attributes
                        MetaAttrUtility.addMetaAttrsFromDb(td, conn, config.getDbschema());
                    }
                }
                // run post-script
                if (config.getPostScript() != null) {
                    try {
                        EhiLogger.logState("run schemaImport post-script...");
                        DbUtility.executeSqlScript(conn, new java.io.FileReader(config.getPostScript()));
                    } catch (FileNotFoundException e) {
                        throw new Ili2dbException("schemaImport post-script statements failed", e);
                    }
                }
                // }
                if (!connectionFromExtern) {
                    try {
                        conn.commit();
                    } catch (SQLException e) {
                        throw new Ili2dbException("failed to commit", e);
                    }
                }
            } catch (java.io.IOException ex) {
                throw new Ili2dbException(ex);
            }
            try {
                if (!connectionFromExtern) {
                    if (conn != null) {
                        try {
                            conn.close();
                        } finally {
                            conn = null;
                            config.setJdbcConnection(null);
                        }
                    }
                }
                EhiLogger.logState("...done");
            } catch (java.sql.SQLException ex) {
                EhiLogger.logError(ex);
            }
        } finally {
            ao.end();
        }
    } catch (Ili2dbException ex) {
        if (logfile != null) {
            logfile.logEvent(new StdLogEvent(LogEvent.ERROR, null, ex, null));
        }
        throw ex;
    } catch (java.lang.RuntimeException ex) {
        if (logfile != null) {
            logfile.logEvent(new StdLogEvent(LogEvent.ERROR, null, ex, null));
        }
        throw ex;
    } finally {
        if (logfile != null) {
            EhiLogger.getInstance().removeListener(logfile);
            logfile.close();
            logfile = null;
        }
        if (logStderr != null) {
            EhiLogger.getInstance().addListener(StdListener.getInstance());
            EhiLogger.getInstance().removeListener(logStderr);
        }
    }
}
Also used : ConverterException(ch.ehi.ili2db.converter.ConverterException) NameMapping(ch.ehi.ili2db.mapping.NameMapping) Configuration(ch.interlis.ili2c.config.Configuration) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Viewable2TableMapping(ch.ehi.ili2db.mapping.Viewable2TableMapping) GeneratorDriver(ch.ehi.sqlgen.generator.GeneratorDriver) TrafoConfig(ch.ehi.ili2db.mapping.TrafoConfig) TransferDescription(ch.interlis.ili2c.metamodel.TransferDescription) FileLogger(ch.interlis.iox_j.logging.FileLogger) SqlColumnConverter(ch.ehi.ili2db.converter.SqlColumnConverter) DbTableName(ch.ehi.sqlgen.repository.DbTableName) Generator(ch.ehi.sqlgen.generator.Generator) SQLException(java.sql.SQLException) StdLogEvent(ch.ehi.basics.logging.StdLogEvent) Element(ch.interlis.ili2c.metamodel.Element) CustomMapping(ch.ehi.ili2db.fromili.CustomMapping) SQLException(java.sql.SQLException) GeneratorJdbc(ch.ehi.sqlgen.generator_impl.jdbc.GeneratorJdbc) StdLogger(ch.interlis.iox_j.logging.StdLogger) TransferFromIli(ch.ehi.ili2db.fromili.TransferFromIli) Ili2cMetaAttrs(ch.interlis.ili2c.metamodel.Ili2cMetaAttrs) DbSchema(ch.ehi.sqlgen.repository.DbSchema) Connection(java.sql.Connection) IOException(java.io.IOException) IoxException(ch.interlis.iox.IoxException) FileNotFoundException(java.io.FileNotFoundException) SQLException(java.sql.SQLException) ConverterException(ch.ehi.ili2db.converter.ConverterException) IOException(java.io.IOException) Configuration(ch.interlis.ili2c.config.Configuration) ModelElementSelector(ch.ehi.ili2db.fromili.ModelElementSelector)

Example 10 with Element

use of ch.interlis.ili2c.metamodel.Element in project ili2db by claeis.

the class Ili2db method runExport.

public static void runExport(Config config, String appHome) throws Ili2dbException {
    ch.ehi.basics.logging.FileListener logfile = null;
    if (config.getLogfile() != null) {
        logfile = new FileLogger(new java.io.File(config.getLogfile()));
        EhiLogger.getInstance().addListener(logfile);
    }
    StdLogger logStderr = new StdLogger(config.getLogfile());
    EhiLogger.getInstance().addListener(logStderr);
    EhiLogger.getInstance().removeListener(StdListener.getInstance());
    try {
        boolean connectionFromExtern = config.getJdbcConnection() != null;
        logGeneralInfo(config);
        String xtffile = config.getXtffile();
        if (xtffile == null) {
            throw new Ili2dbException("no xtf-file given");
        }
        String modeldir = config.getModeldir();
        if (modeldir == null) {
            throw new Ili2dbException("no modeldir given");
        }
        String dburl = config.getDburl();
        String dbusr = config.getDbusr();
        String dbpwd = config.getDbpwd();
        if (!connectionFromExtern && dburl == null) {
            throw new Ili2dbException("no dburl given");
        }
        if (dbusr == null) {
            // EhiLogger.logError("no dbusr given");
            // return;
            dbusr = "";
        }
        if (dbpwd == null) {
            // EhiLogger.logError("no dbpwd given");
            // return;
            dbpwd = "";
        }
        String dbschema = config.getDbschema();
        if (dbschema != null) {
            EhiLogger.logState("dbschema <" + dbschema + ">");
        }
        String geometryConverter = config.getGeometryConverter();
        if (geometryConverter == null) {
            throw new Ili2dbException("no geoemtry converter given");
        }
        if (!connectionFromExtern) {
            String jdbcDriver = config.getJdbcDriver();
            if (jdbcDriver == null) {
                throw new Ili2dbException("no JDBC driver given");
            }
            // open db connection
            try {
                Class.forName(jdbcDriver);
            } catch (Exception ex) {
                throw new Ili2dbException("failed to load JDBC driver", ex);
            }
        }
        String baskets = config.getBaskets();
        String topics = config.getTopics();
        String models = config.getModels();
        String datasetName = config.getDatasetName();
        if (models == null && baskets == null && topics == null && datasetName == null) {
            throw new Ili2dbException("no dataset, baskets, models or topics given");
        }
        CustomMapping customMapping = getCustomMappingStrategy(config);
        Connection conn = null;
        String url = dburl;
        try {
            // DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            try {
                if (connectionFromExtern) {
                    conn = config.getJdbcConnection();
                } else {
                    conn = connect(url, dbusr, dbpwd, config, customMapping);
                }
                customMapping.postConnect(conn, config);
            } catch (SQLException e) {
                throw new Ili2dbException("failed to get db connection", e);
            }
            logDBVersion(conn);
            // run pre-script
            if (config.getPreScript() != null) {
                try {
                    EhiLogger.logState("run export pre-script...");
                    DbUtility.executeSqlScript(conn, new java.io.FileReader(config.getPreScript()));
                } catch (FileNotFoundException e) {
                    throw new Ili2dbException("export pre-script statements failed", e);
                }
            }
            ch.interlis.ili2c.config.Configuration modelv = new ch.interlis.ili2c.config.Configuration();
            boolean createBasketCol = config.BASKET_HANDLING_READWRITE.equals(config.getBasketHandling());
            String[] exportModelnames = null;
            long[] basketSqlIds = null;
            if (datasetName != null) {
                if (!createBasketCol) {
                    throw new Ili2dbException("dataset wise export requires column " + DbNames.T_BASKET_COL);
                }
                // map datasetName to sqlBasketId and modelnames
                Long datasetId = getDatasetId(datasetName, conn, config);
                if (datasetId == null) {
                    throw new Ili2dbException("dataset <" + datasetName + "> doesn't exist");
                }
                basketSqlIds = getBasketSqlIdsFromDatasetId(datasetId, modelv, conn, config);
            } else if (baskets != null) {
                if (!createBasketCol) {
                    throw new Ili2dbException("basket wise export requires column " + DbNames.T_BASKET_COL);
                }
                // BIDs
                String[] basketids = baskets.split(ch.interlis.ili2c.Main.MODELS_SEPARATOR);
                // map BID to sqlBasketId and modelnames
                basketSqlIds = getBasketSqlIdsFromBID(basketids, modelv, conn, config);
            } else if (topics != null) {
                if (!createBasketCol) {
                    throw new Ili2dbException("topic wise export requires column " + DbNames.T_BASKET_COL);
                }
                // TOPICs
                String[] topicv = topics.split(ch.interlis.ili2c.Main.MODELS_SEPARATOR);
                // map BID to sqlBasketId and modelnames
                basketSqlIds = getBasketSqlIdsFromTopic(topicv, modelv, conn, config);
            } else {
                if (createBasketCol) {
                    String[] modelnames = getModelNames(models);
                    basketSqlIds = getBasketSqlIdsFromModel(modelnames, modelv, conn, config);
                } else {
                    exportModelnames = getModelNames(models);
                    for (int modeli = 0; modeli < exportModelnames.length; modeli++) {
                        String m = exportModelnames[modeli];
                        if (m.equals(XTF)) {
                        // TODO read modelname from db
                        }
                        modelv.addFileEntry(new ch.interlis.ili2c.config.FileEntry(m, ch.interlis.ili2c.config.FileEntryKind.ILIMODELFILE));
                    }
                }
            }
            if (modelv.getSizeFileEntry() == 0) {
                throw new Ili2dbException("no models given");
            }
            String adapterClassName = config.getGeometryConverter();
            if (adapterClassName == null) {
                throw new Ili2dbException("no adapter given");
            }
            SqlColumnConverter geomConverter = null;
            try {
                geomConverter = (SqlColumnConverter) Class.forName(geometryConverter).newInstance();
            } catch (Exception ex) {
                throw new Ili2dbException("failed to load/create geometry converter", ex);
            }
            // compile required ili files
            setupIli2cPathmap(config, appHome, xtffile, conn);
            Ili2cMetaAttrs ili2cMetaAttrs = new Ili2cMetaAttrs();
            // don't add ili1 model translations to model list (should already be in list because of topicname in t_baskets table)
            setupIli2cMetaAttrs(ili2cMetaAttrs, config, null);
            EhiLogger.logState("compile models...");
            modelv.setAutoCompleteModelList(true);
            modelv.setGenerateWarnings(false);
            TransferDescription td = ch.interlis.ili2c.Main.runCompiler(modelv, config, ili2cMetaAttrs);
            if (td == null) {
                throw new Ili2dbException("compiler failed");
            }
            if (config.getCreateMetaInfo()) {
                // set elements' meta-attributes
                if (DbUtility.tableExists(conn, new DbTableName(config.getDbschema(), DbNames.META_ATTRIBUTES_TAB))) {
                    MetaAttrUtility.addMetaAttrsFromDb(td, conn, config.getDbschema());
                }
            }
            geomConverter.setup(conn, config);
            // get mapping definition
            NameMapping mapping = new NameMapping(config);
            if (DbUtility.tableExists(conn, new DbTableName(config.getDbschema(), DbNames.CLASSNAME_TAB))) {
                // read mapping from db
                mapping.readTableMappingTable(conn, config.getDbschema());
            }
            if (DbUtility.tableExists(conn, new DbTableName(config.getDbschema(), DbNames.ATTRNAME_TAB))) {
                // read mapping from db
                mapping.readAttrMappingTable(conn, config.getDbschema());
            }
            TrafoConfig trafoConfig = new TrafoConfig();
            trafoConfig.readTrafoConfig(conn, config.getDbschema());
            ModelElementSelector ms = new ModelElementSelector();
            ArrayList<String> modelNames = new ArrayList<String>();
            {
                Iterator<ch.interlis.ili2c.config.FileEntry> modi = modelv.iteratorFileEntry();
                while (modi.hasNext()) {
                    ch.interlis.ili2c.config.FileEntry mod = modi.next();
                    if (mod.getKind() == ch.interlis.ili2c.config.FileEntryKind.ILIMODELFILE) {
                        modelNames.add(mod.getFilename());
                        EhiLogger.traceState("modelname <" + mod.getFilename() + ">");
                    }
                }
            }
            // use models explicitly given by user (--models, --baskets, --dataset, --topics)
            java.util.List<Element> eles = ms.getModelElements(modelNames, td, td.getIli1Format() != null && config.getDoItfLineTables(), Config.CREATE_ENUM_DEFS_MULTI.equals(config.getCreateEnumDefs()), config);
            Viewable2TableMapping class2wrapper = Viewable2TableMapper.getClass2TableMapping(config, trafoConfig, eles, mapping);
            // process xtf files
            EhiLogger.logState("process data...");
            EhiLogger.logState("data <" + xtffile + ">");
            Map<Long, BasketStat> stat = new HashMap<Long, BasketStat>();
            ch.ehi.basics.logging.ErrorTracker errs = new ch.ehi.basics.logging.ErrorTracker();
            EhiLogger.getInstance().addListener(errs);
            transferToXtf(conn, xtffile, mapping, td, geomConverter, config.getSender(), config, exportModelnames, basketSqlIds, stat, trafoConfig, class2wrapper);
            if (errs.hasSeenErrors()) {
                throw new Ili2dbException("...export failed");
            } else {
                logStatistics(td.getIli1Format() != null, stat);
                EhiLogger.logState("...export done");
            }
            EhiLogger.getInstance().removeListener(errs);
            // run post-script
            if (config.getPostScript() != null) {
                try {
                    DbUtility.executeSqlScript(conn, new java.io.FileReader(config.getPostScript()));
                    EhiLogger.logState("run export post-script...");
                } catch (FileNotFoundException e) {
                    throw new Ili2dbException("export post-script statements failed", e);
                }
            }
        // }catch(Exception ex){
        // EhiLogger.logError(ex);
        } finally {
            if (!connectionFromExtern) {
                try {
                    conn.close();
                } catch (java.sql.SQLException ex) {
                    EhiLogger.logError(ex);
                } finally {
                    conn = null;
                    config.setJdbcConnection(null);
                }
            }
        }
    } catch (Ili2dbException ex) {
        if (logfile != null) {
            logfile.logEvent(new StdLogEvent(LogEvent.ERROR, null, ex, null));
        }
        throw ex;
    } catch (java.lang.RuntimeException ex) {
        if (logfile != null) {
            logfile.logEvent(new StdLogEvent(LogEvent.ERROR, null, ex, null));
        }
        throw ex;
    } finally {
        if (logfile != null) {
            EhiLogger.getInstance().removeListener(logfile);
            logfile.close();
            logfile = null;
        }
        if (logStderr != null) {
            EhiLogger.getInstance().addListener(StdListener.getInstance());
            EhiLogger.getInstance().removeListener(logStderr);
        }
    }
}
Also used : NameMapping(ch.ehi.ili2db.mapping.NameMapping) Configuration(ch.interlis.ili2c.config.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Viewable2TableMapping(ch.ehi.ili2db.mapping.Viewable2TableMapping) TrafoConfig(ch.ehi.ili2db.mapping.TrafoConfig) TransferDescription(ch.interlis.ili2c.metamodel.TransferDescription) FileLogger(ch.interlis.iox_j.logging.FileLogger) SqlColumnConverter(ch.ehi.ili2db.converter.SqlColumnConverter) DbTableName(ch.ehi.sqlgen.repository.DbTableName) SQLException(java.sql.SQLException) StdLogEvent(ch.ehi.basics.logging.StdLogEvent) Element(ch.interlis.ili2c.metamodel.Element) CustomMapping(ch.ehi.ili2db.fromili.CustomMapping) SQLException(java.sql.SQLException) StdLogger(ch.interlis.iox_j.logging.StdLogger) Iterator(java.util.Iterator) Ili2cMetaAttrs(ch.interlis.ili2c.metamodel.Ili2cMetaAttrs) Connection(java.sql.Connection) IoxException(ch.interlis.iox.IoxException) FileNotFoundException(java.io.FileNotFoundException) SQLException(java.sql.SQLException) ConverterException(ch.ehi.ili2db.converter.ConverterException) IOException(java.io.IOException) Configuration(ch.interlis.ili2c.config.Configuration) BasketStat(ch.ehi.ili2db.fromxtf.BasketStat) ModelElementSelector(ch.ehi.ili2db.fromili.ModelElementSelector)

Aggregations

Element (ch.interlis.ili2c.metamodel.Element)14 ViewableTransferElement (ch.interlis.ili2c.metamodel.ViewableTransferElement)7 Viewable (ch.interlis.ili2c.metamodel.Viewable)5 ArrayList (java.util.ArrayList)4 StdLogEvent (ch.ehi.basics.logging.StdLogEvent)3 ConverterException (ch.ehi.ili2db.converter.ConverterException)3 SqlColumnConverter (ch.ehi.ili2db.converter.SqlColumnConverter)3 CustomMapping (ch.ehi.ili2db.fromili.CustomMapping)3 ModelElementSelector (ch.ehi.ili2db.fromili.ModelElementSelector)3 NameMapping (ch.ehi.ili2db.mapping.NameMapping)3 TrafoConfig (ch.ehi.ili2db.mapping.TrafoConfig)3 Viewable2TableMapping (ch.ehi.ili2db.mapping.Viewable2TableMapping)3 DbSchema (ch.ehi.sqlgen.repository.DbSchema)3 DbTableName (ch.ehi.sqlgen.repository.DbTableName)3 Configuration (ch.interlis.ili2c.config.Configuration)3 Ili2cMetaAttrs (ch.interlis.ili2c.metamodel.Ili2cMetaAttrs)3 TransferDescription (ch.interlis.ili2c.metamodel.TransferDescription)3 IoxException (ch.interlis.iox.IoxException)3 FileLogger (ch.interlis.iox_j.logging.FileLogger)3 StdLogger (ch.interlis.iox_j.logging.StdLogger)3