Mercurial > dive4elements > river
changeset 5828:dfb26b03b179
Moved directories to org.dive4elements.river
line wrap: on
line diff
--- a/flys-backend/src/main/java/de/intevation/flys/App.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,30 +0,0 @@ -package de.intevation.flys; - -import de.intevation.flys.backend.SessionFactoryProvider; -import de.intevation.flys.backend.FLYSCredentials; - -import org.hibernate.cfg.Configuration; - -import org.hibernate.dialect.resolver.DialectFactory; - -public class App -{ - public static void dumpSchema(Configuration cfg) { - System.out.println("BEGIN;"); - - String [] setupScript = cfg.generateSchemaCreationScript( - DialectFactory.constructDialect( - FLYSCredentials.getDefault().getDialect())); - - for (String line: setupScript) { - System.out.println(line + ";"); - } - - System.out.println("COMMIT;"); - } - - public static void main(String [] args) { - dumpSchema(SessionFactoryProvider.createConfiguration()); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/Credentials.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -package de.intevation.flys.backend; - -public abstract class Credentials -{ - protected String user; - protected String password; - protected String dialect; - protected String driver; - protected String url; - protected String connectionInitSqls; - protected Class [] classes; - - public Credentials() { - } - - public Credentials( - String user, - String password, - String dialect, - String driver, - String url, - String connectionInitSqls, - Class [] classes - ) { - this.user = user; - this.password = password; - this.dialect = dialect; - this.driver = driver; - this.url = url; - this.connectionInitSqls = connectionInitSqls; - this.classes = classes; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getDialect() { - return dialect; - } - - public void setDialect(String dialect) { - this.dialect = dialect; - } - - public String getDriver() { - return driver; - } - - public void setDriver(String driver) { - this.driver = driver; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getConnectionInitSqls() { - return connectionInitSqls; - } - - public void setConnectionInitSqls(String connectionInitSqls) { - this.connectionInitSqls = connectionInitSqls; - } - - public Class [] getClasses() { - return classes; - } - - public void setClasses(Class [] classes) { - this.classes = classes; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/FLYSCredentials.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,253 +0,0 @@ -package de.intevation.flys.backend; - -import de.intevation.artifacts.common.utils.Config; - -import de.intevation.flys.model.Annotation; -import de.intevation.flys.model.AnnotationType; -import de.intevation.flys.model.Attribute; -import de.intevation.flys.model.AxisKind; -import de.intevation.flys.model.BedHeightEpoch; -import de.intevation.flys.model.BedHeightEpochValue; -import de.intevation.flys.model.BedHeightSingle; -import de.intevation.flys.model.BedHeightSingleValue; -import de.intevation.flys.model.BedHeightType; -import de.intevation.flys.model.Building; -import de.intevation.flys.model.BoundaryKind; -import de.intevation.flys.model.CrossSection; -import de.intevation.flys.model.CrossSectionLine; -import de.intevation.flys.model.CrossSectionPoint; -import de.intevation.flys.model.CrossSectionTrack; -import de.intevation.flys.model.CrossSectionTrackKind; -import de.intevation.flys.model.DGM; -import de.intevation.flys.model.Depth; -import de.intevation.flys.model.DischargeTable; -import de.intevation.flys.model.DischargeTableValue; -import de.intevation.flys.model.DischargeZone; -import de.intevation.flys.model.Edge; -import de.intevation.flys.model.ElevationModel; -import de.intevation.flys.model.FedState; -import de.intevation.flys.model.Fixpoint; -import de.intevation.flys.model.Floodmaps; -import de.intevation.flys.model.Floodmark; -import de.intevation.flys.model.Floodplain; -import de.intevation.flys.model.FloodplainKind; -import de.intevation.flys.model.FlowVelocityMeasurement; -import de.intevation.flys.model.FlowVelocityMeasurementValue; -import de.intevation.flys.model.FlowVelocityModel; -import de.intevation.flys.model.FlowVelocityModelValue; -import de.intevation.flys.model.Gauge; -import de.intevation.flys.model.GaugeLocation; -import de.intevation.flys.model.GrainFraction; -import de.intevation.flys.model.HWSKind; -import de.intevation.flys.model.HWSLine; -import de.intevation.flys.model.HWSPoint; -import de.intevation.flys.model.HYK; -import de.intevation.flys.model.HYKEntry; -import de.intevation.flys.model.HYKFlowZone; -import de.intevation.flys.model.HYKFlowZoneType; -import de.intevation.flys.model.HYKFormation; -import de.intevation.flys.model.HydrBoundary; -import de.intevation.flys.model.HydrBoundaryPoly; -import de.intevation.flys.model.Jetty; -import de.intevation.flys.model.LocationSystem; -import de.intevation.flys.model.MainValue; -import de.intevation.flys.model.MainValueType; -import de.intevation.flys.model.MeasurementStation; -import de.intevation.flys.model.MorphologicalWidth; -import de.intevation.flys.model.MorphologicalWidthValue; -import de.intevation.flys.model.NamedMainValue; -import de.intevation.flys.model.Position; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; -import de.intevation.flys.model.RiverAxis; -import de.intevation.flys.model.RiverAxisKm; -import de.intevation.flys.model.SQRelation; -import de.intevation.flys.model.SQRelationValue; -import de.intevation.flys.model.SectieKind; -import de.intevation.flys.model.SobekKind; -import de.intevation.flys.model.SedimentDensity; -import de.intevation.flys.model.SedimentDensityValue; -import de.intevation.flys.model.SedimentYield; -import de.intevation.flys.model.SedimentYieldValue; -import de.intevation.flys.model.TimeInterval; -import de.intevation.flys.model.Unit; -import de.intevation.flys.model.Wst; -import de.intevation.flys.model.WstColumn; -import de.intevation.flys.model.WstColumnQRange; -import de.intevation.flys.model.WstColumnValue; -import de.intevation.flys.model.WstQRange; - -public class FLYSCredentials -extends Credentials -{ - public static final String XPATH_USER = - "/artifact-database/backend-database/user/text()"; - - public static final String XPATH_PASSWORD = - "/artifact-database/backend-database/password/text()"; - - public static final String XPATH_DIALECT = - "/artifact-database/backend-database/dialect/text()"; - - public static final String XPATH_DRIVER = - "/artifact-database/backend-database/driver/text()"; - - public static final String XPATH_URL = - "/artifact-database/backend-database/url/text()"; - - public static final String XPATH_CONNECTION_INIT_SQLS = - "/artifact-database/backend-database/connection-init-sqls/text()"; - - public static final String DEFAULT_USER = - System.getProperty("flys.backend.user", "flys"); - - public static final String DEFAULT_PASSWORD = - System.getProperty("flys.backend.password", "flys"); - - public static final String DEFAULT_DIALECT = - System.getProperty( - "flys.backend.dialect", - "org.hibernate.dialect.PostgreSQLDialect"); - - public static final String DEFAULT_DRIVER = - System.getProperty( - "flys.backend.driver", - "org.postgresql.Driver"); - - public static final String DEFAULT_URL = - System.getProperty( - "flys.backend.url", - "jdbc:postgresql://localhost:5432/flys"); - - public static final String DEFAULT_CONNECTION_INIT_SQLS = - System.getProperty( - "flys.backend.connection.init.sqls"); - - public static final Class [] CLASSES = { - Annotation.class, - AnnotationType.class, - Attribute.class, - AxisKind.class, - BedHeightEpoch.class, - BedHeightEpochValue.class, - BedHeightSingle.class, - BedHeightSingleValue.class, - BedHeightType.class, - Building.class, - BoundaryKind.class, - CrossSection.class, - CrossSectionLine.class, - CrossSectionPoint.class, - CrossSectionTrack.class, - CrossSectionTrackKind.class, - Depth.class, - DGM.class, - DischargeTable.class, - DischargeTableValue.class, - DischargeZone.class, - Edge.class, - ElevationModel.class, - FedState.class, - Fixpoint.class, - Floodmark.class, - Floodplain.class, - FloodplainKind.class, - Floodmaps.class, - FlowVelocityMeasurement.class, - FlowVelocityMeasurementValue.class, - FlowVelocityModel.class, - FlowVelocityModelValue.class, - Gauge.class, - GaugeLocation.class, - GrainFraction.class, - HWSKind.class, - HWSLine.class, - HWSPoint.class, - HydrBoundary.class, - HydrBoundaryPoly.class, - HYK.class, - HYKEntry.class, - HYKFormation.class, - HYKFlowZoneType.class, - HYKFlowZone.class, - Jetty.class, - LocationSystem.class, - MainValueType.class, - MeasurementStation.class, - MorphologicalWidth.class, - MorphologicalWidthValue.class, - NamedMainValue.class, - MainValue.class, - Position.class, - Range.class, - River.class, - RiverAxis.class, - RiverAxisKm.class, - SectieKind.class, - SobekKind.class, - SedimentDensity.class, - SedimentDensityValue.class, - SedimentYield.class, - SedimentYieldValue.class, - SQRelation.class, - SQRelationValue.class, - TimeInterval.class, - Unit.class, - WstColumn.class, - WstColumnQRange.class, - WstColumnValue.class, - Wst.class, - WstQRange.class - }; - - public FLYSCredentials() { - } - - public FLYSCredentials( - String user, - String password, - String dialect, - String driver, - String url, - String connectionInitSqls - ) { - super( - user, password, dialect, driver, url, connectionInitSqls, CLASSES); - } - - private static Credentials instance; - - public static synchronized Credentials getInstance() { - if (instance == null) { - String user = - Config.getStringXPath(XPATH_USER, DEFAULT_USER); - String password = - Config.getStringXPath(XPATH_PASSWORD, DEFAULT_PASSWORD); - String dialect = - Config.getStringXPath(XPATH_DIALECT, DEFAULT_DIALECT); - String driver = - Config.getStringXPath(XPATH_DRIVER, DEFAULT_DRIVER); - String url = - Config.getStringXPath(XPATH_URL, DEFAULT_URL); - String connectionInitSqls = - Config.getStringXPath( - XPATH_CONNECTION_INIT_SQLS, - DEFAULT_CONNECTION_INIT_SQLS); - - instance = new FLYSCredentials( - user, password, dialect, driver, url, connectionInitSqls); - } - return instance; - } - - public static Credentials getDefault() { - return new FLYSCredentials( - DEFAULT_USER, - DEFAULT_PASSWORD, - DEFAULT_DIALECT, - DEFAULT_DRIVER, - DEFAULT_URL, - DEFAULT_CONNECTION_INIT_SQLS); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/SedDBCredentials.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,209 +0,0 @@ -package de.intevation.flys.backend; - -import de.intevation.artifacts.common.utils.Config; - -import de.intevation.seddb.model.Bezugspegel; -import de.intevation.seddb.model.Bezugspegelgew; -import de.intevation.seddb.model.BezugspegelgewId; -import de.intevation.seddb.model.Bild; -import de.intevation.seddb.model.Gewaesser; -import de.intevation.seddb.model.Gfaenger; -import de.intevation.seddb.model.Glotlinks; -import de.intevation.seddb.model.GlotlinksId; -import de.intevation.seddb.model.Glotrechte; -import de.intevation.seddb.model.Gprobe; -import de.intevation.seddb.model.GprobeId; -import de.intevation.seddb.model.Gsiebsatz; -import de.intevation.seddb.model.Gsiebung; -import de.intevation.seddb.model.Gsiebungsieb; -import de.intevation.seddb.model.GsiebungsiebId; -import de.intevation.seddb.model.Hpeilpunkt; -import de.intevation.seddb.model.HpeilpunktId; -import de.intevation.seddb.model.Hpeilung; -import de.intevation.seddb.model.Messung; -import de.intevation.seddb.model.Messunglotcount; -import de.intevation.seddb.model.MessunglotcountId; -import de.intevation.seddb.model.Messungsta; -import de.intevation.seddb.model.MessungstaId; -import de.intevation.seddb.model.Messunguferbezug; -import de.intevation.seddb.model.MessunguferbezugId; -import de.intevation.seddb.model.Mpeilpunkt; -import de.intevation.seddb.model.MpeilpunktId; -import de.intevation.seddb.model.Mpeilung; -import de.intevation.seddb.model.Probebild; -import de.intevation.seddb.model.Siebanalyse; -import de.intevation.seddb.model.Slotlinks; -import de.intevation.seddb.model.SlotlinksId; -import de.intevation.seddb.model.Slotrechte; -import de.intevation.seddb.model.Sohlprobe; -import de.intevation.seddb.model.Sohltest; -import de.intevation.seddb.model.Sprobe; -import de.intevation.seddb.model.SprobeId; -import de.intevation.seddb.model.Ssiebung; -import de.intevation.seddb.model.Ssiebungsieb; -import de.intevation.seddb.model.SsiebungsiebId; -import de.intevation.seddb.model.Station; -import de.intevation.seddb.model.Stationgew; -import de.intevation.seddb.model.StationgewId; -import de.intevation.seddb.model.TmpGloChanged; -import de.intevation.seddb.model.TmpMesAchanged; -import de.intevation.seddb.model.TmpMesGchanged; -import de.intevation.seddb.model.TmpMesQchanged; -import de.intevation.seddb.model.TmpMesSchanged; -import de.intevation.seddb.model.Zzarchiv; -import de.intevation.seddb.model.Zzprobenahmeart; -import de.intevation.seddb.model.Zzsondierungart; -import de.intevation.seddb.model.Zzthema; - -public class SedDBCredentials -extends Credentials -{ - public static final String XPATH_USER = - "/artifact-database/seddb-database/user/text()"; - - public static final String XPATH_PASSWORD = - "/artifact-database/seddb-database/password/text()"; - - public static final String XPATH_DIALECT = - "/artifact-database/seddb-database/dialect/text()"; - - public static final String XPATH_DRIVER = - "/artifact-database/seddb-database/driver/text()"; - - public static final String XPATH_URL = - "/artifact-database/seddb-database/url/text()"; - - public static final String XPATH_CONNECTION_INIT_SQLS = - "/artifact-database/seddb-database/connection-init-sqls/text()"; - - public static final String DEFAULT_USER = - System.getProperty("flys.seddb.user", "seddb"); - - public static final String DEFAULT_PASSWORD = - System.getProperty("flys.seddb.password", "seddb"); - - public static final String DEFAULT_DIALECT = - System.getProperty( - "flys.seddb.dialect", - "org.hibernate.dialect.PostgreSQLDialect"); - - public static final String DEFAULT_DRIVER = - System.getProperty( - "flys.seddb.driver", - "org.postgresql.Driver"); - - public static final String DEFAULT_URL = - System.getProperty( - "flys.seddb.url", - "jdbc:postgresql://localhost:5432/seddb"); - - public static final String DEFAULT_CONNECTION_INIT_SQLS = - System.getProperty( - "flys.seddb.connection.init.sqls"); - - public static final Class [] CLASSES = { - BezugspegelgewId.class, - Bezugspegelgew.class, - Bezugspegel.class, - Bild.class, - Gewaesser.class, - Gfaenger.class, - GlotlinksId.class, - Glotlinks.class, - Glotrechte.class, - GprobeId.class, - Gprobe.class, - Gsiebsatz.class, - Gsiebung.class, - GsiebungsiebId.class, - Gsiebungsieb.class, - HpeilpunktId.class, - Hpeilpunkt.class, - Hpeilung.class, - Messung.class, - MessunglotcountId.class, - Messunglotcount.class, - MessungstaId.class, - Messungsta.class, - MessunguferbezugId.class, - Messunguferbezug.class, - MpeilpunktId.class, - Mpeilpunkt.class, - Mpeilung.class, - Probebild.class, - Siebanalyse.class, - SlotlinksId.class, - Slotlinks.class, - Slotrechte.class, - Sohlprobe.class, - Sohltest.class, - SprobeId.class, - Sprobe.class, - Ssiebung.class, - SsiebungsiebId.class, - Ssiebungsieb.class, - StationgewId.class, - Stationgew.class, - Station.class, - TmpGloChanged.class, - TmpMesAchanged.class, - TmpMesGchanged.class, - TmpMesQchanged.class, - TmpMesSchanged.class, - Zzarchiv.class, - Zzprobenahmeart.class, - Zzsondierungart.class, - Zzthema.class - }; - - private static Credentials instance; - - public SedDBCredentials() { - } - - public SedDBCredentials( - String user, - String password, - String dialect, - String driver, - String url, - String connectionInitSqls - ) { - super( - user, password, dialect, driver, url, connectionInitSqls, CLASSES); - } - - public static synchronized Credentials getInstance() { - if (instance == null) { - String user = - Config.getStringXPath(XPATH_USER, DEFAULT_USER); - String password = - Config.getStringXPath(XPATH_PASSWORD, DEFAULT_PASSWORD); - String dialect = - Config.getStringXPath(XPATH_DIALECT, DEFAULT_DIALECT); - String driver = - Config.getStringXPath(XPATH_DRIVER, DEFAULT_DRIVER); - String url = - Config.getStringXPath(XPATH_URL, DEFAULT_URL); - String connectionInitSqls = - Config.getStringXPath( - XPATH_CONNECTION_INIT_SQLS, - DEFAULT_CONNECTION_INIT_SQLS); - - instance = new SedDBCredentials( - user, password, dialect, driver, url, connectionInitSqls); - } - return instance; - } - - public static Credentials getDefault() { - return new SedDBCredentials( - DEFAULT_USER, - DEFAULT_PASSWORD, - DEFAULT_DIALECT, - DEFAULT_DRIVER, - DEFAULT_URL, - DEFAULT_CONNECTION_INIT_SQLS); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/SedDBSessionHolder.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ -package de.intevation.flys.backend; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; - -public class SedDBSessionHolder -{ - private static Logger log = - Logger.getLogger(SedDBSessionHolder.class); - - public static final ThreadLocal<Session> HOLDER = - new ThreadLocal<Session>() { - @Override - protected Session initialValue() { - return create(); - } - }; - - private SedDBSessionHolder() { - } - - public synchronized static Session create() { - log.debug("create"); - SessionFactory sessionFactory = - SessionFactoryProvider.getSedDBSessionFactory(); - return sessionFactory.openSession(); - } - - public static Session acquire() { - log.debug("acquire"); - Session session = create(); - HOLDER.set(session); - return session; - } - - public static void release() { - log.debug("release"); - HOLDER.remove(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/SessionFactoryProvider.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -package de.intevation.flys.backend; - -import java.util.Properties; - -import org.apache.log4j.Logger; - -import org.hibernate.SessionFactory; - -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; - -import org.hibernate.impl.SessionFactoryImpl; - -public final class SessionFactoryProvider -{ - private static Logger log = Logger.getLogger(SessionFactoryProvider.class); - - //public static final boolean ENABLE_JMX = - // Boolean.getBoolean("flys.backend.enablejmx"); - - private static SessionFactory flysSessionFactory; - private static SessionFactory sedDBSessionFactory; - - private SessionFactoryProvider() { - } - - public static synchronized SessionFactory getSessionFactory() { - if (flysSessionFactory == null) { - flysSessionFactory = - createSessionFactory(FLYSCredentials.getInstance()); - } - return flysSessionFactory; - } - - public static SessionFactory createSessionFactory() { - return createSessionFactory(FLYSCredentials.getDefault()); - } - - public static synchronized SessionFactory getSedDBSessionFactory() { - if (sedDBSessionFactory == null) { - sedDBSessionFactory = - createSessionFactory(SedDBCredentials.getInstance()); - } - return sedDBSessionFactory; - } - - public static SessionFactory createSedDBSessionFactory() { - return createSessionFactory(SedDBCredentials.getDefault()); - } - - public static SessionFactory createSessionFactory( - Credentials credentials - ) { - Configuration cfg = createConfiguration(credentials); - - SessionFactory factory = cfg.buildSessionFactory(); - - /* - if (ENABLE_JMX) { - registerAsMBean(factory); - } - else { - log.info("No JMX support for hibernate."); - } - */ - - return factory; - } - - /** XXX: Commented out till it is configured correctly. - public static void registerAsMBean(SessionFactory factory) { - - // - - StatisticsService statsMBean = new StatisticsService(); - statsMBean.setSessionFactory(factory); - statsMBean.setStatisticsEnabled(true); - - try { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - mbs.registerMBean( - statsMBean, - new ObjectName("Hibernate:application=Statistics")); - - log.info("Enabled JMX support for hibernate."); - } - catch (MalformedObjectNameException mone) { - log.warn(mone, mone); - } - catch (InstanceAlreadyExistsException iaee) { - log.warn(iaee, iaee); - } - catch (MBeanRegistrationException mbre) { - log.warn(mbre, mbre); - } - catch (NotCompliantMBeanException ncmbe) { - log.warn(ncmbe, ncmbe); - } - } - */ - - public static Configuration createConfiguration() { - return createConfiguration(FLYSCredentials.getInstance()); - } - - public static Configuration createConfiguration( - Credentials credentials - ) { - Configuration cfg = new Configuration(); - - for (Class<?> clazz: credentials.getClasses()) { - cfg.addAnnotatedClass(clazz); - } - - if (log.isDebugEnabled()) { - log.debug("user: " + credentials.getUser()); - log.debug("dialect: " + credentials.getDialect()); - log.debug("driver: " + credentials.getDriver()); - log.debug("url: " + credentials.getUrl()); - } - - Properties props = new Properties(); - - // We rely on our own connection pool - props.setProperty( - "hibernate.connection.provider_class", - "de.intevation.flys.utils.DBCPConnectionProvider"); - - props.setProperty(Environment.DIALECT, credentials.getDialect()); - props.setProperty(Environment.USER, credentials.getUser()); - props.setProperty(Environment.PASS, credentials.getPassword()); - props.setProperty(Environment.DRIVER, credentials.getDriver()); - props.setProperty(Environment.URL, credentials.getUrl()); - - String connectionInitSqls = credentials.getConnectionInitSqls(); - if (connectionInitSqls != null) { - props.setProperty("connectionInitSqls", connectionInitSqls); - } - - cfg.mergeProperties(props); - - return cfg; - } - - - public static String getProperty(SessionFactoryImpl factory, String key) { - Properties props = factory.getProperties(); - return props.getProperty(key); - } - - public static String getUser(SessionFactoryImpl factory) { - return getProperty(factory, Environment.USER); - } - - - public static String getPass(SessionFactoryImpl factory) { - return getProperty(factory, Environment.PASS); - } - - - public static String getURL(SessionFactoryImpl factory) { - return getProperty(factory, Environment.URL); - } - - - public static String getDriver(SessionFactoryImpl factory) { - return getProperty(factory, Environment.DRIVER); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/SessionHolder.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -package de.intevation.flys.backend; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; - - -public class SessionHolder -{ - private static Logger log = - Logger.getLogger(SessionHolder.class); - - public static final ThreadLocal<Session> HOLDER = - new ThreadLocal<Session>() { - @Override - protected Session initialValue() { - return create(); - } - }; - - private SessionHolder() { - } - - public synchronized static Session create() { - log.debug("create"); - SessionFactory sessionFactory = - SessionFactoryProvider.getSessionFactory(); - return sessionFactory.openSession(); - } - - public static Session acquire() { - log.debug("acquire"); - Session session = create(); - HOLDER.set(session); - return session; - } - - public static void release() { - log.debug("release"); - HOLDER.remove(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/backend/SpatialInfo.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,176 +0,0 @@ -package de.intevation.flys.backend; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; - -import de.intevation.flys.model.Building; -import de.intevation.flys.model.CrossSectionTrack; -import de.intevation.flys.model.Fixpoint; -import de.intevation.flys.model.River; -import de.intevation.flys.model.RiverAxis; -import de.intevation.flys.model.HWSLine; - - -public class SpatialInfo { - - private static Logger logger = Logger.getLogger(SpatialInfo.class); - - protected static String RIVERNAME = System.getProperty( - "flys.backend.spatial.river", "Saar"); - - protected Session session; - - - public static void main(String[] args) { - logger.info("Start SpatialInfo application."); - - SpatialInfo spatial = null; - - try { - spatial = new SpatialInfo(); - - River river = spatial.getRiver(RIVERNAME); - if (river == null) { - logger.warn("Could not find river '" + RIVERNAME + "'!"); - return; - } - - logger.info("Spatial information of River '" + RIVERNAME + "'"); - spatial.doRiverAxisInfo(river); - spatial.doCrossSectionTracksInfo(river); - spatial.doBuildingsInfo(river); - spatial.doFixpointsInfo(river); - } - finally { - if (spatial != null) { - spatial.close(); - } - } - - logger.info("Finish SpatialInfo application."); - } - - - public SpatialInfo() { - session = SessionFactoryProvider - .createSessionFactory() - .openSession(); - } - - - public void close() { - session.close(); - } - - - protected River getRiver(String rivername) { - Query query = session.createQuery( - "from River where name =:name"); - query.setParameter("name", rivername); - - List<River> list = query.list(); - - if (list == null || list.size() == 0) { - logger.warn("No river '" + rivername + "' found!"); - return null; - } - - return list.get(0); - } - - - protected void doRiverAxisInfo(River river) { - try { - List<RiverAxis> axis = RiverAxis.getRiverAxis(river.getName()); - if (axis != null && axis.size() > 0) { - logger.debug("TODO: Compute length and boundary."); - } - else { - logger.warn("River has no RiverAxis."); - } - } - catch(HibernateException iae) { - logger.warn("No vaild river axis found for " + river.getName()); - return; - } - - } - - - protected void doCrossSectionTracksInfo(River river) { - Query query = session.createQuery( - "from CrossSectionTrack where river =:river"); - query.setParameter("river", river); - - List<CrossSectionTrack> list = query.list(); - - if (list == null || list.size() == 0) { - logger.warn("No CrossSectionTracks for '" + river.getName() + "' found!"); - return; - } - else { - logger.info("River contains " + list.size() + " CrossSectionTracks."); - } - } - - - protected void doBuildingsInfo(River river) { - Query query = session.createQuery( - "from Building where river =:river"); - query.setParameter("river", river); - - List<Building> list = query.list(); - - if (list == null || list.size() == 0) { - logger.warn("No Buildings for '" + river.getName() + "' found!"); - return; - } - else { - logger.info("River contains " + list.size() + " Buildings."); - } - } - - - protected void doFixpointsInfo(River river) { - Query query = session.createQuery( - "from Fixpoint where river =:river"); - query.setParameter("river", river); - - List<Fixpoint> list = query.list(); - - if (list == null || list.size() == 0) { - logger.warn("No Fixpoints for '" + river.getName() + "' found!"); - return; - } - else { - logger.info("River contains " + list.size() + " Fixpoints."); - } - } - - @Deprecated - protected void doLinesInfo(River river) { - doHWSLinesInfo(river); - } - - protected void doHWSLinesInfo(River river) { - Query query = session.createQuery( - "from hws_lines where river =:river"); - query.setParameter("river", river); - - List<HWSLine> list = query.list(); - - if (list == null || list.size() == 0) { - logger.warn("No Lines for '" + river.getName() + "' found!"); - return; - } - else { - logger.info("River contains " + list.size() + " Lines."); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/Config.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,224 +0,0 @@ -package de.intevation.flys.importer; - -public class Config -{ - public static final String SKIP_DEFAULT = - "flys.backend.importer.skip.default"; - - public static final String DRY_RUN = - "flys.backend.importer.dry.run"; - - public static final String INFO_GEW_FILE = - "flys.backend.importer.infogew.file"; - - public static final String ANNOTATION_TYPES = - "flys.backend.importer.annotation.types"; - - public static final String SKIP_GAUGES = - "flys.backend.importer.skip.gauges"; - - public static final String SKIP_BWASTR = - "flys.backend.importer.skip.bwastr"; - - public static final String SKIP_HISTORICAL_DISCHARGE_TABLES = - "flys.backend.importer.skip.historical.discharge.tables"; - - public static final String SKIP_ANNOTATIONS = - "flys.backend.importer.skip.annotations"; - - public static final String SKIP_PRFS = - "flys.backend.importer.skip.prfs"; - - public static final String SKIP_DA50S = - "flys.backend.importer.skip.da50s"; - - public static final String SKIP_W80S = - "flys.backend.importer.skip.w80s"; - - public static final String SKIP_W80_CSVS = - "flys.backend.importer.skip.w80.csvs"; - - public static final String SKIP_HYKS = - "flys.backend.importer.skip.hyks"; - - public static final String SKIP_WST = - "flys.backend.importer.skip.wst"; - - public static final String SKIP_EXTRA_WSTS = - "flys.backend.importer.skip.extra.wsts"; - - public static final String SKIP_FIXATIONS = - "flys.backend.importer.skip.fixations"; - - public static final String SKIP_OFFICIAL_LINES = - "flys.backend.importer.skip.official.lines"; - - public static final String SKIP_FLOOD_WATER = - "flys.backend.importer.skip.flood.water"; - - public static final String SKIP_FLOOD_PROTECTION = - "flys.backend.importer.skip.flood.protection"; - - public static final String SKIP_BED_HEIGHT_SINGLE = - "flys.backend.importer.skip.bed.height.single"; - - public static final String SKIP_DA66S = - "flys.backend.importer.skip.da66s"; - - public static final String SKIP_BED_HEIGHT_EPOCH = - "flys.backend.importer.skip.bed.height.epoch"; - - public static final String SKIP_SEDIMENT_DENSITY = - "flys.backend.importer.skip.sediment.density"; - - public static final String SKIP_MORPHOLOGICAL_WIDTH = - "flys.backend.importer.skip.morphological.width"; - - public static final String SKIP_FLOW_VELOCITY = - "flys.backend.importer.skip.flow.velocity"; - - public static final String SKIP_SEDIMENT_YIELD = - "flys.backend.importer.skip.sediment.yield"; - - public static final String SKIP_WATERLEVELS = - "flys.backend.importer.skip.waterlevels"; - - public static final String SKIP_WATERLEVEL_DIFFERENCES = - "flys.backend.importer.skip.waterlevel.differences"; - - public static final String SKIP_MEASUREMENT_STATIONS = - "flys.backend.importer.skip.measurement.stations"; - - public static final String SKIP_SQ_RELATION = - "flys.backend.importer.skip.sq.relation"; - - - public static final Config INSTANCE = new Config(); - - private Config () { - } - - public static final boolean getFlag(String key) { - String flag = System.getProperty(key); - return flag != null - ? Boolean.valueOf(flag) - : Boolean.getBoolean(SKIP_DEFAULT); - } - - public boolean dryRun() { - return getFlag(DRY_RUN); - } - - public String getInfoGewFile() { - return System.getProperty(INFO_GEW_FILE); - } - - public String getAnnotationTypes() { - return System.getProperty(ANNOTATION_TYPES); - } - - public boolean skipGauges() { - return getFlag(SKIP_GAUGES); - } - - public boolean skipHistoricalDischargeTables() { - return getFlag(SKIP_HISTORICAL_DISCHARGE_TABLES); - } - - public boolean skipBWASTR() { - return getFlag(SKIP_BWASTR); - } - - public boolean skipAnnotations() { - return getFlag(SKIP_ANNOTATIONS); - } - - public boolean skipPRFs() { - return getFlag(SKIP_PRFS); - } - - public boolean skipDA50s() { - return getFlag(SKIP_DA50S); - } - - public boolean skipW80CSVs() { - return getFlag(SKIP_W80_CSVS); - } - - public boolean skipW80s() { - return getFlag(SKIP_W80S); - } - - public boolean skipHYKs() { - return getFlag(SKIP_HYKS); - } - - public boolean skipWst() { - return getFlag(SKIP_WST); - } - - public boolean skipExtraWsts() { - return getFlag(SKIP_EXTRA_WSTS); - } - - public boolean skipFixations() { - return getFlag(SKIP_FIXATIONS); - } - - public boolean skipOfficialLines() { - return getFlag(SKIP_OFFICIAL_LINES); - } - - public boolean skipFloodWater() { - return getFlag(SKIP_FLOOD_WATER); - } - - public boolean skipFloodProtection() { - return getFlag(SKIP_FLOOD_PROTECTION); - } - - public boolean skipDA66s() { - return getFlag(SKIP_DA66S); - } - - public boolean skipBedHeightSingle() { - return getFlag(SKIP_BED_HEIGHT_SINGLE); - } - - public boolean skipBedHeightEpoch() { - return getFlag(SKIP_BED_HEIGHT_EPOCH); - } - - public boolean skipSedimentDensity() { - return getFlag(SKIP_SEDIMENT_DENSITY); - } - - public boolean skipMorphologicalWidth() { - return getFlag(SKIP_MORPHOLOGICAL_WIDTH); - } - - public boolean skipFlowVelocity() { - return getFlag(SKIP_FLOW_VELOCITY); - } - - public boolean skipSedimentYield() { - return getFlag(SKIP_SEDIMENT_YIELD); - } - - public boolean skipWaterlevels() { - return getFlag(SKIP_WATERLEVELS); - } - - public boolean skipWaterlevelDifferences() { - return getFlag(SKIP_WATERLEVEL_DIFFERENCES); - } - - public boolean skipMeasurementStations() { - return getFlag(SKIP_MEASUREMENT_STATIONS); - } - - public boolean skipSQRelation() { - return getFlag(SKIP_SQ_RELATION); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportAnnotation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,146 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Annotation; -import de.intevation.flys.model.AnnotationType; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.Position; -import de.intevation.flys.model.Attribute; -import de.intevation.flys.model.River; -import de.intevation.flys.model.Edge; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportAnnotation -implements Comparable<ImportAnnotation> -{ - protected ImportAttribute attribute; - protected ImportPosition position; - protected ImportRange range; - protected ImportEdge edge; - protected ImportAnnotationType type; - - protected Annotation peer; - - public ImportAnnotation() { - } - - public ImportAnnotation( - ImportAttribute attribute, - ImportPosition position, - ImportRange range, - ImportEdge edge, - ImportAnnotationType type - ) { - this.attribute = attribute; - this.position = position; - this.range = range; - this.edge = edge; - this.type = type; - } - - public int compareTo(ImportAnnotation other) { - int d = attribute.compareTo(other.attribute); - if (d != 0) { - return d; - } - - if ((d = position.compareTo(other.position)) != 0) { - return d; - } - - if ((d = range.compareTo(other.range)) != 0) { - return d; - } - - if (edge == null && other.edge != null) return -1; - if (edge != null && other.edge == null) return +1; - if (edge == null && other.edge == null) return 0; - - if ((d = edge.compareTo(other.edge)) != 0) { - return d; - } - - if (type == null && other.type != null) return -1; - if (type != null && other.type == null) return +1; - if (type == null && other.type == null) return 0; - - return type.compareTo(other.type); - } - - public ImportAttribute getAttribute() { - return attribute; - } - - public void setAttribute(ImportAttribute attribute) { - this.attribute = attribute; - } - - public ImportPosition getPosition() { - return position; - } - - public void setPosition(ImportPosition position) { - this.position = position; - } - - public ImportRange getRange() { - return range; - } - - public void setRange(ImportRange range) { - this.range = range; - } - - public ImportEdge getEdge() { - return edge; - } - - public void setEdge(ImportEdge edge) { - this.edge = edge; - } - - public ImportAnnotationType getType() { - return type; - } - - public void setType(ImportAnnotationType type) { - this.type = type; - } - - public Annotation getPeer(River river) { - if (peer == null) { - Range r = range.getPeer(river); - Attribute a = attribute.getPeer(); - Position p = position.getPeer(); - Edge e = edge != null ? edge.getPeer() : null; - AnnotationType t = type != null ? type.getPeer() : null; - - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from Annotation where " + - "range=:range and " + - "attribute=:attribute and " + - "position=:position and " + - "edge=:edge and " + - "type=:type"); - query.setParameter("range", r); - query.setParameter("attribute", a); - query.setParameter("position", p); - query.setParameter("edge", e); - query.setParameter("type", t); - List<Annotation> annotations = query.list(); - if (annotations.isEmpty()) { - peer = new Annotation(r, a, p, e, t); - session.save(peer); - } - else { - peer = annotations.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportAnnotationType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.AnnotationType; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportAnnotationType -implements Comparable<ImportAnnotationType> -{ - protected String name; - protected AnnotationType peer; - - public ImportAnnotationType() { - } - - public ImportAnnotationType(String name) { - this.name = name; - } - - public int compareTo(ImportAnnotationType other) { - return name.compareTo(other.name); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public AnnotationType getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from AnnotationType where name=:name"); - query.setParameter("name", name); - List<AnnotationType> types = query.list(); - if (types.isEmpty()) { - peer = new AnnotationType(name); - session.save(peer); - } - else { - peer = types.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportAttribute.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Attribute; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportAttribute -implements Comparable<ImportAttribute> -{ - protected String value; - - protected Attribute peer; - - public ImportAttribute() { - } - - public ImportAttribute(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public int compareTo(ImportAttribute other) { - return value.compareTo(other.value); - } - - @Override - public boolean equals(Object other) { - if (other == this) return true; - if (!(other instanceof ImportAttribute)) return false; - return value.equals(((ImportAttribute)other).value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - public Attribute getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from Attribute where value=:value"); - query.setString("value", value); - List<Attribute> attributes = query.list(); - if (attributes.isEmpty()) { - peer = new Attribute(value); - session.save(peer); - } - else { - peer = attributes.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeight.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -package de.intevation.flys.importer; - - -import java.sql.SQLException; - -import org.hibernate.exception.ConstraintViolationException; - -import de.intevation.flys.model.River; - - -public interface ImportBedHeight { - - String getDescription(); - - void addValue(ImportBedHeightValue value); - - void storeDependencies(River river) - throws SQLException, ConstraintViolationException; - - Object getPeer(River river); - - int getValueCount(); - - void setYear(int year); - - void setTimeInterval(ImportTimeInterval timeInterval); - - void setSoundingWidth(int soundingWidth); - - void setDescription(String description); - - void setEvaluationBy(String evaluationBy); - - void setRange(ImportRange range); - - void setType(ImportBedHeightType type); - - void setLocationSystem(ImportLocationSystem locationSystem); - - void setCurElevationModel(ImportElevationModel model); - - void setOldElevationModel(ImportElevationModel model); -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightEpoch.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,198 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.hibernate.Query; -import org.hibernate.Session; - -import de.intevation.flys.model.BedHeightEpoch; -import de.intevation.flys.model.ElevationModel; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; -import de.intevation.flys.model.TimeInterval; - - -/** Import Bed Height Data, 'epoch' type from csv file. */ -public class ImportBedHeightEpoch implements ImportBedHeight { - - /** Private logger. */ - private static Logger log = Logger.getLogger(ImportBedHeightEpoch.class); - - protected String evaluationBy; - - /** De facto the file name. */ - protected String description; - - protected ImportTimeInterval timeInterval; - protected ImportRange range; - protected ImportElevationModel curElevationModel; - protected ImportElevationModel oldElevationModel; - - protected List<ImportBedHeightEpochValue> values; - - protected BedHeightEpoch peer; - - public ImportBedHeightEpoch(String description) { - this.description = description; - this.values = new ArrayList<ImportBedHeightEpochValue>(); - } - - public String getDescription() { - return description; - } - - public int getValueCount() { - return values.size(); - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - public void setEvaluationBy(String evaluationBy) { - this.evaluationBy = evaluationBy; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setRange(ImportRange range) { - this.range = range; - } - - public void setCurElevationModel(ImportElevationModel curElevationModel) { - this.curElevationModel = curElevationModel; - } - - public void setOldElevationModel(ImportElevationModel oldElevationModel) { - this.oldElevationModel = oldElevationModel; - } - - /** Does nothing. */ - public void setYear(int year) { - // do nothing - } - - /** Does nothing. */ - public void setSoundingWidth(int soundingWidth) { - // do nothing - } - - - /** Does nothing. */ - public void setLocationSystem(ImportLocationSystem locationSystem) { - // do nothing - } - - - /** Does nothing. */ - public void setType(ImportBedHeightType type) { - // do nothing - } - - @Override - public void addValue(ImportBedHeightValue value) { - values.add((ImportBedHeightEpochValue) value); - } - - @Override - public void storeDependencies(River river) { - log.info("Store dependencies for epoch: '" + getDescription() + "'"); - - BedHeightEpoch peer = getPeer(river); - - if (curElevationModel != null) { - curElevationModel.storeDependencies(); - } - - if (oldElevationModel != null) { - oldElevationModel.storeDependencies(); - } - - if (peer != null) { - log.debug("store values now..."); - - for (ImportBedHeightEpochValue value : values) { - value.storeDependencies(peer); - } - } - - Session session = ImporterSession.getInstance().getDatabaseSession(); - session.flush(); - } - - /** - * Asserts all dependent entities (ElevationModel, TimeInterval, Range, - * BedHeighEpoch) are in db and returns bound (either newly created or - * freshly fetched) BedHeightEpoch. - */ - @Override - public BedHeightEpoch getPeer(River river) { - if (peer == null) { - ElevationModel theCurModel = null; - if (curElevationModel != null) { - curElevationModel.storeDependencies(); - theCurModel = curElevationModel.getPeer(); - } - - if (theCurModel == null) { - log.warn("BHE: Skip file - invalid current elevation model."); - return null; - } - - TimeInterval theTime = null; - if (timeInterval != null) { - theTime = timeInterval.getPeer(); - } - - if (theTime == null) { - log.warn("BHE: Skip file - invalid time range."); - return null; - } - - Range theRange = range != null ? range.getPeer(river) : null; - - if (theRange == null) { - log.warn("BHE: invalid km range."); - } - - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - Query query = session.createQuery("from BedHeightEpoch where " - + " river=:river and " + " timeInterval=:timeInterval and " - + " curElevationModel=:curElevationModel and " - + " range=:range and " + " evaluationBy=:evaluationBy and " - + " description=:description"); - - query.setParameter("river", river); - query.setParameter("timeInterval", theTime); - query.setParameter("curElevationModel", theCurModel); - query.setParameter("range", theRange); - query.setParameter("evaluationBy", evaluationBy); - query.setParameter("description", description); - - List<BedHeightEpoch> bedHeights = query.list(); - - if (bedHeights.isEmpty()) { - log.info("Create new BedHeightEpoch DB instance."); - - peer = new BedHeightEpoch(river, theTime, theRange, - theCurModel, - oldElevationModel != null ? oldElevationModel.getPeer() - : null, evaluationBy, description); - - session.save(peer); - } - else { - peer = bedHeights.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightEpochValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,75 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.BedHeightEpoch; -import de.intevation.flys.model.BedHeightEpochValue; - - -public class ImportBedHeightEpochValue implements ImportBedHeightValue { - - private static final Logger log = - Logger.getLogger(ImportBedHeightEpochValue.class); - - - private BigDecimal station; - private BigDecimal height; - - private BedHeightEpochValue peer; - - - public ImportBedHeightEpochValue() { - } - - - public ImportBedHeightEpochValue(BigDecimal station, BigDecimal height) { - this.station = station; - this.height = height; - } - - - public void storeDependencies(BedHeightEpoch bedHeight) { - getPeer(bedHeight); - } - - - public BedHeightEpochValue getPeer(BedHeightEpoch bedHeight) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from BedHeightEpochValue where " + - " bedHeight=:bedHeight and " + - " station=:station and " + - " height=:height"); - - query.setParameter("bedHeight", bedHeight); - query.setParameter("station", station); - query.setParameter("height", height); - - List<BedHeightEpochValue> values = query.list(); - - if (values.isEmpty()) { - peer = new BedHeightEpochValue( - bedHeight, - station, - height - ); - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightSingle.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,198 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.BedHeightSingle; -import de.intevation.flys.model.BedHeightType; -import de.intevation.flys.model.ElevationModel; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; - - -public class ImportBedHeightSingle implements ImportBedHeight -{ - private static Logger log = Logger.getLogger(ImportBedHeightSingle.class); - - protected Integer year; - protected int soundingWidth; - - protected String evaluationBy; - protected String description; - - protected ImportRange range; - protected ImportBedHeightType type; - protected ImportLocationSystem locationSystem; - protected ImportElevationModel curElevationModel; - protected ImportElevationModel oldElevationModel; - - protected List<ImportBedHeightSingleValue> values; - - protected BedHeightSingle peer; - - - public ImportBedHeightSingle(String description) { - this.description = description; - this.values = new ArrayList<ImportBedHeightSingleValue>(); - } - - - public String getDescription() { - return description; - } - - public int getValueCount() { - return values.size(); - } - - - public void setYear(int year) { - this.year = year; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - // do nothing - } - - public void setSoundingWidth(int soundingWidth) { - this.soundingWidth = soundingWidth; - } - - public void setEvaluationBy(String evaluationBy) { - this.evaluationBy = evaluationBy; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setRange(ImportRange range) { - this.range = range; - } - - public void setType(ImportBedHeightType type) { - this.type = type; - } - - public void setLocationSystem(ImportLocationSystem locationSystem) { - this.locationSystem = locationSystem; - } - - public void setCurElevationModel(ImportElevationModel curElevationModel) { - this.curElevationModel = curElevationModel; - } - - public void setOldElevationModel(ImportElevationModel oldElevationModel) { - this.oldElevationModel = oldElevationModel; - } - - @Override - public void addValue(ImportBedHeightValue value) { - values.add((ImportBedHeightSingleValue) value); - } - - @Override - public void storeDependencies(River river) { - log.info("Store dependencies for single: '" + getDescription() + "'"); - - if (type != null) { - type.storeDependencies(); - } - - if (locationSystem != null) { - locationSystem.storeDependencies(); - } - - if (curElevationModel != null) { - curElevationModel.storeDependencies(); - } - - if (oldElevationModel != null) { - oldElevationModel.storeDependencies(); - } - - BedHeightSingle peer = getPeer(river); - - if (peer != null) { - for (ImportBedHeightSingleValue value: values) { - value.storeDependencies(peer); - } - } - - Session session = ImporterSession.getInstance().getDatabaseSession(); - session.flush(); - } - - @Override - public BedHeightSingle getPeer(River river) { - if (peer == null) { - BedHeightType theType = type != null ? type.getPeer() : null; - ElevationModel theCurModel = curElevationModel.getPeer(); - Range theRange = range != null ? range.getPeer(river) : null; - - if (theType == null) { - log.warn("BHS: No bed height type given. Skip file '" + - description + "'"); - return null; - } - - if (theCurModel == null) { - log.warn("BHS: No elevation model given. Skip file '" + - description + "'"); - return null; - } - - if (theRange == null) { - log.warn("BHS: No km-range given: '" + - description + "'"); - } - - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from BedHeightSingle where " + - "river=:river and year=:year and soundingWidth=:soundingWidth " + - "and type=:type and locationSystem=:locationSystem and " + - "curElevationModel=:curElevationModel and range=:range"); - - query.setParameter("river", river); - query.setParameter("year", year); - query.setParameter("soundingWidth", soundingWidth); - query.setParameter("type", theType); - query.setParameter("locationSystem", locationSystem.getPeer()); - query.setParameter("curElevationModel", theCurModel); - query.setParameter("range", range.getPeer(river)); - - List<BedHeightSingle> bedHeights = query.list(); - if (bedHeights.isEmpty()) { - log.info("Create new BedHeightSingle DB instance."); - - peer = new BedHeightSingle( - river, - year, - soundingWidth, - theType, - locationSystem.getPeer(), - theCurModel, - oldElevationModel != null ? oldElevationModel.getPeer() : null, - range.getPeer(river), - evaluationBy, - description - ); - - session.save(peer); - } - else { - peer = bedHeights.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightSingleValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,105 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.BedHeightSingle; -import de.intevation.flys.model.BedHeightSingleValue; - - -public class ImportBedHeightSingleValue implements ImportBedHeightValue { - - private static final Logger log = - Logger.getLogger(ImportBedHeightSingleValue.class); - - - protected ImportBedHeightSingle bedHeight; - - protected BigDecimal station; - protected BigDecimal height; - protected BigDecimal uncertainty; - protected BigDecimal dataGap; - protected BigDecimal soundingWidth; - protected BigDecimal width; - - protected BedHeightSingleValue peer; - - - public ImportBedHeightSingleValue( - ImportBedHeightSingle bedHeight, - BigDecimal station, - BigDecimal height, - BigDecimal uncertainty, - BigDecimal dataGap, - BigDecimal soundingWidth, - BigDecimal width - ) { - this.bedHeight = bedHeight; - this.station = station; - this.height = height; - this.uncertainty = uncertainty; - this.dataGap = dataGap; - this.soundingWidth = soundingWidth; - this.width = width; - } - - - public void storeDependencies(BedHeightSingle bedHeight) { - getPeer(bedHeight); - } - - - /** - * Add this value to database or return database bound Value, assuring - * that the BedHeightSingle exists in db already. - */ - public BedHeightSingleValue getPeer(BedHeightSingle bedHeight) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from BedHeightSingleValue where " + - " bedHeight=:bedHeight and " + - " station=:station and " + - " height=:height and " + - " uncertainty=:uncertainty and " + - " dataGap=:dataGap and " + - " soundingWidth=:soundingWidth and " + - " width=:width"); - - query.setParameter("bedHeight", bedHeight); - query.setParameter("station", station); - query.setParameter("height", height); - query.setParameter("uncertainty", uncertainty); - query.setParameter("dataGap", dataGap); - query.setParameter("soundingWidth", soundingWidth); - query.setParameter("width", width); - - List<BedHeightSingleValue> values = query.list(); - if (values.isEmpty()) { - peer = new BedHeightSingleValue( - bedHeight, - station, - height, - uncertainty, - dataGap, - soundingWidth, - width - ); - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,61 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.BedHeightType; - - -public class ImportBedHeightType { - - private static final Logger log = - Logger.getLogger(ImportBedHeightType.class); - - protected String name; - - protected BedHeightType peer; - - public ImportBedHeightType(BedHeightType peer) { - this.peer = peer; - name = peer.getName(); - } - - - public ImportBedHeightType(String name) { - this.name = name; - } - - - public void storeDependencies() { - getPeer(); - } - - - public BedHeightType getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from BedHeightType where name=:name and description=:description"); - - query.setParameter("name", name); - - List<BedHeightType> types = query.list(); - - if (types.isEmpty()) { - peer = new BedHeightType(name); - session.save(peer); - } - else { - peer = types.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportBedHeightValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,7 +0,0 @@ -package de.intevation.flys.importer; - - -public interface ImportBedHeightValue { - -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportCrossSection.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.River; -import de.intevation.flys.model.CrossSection; -import de.intevation.flys.model.TimeInterval; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -import org.apache.log4j.Logger; - -/** CrossSection to be imported, holds list of ImportCrossSectionLines. */ -public class ImportCrossSection -{ - private static Logger log = Logger.getLogger(ImportRiver.class); - - protected ImportRiver river; - protected String description; - protected ImportTimeInterval timeInterval; - protected List<ImportCrossSectionLine> lines; - - protected CrossSection peer; - - public ImportCrossSection() { - } - - public ImportCrossSection( - ImportRiver river, - String description, - ImportTimeInterval timeInterval, - List<ImportCrossSectionLine> lines - ) { - this.river = river; - this.description = description; - this.timeInterval = timeInterval; - this.lines = lines; - wireWithLines(); - } - - public void wireWithLines() { - for (ImportCrossSectionLine line: lines) { - line.setCrossSection(this); - } - } - - public ImportRiver getRiver() { - return river; - } - - public void setRiver(ImportRiver river) { - this.river = river; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ImportTimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - public void storeDependencies() { - - log.info("store cross section '" + description + "'"); - - getPeer(); - - int i = 1, N = lines.size(); - - for (ImportCrossSectionLine line: lines) { - line.storeDependencies(); - log.info(" stored " + i + " lines. remaining: " + (N-i)); - ++i; - } - } - - public CrossSection getPeer() { - - if (peer == null) { - River r = river.getPeer(); - TimeInterval t = timeInterval != null - ? timeInterval.getPeer() - : null; - - Session session = - ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from CrossSection where " + - "river=:r and " + - "timeInterval=:t and " + - "description=:d"); - - query.setParameter("r", r); - query.setParameter("t", t); - query.setParameter("d", description); - - List<CrossSection> crossSections = query.list(); - if (crossSections.isEmpty()) { - peer = new CrossSection(r, t, description); - session.save(peer); - } - else { - peer = crossSections.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportCrossSectionLine.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,127 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.CrossSection; -import de.intevation.flys.model.CrossSectionPoint; -import de.intevation.flys.model.CrossSectionLine; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; -import java.util.Comparator; -import java.util.Map; -import java.util.TreeMap; - -/** - * A CrossSectionLine (containing points) ready to be transformed into a mapped - * object and written to db (used in importer). - */ -public class ImportCrossSectionLine -{ - public static final Comparator<CrossSectionPoint> INDEX_CMP = - new Comparator<CrossSectionPoint>() { - public int compare(CrossSectionPoint a, CrossSectionPoint b) { - return a.getColPos().compareTo(b.getColPos()); - } - }; - - protected Double km; - protected ImportCrossSection crossSection; - protected List<XY> points; - - protected CrossSectionLine peer; - - public ImportCrossSectionLine() { - } - - public ImportCrossSectionLine(Double km, List<XY> points) { - this.km = km; - this.points = points; - } - - public ImportCrossSection getCrossSection() { - return crossSection; - } - - public void setCrossSection(ImportCrossSection crossSection) { - this.crossSection = crossSection; - } - - public Double getKm() { - return km; - } - - public void setKm(Double km) { - this.km = km; - } - - public void storeDependencies() { - storePoints(); - } - - - /** Write a line and its points. */ - protected void storePoints() { - CrossSectionLine csl = getPeer(); - - Map<CrossSectionPoint, CrossSectionPoint> map = - new TreeMap<CrossSectionPoint, CrossSectionPoint>(INDEX_CMP); - - // Build index for faster (index) collision lookup. - List<CrossSectionPoint> ps = csl.getPoints(); - if (ps != null) { - for (CrossSectionPoint point: ps) { - map.put(point, point); - } - } - - Session session = - ImporterSession.getInstance().getDatabaseSession(); - - CrossSectionPoint key = new CrossSectionPoint(); - - // Somehow it looks as if even with the map it is still possible that - // multiple points with same id enter hibernate (and then violate a - // constraint). -> TODO - for (XY xy: points) { - key.setColPos(xy.getIndex()); - CrossSectionPoint csp = map.get(key); - if (csp == null) { // create new - csp = new CrossSectionPoint( - csl, key.getColPos(), - Double.valueOf(xy.getX()), - Double.valueOf(xy.getY())); - } - else { // update old - csp.setX(Double.valueOf(xy.getX())); - csp.setY(Double.valueOf(xy.getY())); - } - session.save(csp); - } - } - - public CrossSectionLine getPeer() { - if (peer == null) { - CrossSection cs = crossSection.getPeer(); - - Session session = - ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from CrossSectionLine where crossSection=:cs and km=:km"); - query.setParameter("cs", cs); - query.setParameter("km", km); - - List<CrossSectionLine> lines = query.list(); - if (lines.isEmpty()) { - peer = new CrossSectionLine(cs, km); - session.save(peer); - } - else { - peer = lines.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportDepth.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,70 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.Depth; - - -public class ImportDepth { - - private static Logger log = Logger.getLogger(ImportDepth.class); - - - protected Depth peer; - - protected BigDecimal lower; - protected BigDecimal upper; - - - public ImportDepth(BigDecimal lower, BigDecimal upper) { - this.lower = lower; - this.upper = upper; - } - - - public void storeDependencies() { - log.info("store dependencies"); - - getPeer(); - } - - - public Depth getPeer() { - log.info("get peer"); - - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from Depth where " + - " lower=:lower and " + - " upper=:upper"); - - query.setParameter("lower", lower); - query.setParameter("upper", upper); - - List<Depth> depths = query.list(); - - if (depths.isEmpty()) { - log.debug("Create new Depth DB instance."); - - peer = new Depth(lower, upper); - - session.save(peer); - } - else { - peer = depths.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportDischargeTable.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,116 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.DischargeTable; -import de.intevation.flys.model.Gauge; -import de.intevation.flys.model.TimeInterval; - -import org.apache.log4j.Logger; - -public class ImportDischargeTable -{ - private static Logger log = Logger.getLogger(ImportDischargeTable.class); - - protected DischargeTable peer; - - protected String description; - - protected Integer kind; - - protected List<ImportDischargeTableValue> dischargeTableValues; - - protected ImportTimeInterval timeInterval; - - public ImportDischargeTable() { - this(0, null); - } - - public ImportDischargeTable(int kind, String description) { - this.kind = kind; - this.description = description; - dischargeTableValues = new ArrayList<ImportDischargeTableValue>(); - } - - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - public void addDischargeTableValue(ImportDischargeTableValue value) { - dischargeTableValues.add(value); - } - - - public void setDischargeTableValues(List<ImportDischargeTableValue> values){ - this.dischargeTableValues = values; - } - - - public List<ImportDischargeTableValue> getDischargeTableValues() { - return dischargeTableValues; - } - - public ImportTimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - - public DischargeTable getPeer(Gauge gauge) { - if (peer == null) { - TimeInterval ti = timeInterval != null - ? timeInterval.getPeer() - : null; - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from DischargeTable where " + - "gauge.id=:gauge and kind=:kind and " + - "description=:description and timeInterval=:interval"); - query.setParameter("gauge", gauge.getId()); - query.setParameter("description", description); - query.setParameter("kind", kind); - query.setParameter("interval", ti); - - List<DischargeTable> dischargeTables = query.list(); - if (dischargeTables.isEmpty()) { - peer = new DischargeTable(gauge, description, null, kind, ti); - session.save(peer); - } - else { - peer = dischargeTables.get(0); - } - } - - return peer; - } - - - public void storeDependencies(Gauge gauge) { - log.info("store discharge table '" + description + "'"); - storeDischargeTableValues(gauge); - } - - - public void storeDischargeTableValues(Gauge gauge) { - DischargeTable dischargeTable = getPeer(gauge); - - for (ImportDischargeTableValue value: dischargeTableValues) { - value.getPeer(dischargeTable); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportDischargeTableValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,34 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import de.intevation.flys.model.DischargeTable; -import de.intevation.flys.model.DischargeTableValue; - - -public class ImportDischargeTableValue -{ - private BigDecimal q; - private BigDecimal w; - - private DischargeTableValue peer; - - public ImportDischargeTableValue() { - } - - - public ImportDischargeTableValue(BigDecimal q, BigDecimal w) { - this.q = q; - this.w = w; - } - - - public DischargeTableValue getPeer(DischargeTable dischargeTable) { - if (peer == null) { - peer = ImporterSession.getInstance() - .getDischargeTableValue(dischargeTable, q, w); - } - - return peer; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportDischargeZone.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,86 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.DischargeZone; -import de.intevation.flys.model.River; - - -public class ImportDischargeZone { - - private static final Logger log = - Logger.getLogger(ImportDischargeZone.class); - - - private String gaugeName; - - private BigDecimal value; - - private String lowerDischarge; - private String upperDischarge; - - private DischargeZone peer; - - - public ImportDischargeZone( - String gaugeName, - BigDecimal value, - String lowerDischarge, - String upperDischarge - ) { - this.gaugeName = gaugeName; - this.value = value; - this.lowerDischarge = lowerDischarge; - this.upperDischarge = upperDischarge; - } - - - public void storeDependencies(River river) { - log.debug("store dependencies"); - - getPeer(river); - } - - - public DischargeZone getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from DischargeZone where " + - " river=:river and " + - " gaugeName=:gaugeName and " + - " value=:value" - ); - - query.setParameter("river", river); - query.setParameter("gaugeName", gaugeName); - query.setParameter("value", value); - - List<DischargeZone> zone = query.list(); - - if (zone.isEmpty()) { - peer = new DischargeZone( - river, - gaugeName, - value, - lowerDischarge, - upperDischarge); - - session.save(peer); - } - else { - peer = zone.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportEdge.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,75 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Edge; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -import java.math.BigDecimal; - -public class ImportEdge -implements Comparable<ImportEdge> -{ - protected BigDecimal top; - protected BigDecimal bottom; - - protected Edge peer; - - public ImportEdge() { - } - - public ImportEdge(BigDecimal top, BigDecimal bottom) { - this.top = top; - this.bottom = bottom; - } - - public BigDecimal getTop() { - return top; - } - - public void setTop(BigDecimal top) { - this.top = top; - } - - public BigDecimal getBottom() { - return bottom; - } - - public void setBottom(BigDecimal bottom) { - this.bottom = bottom; - } - - private static final int compare(BigDecimal a, BigDecimal b) { - if (a == null && b != null) return -1; - if (a != null && b == null) return +1; - if (a == null && b == null) return 0; - return a.compareTo(b); - } - - public int compareTo(ImportEdge other) { - int cmp = compare(top, other.top); - return cmp != 0 ? cmp : compare(bottom, other.bottom); - } - - public Edge getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from Edge where top=:top and bottom=:bottom"); - query.setParameter("top", top); - query.setParameter("bottom", bottom); - List<Edge> edges = query.list(); - if (edges.isEmpty()) { - peer = new Edge(top, bottom); - session.save(peer); - } - else { - peer = edges.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportElevationModel.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,64 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.ElevationModel; - - -public class ImportElevationModel { - - private static final Logger log = - Logger.getLogger(ImportElevationModel.class); - - protected String name; - - protected ImportUnit unit; - - protected ElevationModel peer; - - - public ImportElevationModel(String name, ImportUnit unit) { - this.name = name; - this.unit = unit; - } - - - public void storeDependencies() { - ElevationModel model = getPeer(); - } - - public ElevationModel getPeer() { - if (unit == null) { - log.warn("No elevation model specified."); - return null; - } - - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from ElevationModel where " + - "name=:name and unit=:unit"); - query.setParameter("name", name); - query.setParameter("unit", unit.getPeer()); - List<ElevationModel> models = query.list(); - - if (models.isEmpty()) { - log.info("Create new ElevationModel DB instance."); - - peer = new ElevationModel(name, unit.getPeer()); - session.save(peer); - } - else { - peer = models.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportFlowVelocityMeasurement.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,82 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.FlowVelocityMeasurement; -import de.intevation.flys.model.River; - - -public class ImportFlowVelocityMeasurement { - - private static final Logger log = Logger - .getLogger(ImportFlowVelocityMeasurement.class); - - private String description; - - private List<ImportFlowVelocityMeasurementValue> values; - - private FlowVelocityMeasurement peer; - - public ImportFlowVelocityMeasurement() { - this(null); - } - - public ImportFlowVelocityMeasurement(String description) { - this.description = description; - this.values = new ArrayList<ImportFlowVelocityMeasurementValue>(); - } - - public void setDescription(String description) { - this.description = description; - } - - public void addValue(ImportFlowVelocityMeasurementValue value) { - this.values.add(value); - } - - public void storeDependencies(River river) { - log.debug("store dependencies"); - - FlowVelocityMeasurement peer = getPeer(river); - - if (peer != null) { - for (ImportFlowVelocityMeasurementValue value : values) { - value.storeDependencies(peer); - } - } - } - - public FlowVelocityMeasurement getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - Query query = session - .createQuery("from FlowVelocityMeasurement where " - + " river=:river and " + " description=:description"); - - query.setParameter("river", river); - query.setParameter("description", description); - - List<FlowVelocityMeasurement> measurement = query.list(); - - if (measurement.isEmpty()) { - peer = new FlowVelocityMeasurement(river, description); - - session.save(peer); - } - else { - peer = measurement.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportFlowVelocityMeasurementValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,97 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.Date; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.FlowVelocityMeasurement; -import de.intevation.flys.model.FlowVelocityMeasurementValue; - - -public class ImportFlowVelocityMeasurementValue { - - private static final Logger log = - Logger.getLogger(ImportFlowVelocityMeasurementValue.class); - - - private Date datetime; - - private String description; - - private BigDecimal station; - private BigDecimal w; - private BigDecimal q; - private BigDecimal v; - - private FlowVelocityMeasurementValue peer; - - - public ImportFlowVelocityMeasurementValue( - Date datetime, - BigDecimal station, - BigDecimal w, - BigDecimal q, - BigDecimal v, - String description - ) { - this.datetime = datetime; - this.station = station; - this.w = w; - this.q = q; - this.v = v; - this.description = description; - } - - - - public void storeDependencies(FlowVelocityMeasurement measurement) { - log.debug("store dependencies"); - - getPeer(measurement); - } - - - public FlowVelocityMeasurementValue getPeer(FlowVelocityMeasurement m) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from FlowVelocityMeasurementValue where " + - " measurement=:measurement and " + - " station=:station and " + - " datetime=:datetime" - ); - - query.setParameter("measurement", m); - query.setParameter("station", station); - query.setParameter("datetime", datetime); - - List<FlowVelocityMeasurementValue> values = query.list(); - - if (values.isEmpty()) { - peer = new FlowVelocityMeasurementValue( - m, - datetime, - station, - w, - q, - v, - description); - - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportFlowVelocityModel.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,109 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.DischargeZone; -import de.intevation.flys.model.FlowVelocityModel; -import de.intevation.flys.model.River; - - -public class ImportFlowVelocityModel { - - private static final Logger log = Logger - .getLogger(ImportFlowVelocityModel.class); - - private String description; - - private ImportDischargeZone dischargeZone; - - private List<ImportFlowVelocityModelValue> values; - - private FlowVelocityModel peer; - - public ImportFlowVelocityModel() { - values = new ArrayList<ImportFlowVelocityModelValue>(); - } - - public ImportFlowVelocityModel(String description) { - this(); - - this.description = description; - } - - public ImportFlowVelocityModel(ImportDischargeZone dischargeZone, - String description) { - this(); - - this.dischargeZone = dischargeZone; - this.description = description; - } - - public void setDischargeZone(ImportDischargeZone dischargeZone) { - this.dischargeZone = dischargeZone; - } - - public void setDescription(String description) { - this.description = description; - } - - public void addValue(ImportFlowVelocityModelValue value) { - this.values.add(value); - } - - public void storeDependencies(River river) { - log.debug("store dependencies"); - - if (dischargeZone == null) { - log.warn("skip flow velocity model: No discharge zone specified."); - return; - } - - dischargeZone.storeDependencies(river); - - FlowVelocityModel peer = getPeer(river); - - if (peer != null) { - int i = 0; - - for (ImportFlowVelocityModelValue value : values) { - value.storeDependencies(peer); - i++; - } - - log.info("stored " + i + " flow velocity model values."); - } - } - - public FlowVelocityModel getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - DischargeZone zone = dischargeZone.getPeer(river); - - Query query = session.createQuery("from FlowVelocityModel where " - + " dischargeZone=:dischargeZone"); - - query.setParameter("dischargeZone", zone); - - List<FlowVelocityModel> model = query.list(); - - if (model.isEmpty()) { - peer = new FlowVelocityModel(zone, description); - session.save(peer); - } - else { - peer = model.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportFlowVelocityModelValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,74 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.FlowVelocityModel; -import de.intevation.flys.model.FlowVelocityModelValue; - - -public class ImportFlowVelocityModelValue { - - private BigDecimal station; - private BigDecimal q; - private BigDecimal totalChannel; - private BigDecimal mainChannel; - private BigDecimal shearStress; - - private FlowVelocityModelValue peer; - - - public ImportFlowVelocityModelValue( - BigDecimal station, - BigDecimal q, - BigDecimal totalChannel, - BigDecimal mainChannel, - BigDecimal shearStress - ) { - this.station = station; - this.q = q; - this.totalChannel = totalChannel; - this.mainChannel = mainChannel; - this.shearStress = shearStress; - } - - - public void storeDependencies(FlowVelocityModel model) { - getPeer(model); - } - - - public FlowVelocityModelValue getPeer(FlowVelocityModel model) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from FlowVelocityModelValue where " + - " flowVelocity=:model and " + - " station between :station - 0.00001 and :station + 0.00001" - ); - - query.setParameter("model", model); - query.setParameter("station", station.doubleValue()); - - List<FlowVelocityModelValue> values = query.list(); - - if (values.isEmpty()) { - peer = new FlowVelocityModelValue( - model, station, q, totalChannel, mainChannel, shearStress); - - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportGauge.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,274 +0,0 @@ -package de.intevation.flys.importer; - -import java.io.File; - -import java.util.ArrayList; -import java.util.List; - -import java.math.BigDecimal; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.model.River; -import de.intevation.flys.model.Gauge; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.io.IOException; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.parsers.AtFileParser; -import de.intevation.flys.importer.parsers.StaFileParser; - -/** Gauge not in DB. */ -public class ImportGauge -{ - private static Logger log = Logger.getLogger(ImportGauge.class); - - public static final String HISTORICAL_DISCHARGE_TABLES = - "Histor.Abflusstafeln"; - - protected ImportRange range; - - protected File staFile; - protected File atFile; - - protected String name; - protected BigDecimal aeo; - protected BigDecimal datum; - protected BigDecimal station; - protected Long officialNumber; - - protected Gauge peer; - - protected ImportDischargeTable dischargeTable; - - protected List<ImportMainValueType> mainValueTypes; - protected List<ImportNamedMainValue> namedMainValues; - protected List<ImportMainValue> mainValues; - protected List<ImportDischargeTable> historicalDischargeTables; - - public ImportGauge() { - historicalDischargeTables = new ArrayList<ImportDischargeTable>(); - } - - public ImportGauge(ImportRange range, File staFile, File atFile) { - this(); - this.range = range; - this.staFile = staFile; - this.atFile = atFile; - } - - public void setRange(ImportRange range) { - this.range = range; - } - - public void setStaFile(File staFile) { - this.staFile = staFile; - } - - public File getStaFile() { - return staFile; - } - - public void setAtFile(File atFile) { - this.atFile = atFile; - } - - public File getAtFile() { - return atFile; - } - - public BigDecimal getAeo() { - return aeo; - } - - public void setAeo(BigDecimal aeo) { - this.aeo = aeo; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public BigDecimal getDatum() { - return datum; - } - - public void setDatum(BigDecimal datum) { - this.datum = datum; - } - - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - public Long getOfficialNumber() { - return officialNumber; - } - - public void setOfficialNumber(Long officialNumber) { - this.officialNumber = officialNumber; - } - - public ImportDischargeTable getDischargeTable() { - return dischargeTable; - } - - public void setDischargeTable(ImportDischargeTable dischargeTable) { - this.dischargeTable = dischargeTable; - } - - public List<ImportMainValueType> getMainValueTypes() { - return mainValueTypes; - } - - public void setMainValueTypes(List<ImportMainValueType> mainValueTypes) { - this.mainValueTypes = mainValueTypes; - } - - public List<ImportNamedMainValue> getNamedMainValues() { - return namedMainValues; - } - - public void setNamedMainValues(List<ImportNamedMainValue> namedMainValues) { - this.namedMainValues = namedMainValues; - } - - public List<ImportMainValue> getMainValues() { - return mainValues; - } - - public void setMainValues(List<ImportMainValue> mainValues) { - this.mainValues = mainValues; - } - - public void parseDependencies() throws IOException { - StaFileParser sfp = new StaFileParser(); - sfp.parse(this); - - AtFileParser afp = new AtFileParser(); - setDischargeTable(afp.parse(getAtFile())); - parseHistoricalDischargeTables(); - } - - public void parseHistoricalDischargeTables() throws IOException { - if (Config.INSTANCE.skipHistoricalDischargeTables()) { - log.info("skip historical discharge tables"); - return; - } - - log.info("parse historical discharge tables"); - - File riverDir = atFile.getParentFile().getParentFile(); - - File histDischargeDir = FileTools.repair( - new File(riverDir, HISTORICAL_DISCHARGE_TABLES)); - - if (!histDischargeDir.isDirectory() || !histDischargeDir.canRead()) { - log.info("cannot find '" + histDischargeDir + "'"); - return; - } - - histDischargeDir = FileTools.repair( - new File(histDischargeDir, getName())); - - if (!histDischargeDir.isDirectory() || !histDischargeDir.canRead()) { - log.info("cannot find '" + histDischargeDir + "'"); - return; - } - - File [] files = histDischargeDir.listFiles(); - - if (files == null) { - log.info("cannot read directory '" + histDischargeDir + "'"); - return; - } - - for (File file: files) { - if (!file.isFile() || !file.canRead()) { - continue; - } - String name = file.getName().toLowerCase(); - if (!name.endsWith(".at")) { - continue; - } - log.info("found at file '" + file.getName() + "'"); - - AtFileParser afp = new AtFileParser(); - historicalDischargeTables.add( - afp.parse(file, HISTORICAL_DISCHARGE_TABLES + "/", 1)); - } - } - - public void storeDependencies(River river) { - - Gauge gauge = getPeer(river); - - log.info("store main value types"); - for (ImportMainValueType mainValueType: mainValueTypes) { - mainValueType.getPeer(); - } - - log.info("store named main values"); - for (ImportNamedMainValue namedMainValue: namedMainValues) { - namedMainValue.getPeer(); - } - - log.info("store main values"); - for (ImportMainValue mainValue: mainValues) { - mainValue.getPeer(river); - } - - storeDischargeTable(gauge); - storeHistoricalDischargeTable(gauge); - } - - public void storeDischargeTable(Gauge gauge) { - log.info("store discharge table"); - dischargeTable.getPeer(gauge); - dischargeTable.storeDependencies(gauge); - } - - public void storeHistoricalDischargeTable(Gauge gauge) { - log.info("store historical discharge tables"); - for (ImportDischargeTable hdt: historicalDischargeTables) { - hdt.storeDependencies(gauge); - } - } - - public Gauge getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from Gauge where name=:name " + - "and river.id=:river"); - query.setString("name", name); - query.setParameter("river", river.getId()); - List<Gauge> gauges = query.list(); - if (gauges.isEmpty()) { - peer = new Gauge( - name, river, - station, aeo, datum, - officialNumber, - range.getPeer(river)); - session.save(peer); - } - else { - peer = gauges.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportGrainFraction.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.GrainFraction; - - -public class ImportGrainFraction { - - private static final Logger log = - Logger.getLogger(ImportGrainFraction.class); - - private String name; - - private Double lower; - private Double upper; - - private GrainFraction peer; - - - public ImportGrainFraction(String name) { - this.name = name; - } - - - public ImportGrainFraction( - String name, - Double lower, - Double upper - ) { - this.name = name; - this.lower = lower; - this.upper = upper; - } - - - public void storeDependencies() { - log.debug("store dependencies"); - - getPeer(); - } - - - public GrainFraction getPeer() { - log.debug("get peer"); - - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from GrainFraction where " + - " name=:name and " + - " lower=:lower and " + - " upper=:upper" - ); - - query.setParameter("name", name); - query.setParameter("lower", lower); - query.setParameter("upper", upper); - - List<GrainFraction> fractions = query.list(); - if (fractions.isEmpty()) { - log.info("create new GrainFraction"); - - peer = new GrainFraction(name, lower, upper); - session.save(peer); - } - else { - peer = fractions.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportHYK.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.HYK; -import de.intevation.flys.model.River; - -import java.util.List; -import java.util.ArrayList; - -import org.hibernate.Session; -import org.hibernate.Query; - -import org.apache.log4j.Logger; - -public class ImportHYK -{ - private static Logger log = Logger.getLogger(ImportHYK.class); - - protected ImportRiver river; - protected String description; - - protected List<ImportHYKEntry> entries; - - protected HYK peer; - - public ImportHYK() { - entries = new ArrayList<ImportHYKEntry>(); - } - - public ImportHYK(ImportRiver river, String description) { - this(); - this.river = river; - this.description = description; - } - - public ImportRiver getRiver() { - return river; - } - - public void setRiver(ImportRiver river) { - this.river = river; - } - - public void addEntry(ImportHYKEntry entry) { - entries.add(entry); - entry.setHYK(this); - } - - public void storeDependencies() { - log.info("store HYK '" + description + "'"); - getPeer(); - for (int i = 0, N = entries.size(); i < N; ++i) { - ImportHYKEntry entry = entries.get(i); - log.info(" store km " + entry.getKm() + - " (" + (i+1) + " of " + N + ")"); - entry.storeDependencies(); - } - } - - public HYK getPeer() { - if (peer == null) { - River r = river.getPeer(); - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery( - "from HYK where river=:river and description=:description"); - query.setParameter("river", r); - query.setParameter("description", description); - List<HYK> hyks = query.list(); - if (hyks.isEmpty()) { - peer = new HYK(r, description); - session.save(peer); - } - else { - peer = hyks.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportHYKEntry.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.HYKEntry; -import de.intevation.flys.model.HYK; - -import java.util.Date; -import java.util.List; -import java.util.ArrayList; - -import java.math.BigDecimal; - -import org.hibernate.Session; -import org.hibernate.Query; - -public class ImportHYKEntry -{ - protected ImportHYK hyk; - protected BigDecimal km; - protected Date measure; - - protected List<ImportHYKFormation> formations; - - protected HYKEntry peer; - - public ImportHYKEntry() { - formations = new ArrayList<ImportHYKFormation>(); - } - - public ImportHYKEntry( - ImportHYK hyk, - BigDecimal km, - Date measure - ) { - this(); - this.hyk = hyk; - this.km = km; - this.measure = measure; - } - - public ImportHYK getHYK() { - return hyk; - } - - public void setHYK(ImportHYK hyk) { - this.hyk = hyk; - } - - public BigDecimal getKm() { - return km; - } - - public void setKm(BigDecimal km) { - this.km = km; - } - - public void addFormation(ImportHYKFormation formation) { - int numFormation = formations.size(); - formations.add(formation); - formation.setFormationNum(numFormation); - formation.setEntry(this); - } - - public void storeDependencies() { - getPeer(); - for (ImportHYKFormation formation: formations) { - formation.storeDependencies(); - } - } - - public HYKEntry getPeer() { - if (peer == null) { - HYK h = hyk.getPeer(); - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery( - "from HYKEntry where HYK=:hyk " + - "and km=:km and measure=:measure"); - query.setParameter("hyk", h); - query.setParameter("km", km); - query.setParameter("measure", measure); - List<HYKEntry> entries = query.list(); - if (entries.isEmpty()) { - peer = new HYKEntry(h, km, measure); - session.save(peer); - } - else { - peer = entries.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportHYKFlowZone.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.HYKFormation; -import de.intevation.flys.model.HYKFlowZone; -import de.intevation.flys.model.HYKFlowZoneType; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -import java.math.BigDecimal; - -public class ImportHYKFlowZone -{ - protected ImportHYKFormation formation; - protected ImportHYKFlowZoneType type; - protected BigDecimal a; - protected BigDecimal b; - - protected HYKFlowZone peer; - - public ImportHYKFlowZone() { - } - - public ImportHYKFlowZone( - ImportHYKFormation formation, - ImportHYKFlowZoneType type, - BigDecimal a, - BigDecimal b - ) { - this.formation = formation; - this.type = type; - this.a = a; - this.b = b; - } - - public ImportHYKFormation getFormation() { - return formation; - } - - public void setFormation(ImportHYKFormation formation) { - this.formation = formation; - } - - public void storeDependencies() { - getPeer(); - } - - public HYKFlowZone getPeer() { - if (peer == null) { - HYKFormation f = formation.getPeer(); - HYKFlowZoneType t = type.getPeer(); - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery( - "from HYKFlowZone where formation=:formation " + - "and type=:type and a=:a and b=:b"); - query.setParameter("formation", f); - query.setParameter("type", t); - query.setParameter("a", a); - query.setParameter("b", b); - List<HYKFlowZone> zones = query.list(); - if (zones.isEmpty()) { - peer = new HYKFlowZone(f, t, a, b); - session.save(peer); - } - else { - peer = zones.get(0); - } - - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportHYKFlowZoneType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,41 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.HYKFlowZoneType; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportHYKFlowZoneType -{ - private String name; - private HYKFlowZoneType peer; - - public ImportHYKFlowZoneType() { - } - - public ImportHYKFlowZoneType(String name) { - this.name = name; - } - - public HYKFlowZoneType getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery( - "from HYKFlowZoneType where name=:name"); - query.setParameter("name", name); - List<HYKFlowZoneType> flowZoneTypes = query.list(); - if (flowZoneTypes.isEmpty()) { - peer = new HYKFlowZoneType(name); - session.save(peer); - } - else { - peer = flowZoneTypes.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportHYKFormation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,150 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.HYKFormation; -import de.intevation.flys.model.HYKEntry; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.math.BigDecimal; - -public class ImportHYKFormation -{ - protected int formationNum; - protected ImportHYKEntry entry; - protected BigDecimal top; - protected BigDecimal bottom; - protected BigDecimal distanceVL; - protected BigDecimal distanceHF; - protected BigDecimal distanceVR; - - protected List<ImportHYKFlowZone> zones; - - protected HYKFormation peer; - - public ImportHYKFormation() { - zones = new ArrayList<ImportHYKFlowZone>(); - } - - public ImportHYKFormation( - int formationNum, - ImportHYKEntry entry, - BigDecimal top, - BigDecimal bottom, - BigDecimal distanceVL, - BigDecimal distanceHF, - BigDecimal distanceVR - ) { - this(); - this.formationNum = formationNum; - this.entry = entry; - this.top = top; - this.bottom = bottom; - this.distanceVL = distanceVL; - this.distanceHF = distanceHF; - this.distanceVR = distanceVR; - } - - public void addFlowZone(ImportHYKFlowZone zone) { - zones.add(zone); - zone.setFormation(this); - } - - public int getFormationNum() { - return formationNum; - } - - public void setFormationNum(int formationNum) { - this.formationNum = formationNum; - } - - public ImportHYKEntry getEntry() { - return entry; - } - - public void setEntry(ImportHYKEntry entry) { - this.entry = entry; - } - - public BigDecimal getTop() { - return top; - } - - public void setTop(BigDecimal top) { - this.top = top; - } - - public BigDecimal getBottom() { - return bottom; - } - - public void setBottom(BigDecimal bottom) { - this.bottom = bottom; - } - - public BigDecimal getDistanceVL() { - return distanceVL; - } - - public void setDistanceVL(BigDecimal distanceVL) { - this.distanceVL = distanceVL; - } - - public BigDecimal getDistanceHF() { - return distanceHF; - } - - public void setDistanceHF(BigDecimal distanceHF) { - this.distanceHF = distanceHF; - } - - public BigDecimal getDistanceVR() { - return distanceVR; - } - - public void setDistanceVR(BigDecimal distanceVR) { - this.distanceVR = distanceVR; - } - - public void storeDependencies() { - getPeer(); - for (ImportHYKFlowZone zone: zones) { - zone.storeDependencies(); - } - } - - public HYKFormation getPeer() { - if (peer == null) { - HYKEntry e = entry.getPeer(); - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery( - "from HYKFormation where formationNum=:formationNum " + - "and entry=:entry and top=:top and bottom=:bottom " + - "and distanceVL=:distanceVL and distanceHF=:distanceHF " + - "and distanceVR=:distanceVR"); - query.setParameter("formationNum", formationNum); - query.setParameter("entry", e); - query.setParameter("top", top); - query.setParameter("bottom", bottom); - query.setParameter("distanceVL", distanceVL); - query.setParameter("distanceHF", distanceHF); - query.setParameter("distanceVR", distanceVR); - List<HYKFormation> formations = query.list(); - if (formations.isEmpty()) { - peer = new HYKFormation( - formationNum, e, top, bottom, - distanceVL, distanceHF, distanceVR); - session.save(peer); - } - else { - peer = formations.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportLocationSystem.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.LocationSystem; - - -public class ImportLocationSystem { - - private static final Logger log = - Logger.getLogger(ImportLocationSystem.class); - - - protected String name; - protected String description; - - protected LocationSystem peer; - - - public ImportLocationSystem(String name, String description) { - this.name = name; - this.description = description; - } - - public void storeDependencies() { - log.info("store LocationSystem '" + name + "'"); - LocationSystem ls = getPeer(); - - Session session = ImporterSession.getInstance().getDatabaseSession(); - session.flush(); - } - - public LocationSystem getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from LocationSystem where " + - "name=:name and description=:description"); - query.setParameter("name", name); - query.setParameter("description", description); - - List<LocationSystem> lss = query.list(); - if (lss.isEmpty()) { - peer = new LocationSystem(name, description); - session.save(peer); - } - else { - peer = lss.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportMainValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,92 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import java.math.BigDecimal; - -import de.intevation.flys.model.MainValue; -import de.intevation.flys.model.Gauge; -import de.intevation.flys.model.River; -import de.intevation.flys.model.NamedMainValue; -import de.intevation.flys.model.TimeInterval; - -import org.hibernate.Session; -import org.hibernate.Query; - -public class ImportMainValue -{ - protected ImportGauge gauge; - protected ImportNamedMainValue mainValue; - protected BigDecimal value; - protected ImportTimeInterval timeInterval; - - protected MainValue peer; - - public ImportMainValue() { - } - - public ImportMainValue( - ImportGauge gauge, - ImportNamedMainValue mainValue, - BigDecimal value, - ImportTimeInterval timeInterval - ) { - this.gauge = gauge; - this.mainValue = mainValue; - this.value = value; - this.timeInterval = timeInterval; - } - - public ImportGauge getGauge() { - return gauge; - } - - public void setGauge(ImportGauge gauge) { - this.gauge = gauge; - } - - public ImportNamedMainValue getMainValue() { - return mainValue; - } - - public void setMainValue(ImportNamedMainValue mainValue) { - this.mainValue = mainValue; - } - - public BigDecimal getValue() { - return value; - } - - public void setValue(BigDecimal value) { - this.value = value; - } - - public MainValue getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from MainValue where " - + "gauge.id=:gauge_id and mainValue.id=:name_id " - + "and timeInterval = :time " - + "and value=:value"); - Gauge g = gauge.getPeer(river); - NamedMainValue n = mainValue.getPeer(); - TimeInterval t = timeInterval != null - ? timeInterval.getPeer() - : null; - query.setParameter("gauge_id", g.getId()); - query.setParameter("name_id", n.getId()); - query.setParameter("value", value); - query.setParameter("time", t); - List<MainValue> values = query.list(); - if (values.isEmpty()) { - peer = new MainValue(g, n, value, null); - session.save(peer); - } - else { - peer = values.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportMainValueType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.MainValueType; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportMainValueType -implements Comparable<ImportMainValueType> -{ - protected String name; - - protected MainValueType peer; - - public ImportMainValueType() { - } - - public ImportMainValueType(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int compareTo(ImportMainValueType other) { - return name.compareTo(other.name); - } - - @Override - public boolean equals(Object other) { - if (other == this) return true; - if (!(other instanceof ImportMainValueType)) return false; - return name.equals(((ImportMainValueType)other).name); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - public MainValueType getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from MainValueType where name=:name"); - query.setString("name", name); - List<MainValueType> values = query.list(); - if (values.isEmpty()) { - peer = new MainValueType(name); - session.save(peer); - } - else { - peer = values.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportMeasurementStation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,113 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.hibernate.Session; - -import de.intevation.flys.model.Gauge; -import de.intevation.flys.model.MeasurementStation; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; -import de.intevation.flys.model.TimeInterval; - - -public class ImportMeasurementStation { - - private static final Logger log = Logger - .getLogger(ImportMeasurementStation.class); - - private MeasurementStation peer; - - public String name; - public Double station; - public ImportRange range; - public String measurementType; - public String riverside; - public String gauge; - public ImportTimeInterval observationTimerange; - public String operator; - public String description; - - public ImportMeasurementStation() { - } - - private Gauge getGaugeFromDB() { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - org.hibernate.Query query = session - .createQuery("FROM Gauge WHERE name=:name"); - - query.setParameter("name", gauge); - List<Gauge> gauges = query.list(); - - return gauges.isEmpty() ? null : gauges.get(0); - } - - public boolean storeDependencies(River river) { - getPeer(river); - - return peer != null; - } - - public Object getPeer(River river) { - if (peer == null) { - Gauge gauge = null; - try { - gauge = getGaugeFromDB(); - if (gauge == null) { - log.warn("No gauge found for measurement station '" + name - + "'"); - } - } - catch (Exception e) { - log.error("Exception: " + e.getMessage()); - } - - Range range = null; - - if (this.range != null) { - range = this.range.getPeer(river); - } - - if (range == null) { - log.warn("No range found for measurement station '" + name + "'"); - } - - TimeInterval observationTimerange = this.observationTimerange - .getPeer(); - if (observationTimerange == null) { - log.warn("No time range found for measurement station '" - + name + "'"); - } - - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - org.hibernate.Query query = session - .createQuery( - "FROM MeasurementStation " + - "WHERE river=:river" + - " AND station=:station " + - " AND measurement_type=:measurement_type "); - - query.setParameter("river", river); - query.setParameter("station", station); - query.setParameter("measurement_type", measurementType); - - List<MeasurementStation> stations = query.list(); - - if (stations.isEmpty()) { - log.info("create new measurement station '" + name + "'"); - - peer = new MeasurementStation(river, name, measurementType, - riverside, station, range, gauge, this.gauge, - observationTimerange, operator, description); - - session.save(peer); - } - } - - return peer; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportMorphWidth.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.MorphologicalWidth; -import de.intevation.flys.model.River; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; - - -public class ImportMorphWidth { - - private static Logger log = Logger.getLogger(ImportMorphWidth.class); - - protected MorphologicalWidth peer; - - protected ImportUnit unit; - - protected List<ImportMorphWidthValue> values; - - public ImportMorphWidth() { - this.values = new ArrayList<ImportMorphWidthValue>(); - } - - public void addValue(ImportMorphWidthValue value) { - this.values.add(value); - } - - public void setUnit(ImportUnit unit) { - this.unit = unit; - } - - public void storeDependencies(River river) { - log.info("store dependencies"); - - MorphologicalWidth peer = getPeer(river); - - if (peer != null) { - log.info("store morphological width values"); - - for (ImportMorphWidthValue value : values) { - value.storeDependencies(peer); - } - } - } - - public MorphologicalWidth getPeer(River river) { - log.info("get peer"); - - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - Query query = session.createQuery("from MorphologicalWidth where " - + " river=:river and " + " unit=:unit"); - - query.setParameter("river", river); - query.setParameter("unit", unit.getPeer()); - - List<MorphologicalWidth> widths = query.list(); - - if (widths.isEmpty()) { - log.debug("Create new MorphologicalWidth DB instance."); - - peer = new MorphologicalWidth(river, unit.getPeer()); - - session.save(peer); - } - else { - peer = widths.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportMorphWidthValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.MorphologicalWidth; -import de.intevation.flys.model.MorphologicalWidthValue; - - -public class ImportMorphWidthValue { - - private static Logger log = Logger.getLogger(ImportMorphWidthValue.class); - - - protected MorphologicalWidthValue peer; - - protected BigDecimal station; - protected BigDecimal width; - - protected String description; - - - public ImportMorphWidthValue( - BigDecimal station, - BigDecimal width, - String description - ) { - this.station = station; - this.width = width; - this.description = description; - } - - - public void storeDependencies(MorphologicalWidth parent) { - getPeer(parent); - } - - - public MorphologicalWidthValue getPeer(MorphologicalWidth parent) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from MorphologicalWidthValue where " + - " morphologicalWidth=:morphologicalWidth and " + - " station=:station and " + - " width=:width and " + - " description=:description"); - - query.setParameter("morphologicalWidth", parent); - query.setParameter("station", station); - query.setParameter("width", width); - query.setParameter("description", description); - - List<MorphologicalWidthValue> values = query.list(); - - if (values.isEmpty()) { - peer = new MorphologicalWidthValue( - parent, - station, - width, - description - ); - - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportNamedMainValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import de.intevation.flys.model.NamedMainValue; -import de.intevation.flys.model.MainValueType; - -import org.hibernate.Session; -import org.hibernate.Query; - -public class ImportNamedMainValue -{ - protected ImportMainValueType mainValueType; - protected String name; - - protected NamedMainValue peer; - - public ImportNamedMainValue() { - } - - public ImportNamedMainValue( - ImportMainValueType mainValueType, - String name - ) { - this.mainValueType = mainValueType; - this.name = name; - } - - public ImportMainValueType getMainValueType() { - return mainValueType; - } - - public void setMainValueType(ImportMainValueType mainValueType) { - this.mainValueType = mainValueType; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public NamedMainValue getPeer() { - if (peer == null) { - MainValueType type = mainValueType.getPeer(); - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from NamedMainValue where " + - "name=:name and type.id=:id"); - query.setString("name", name); - query.setParameter("id", type.getId()); - List<NamedMainValue> named = query.list(); - if (named.isEmpty()) { - peer = new NamedMainValue(name, type); - session.save(peer); - } - else { - peer = named.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportPosition.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Position; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportPosition -implements Comparable<ImportPosition> -{ - protected String value; - - protected Position peer; - - public ImportPosition() { - } - - public ImportPosition(String value) { - this.value = value; - } - - public int compareTo(ImportPosition other) { - return value.compareTo(other.value); - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public Position getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from Position where value=:value"); - query.setString("value", value); - List<Position> positions = query.list(); - if (positions.isEmpty()) { - peer = new Position(value); - session.save(peer); - } - else { - peer = positions.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : -
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportRange.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,78 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -/** A range that is about to be imported. */ -public class ImportRange -implements Comparable<ImportRange> -{ - /** Private logger. */ - private static Logger log = Logger.getLogger(ImportRange.class); - - protected BigDecimal a; - protected BigDecimal b; - - protected Range peer; - - public ImportRange() { - } - - public ImportRange(BigDecimal a, BigDecimal b) { - this.a = a; - this.b = b; - } - - private static final int compare(BigDecimal a, BigDecimal b) { - if (a == null && b == null) { - return 0; - } - if (a == null && b != null) { - return -1; - } - if (a != null && b == null) { - return +1; - } - return a.compareTo(b); - } - - public void fixRangesOrder() { - if (compare(a, b) > 0) { - BigDecimal t = a; a = b; b = t; - } - } - - public int compareTo(ImportRange other) { - int cmp = compare(a, other.a); - if (cmp != 0) return cmp; - return compare(b, other.b); - } - - public BigDecimal getA() { - return a; - } - - public void setA(BigDecimal a) { - this.a = a; - } - - public BigDecimal getB() { - return b; - } - - public void setB(BigDecimal b) { - this.b = b; - } - - public Range getPeer(River river) { - if (peer == null) { - peer = ImporterSession.getInstance().getRange(river, a, b); - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportRiver.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1464 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.artifacts.common.utils.FileTools.HashedFile; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.parsers.AnnotationClassifier; -import de.intevation.flys.importer.parsers.AnnotationsParser; -import de.intevation.flys.importer.parsers.BedHeightEpochParser; -import de.intevation.flys.importer.parsers.BedHeightSingleParser; -import de.intevation.flys.importer.parsers.CrossSectionParser; -import de.intevation.flys.importer.parsers.DA50Parser; -import de.intevation.flys.importer.parsers.DA66Parser; -import de.intevation.flys.importer.parsers.FlowVelocityMeasurementParser; -import de.intevation.flys.importer.parsers.FlowVelocityModelParser; -import de.intevation.flys.importer.parsers.HYKParser; -import de.intevation.flys.importer.parsers.MeasurementStationsParser; -import de.intevation.flys.importer.parsers.MorphologicalWidthParser; -import de.intevation.flys.importer.parsers.PRFParser; -import de.intevation.flys.importer.parsers.PegelGltParser; -import de.intevation.flys.importer.parsers.SQRelationParser; -import de.intevation.flys.importer.parsers.SedimentDensityParser; -import de.intevation.flys.importer.parsers.SedimentYieldParser; -import de.intevation.flys.importer.parsers.W80Parser; -import de.intevation.flys.importer.parsers.W80CSVParser; -import de.intevation.flys.importer.parsers.WaterlevelDifferencesParser; -import de.intevation.flys.importer.parsers.WaterlevelParser; -import de.intevation.flys.importer.parsers.WstParser; - -import de.intevation.flys.model.River; -import de.intevation.flys.model.Unit; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; - - -/** Import all river-related data (files) that can be found. */ -public class ImportRiver -{ - /** Private logger. */ - private static Logger log = Logger.getLogger(ImportRiver.class); - - public static final String PEGEL_GLT = "PEGEL.GLT"; - - public static final String FIXATIONS = "Fixierungen"; - - public static final String EXTRA_LONGITUDINALS = - "Zus.L\u00e4ngsschnitte"; - - public static final String [] OFFICIAL_LINES_FOLDERS = { - "Basisdaten", - "Fixierungen" }; - - public static final String OFFICIAL_LINES = - "Amtl_Linien.wst"; - - public static final String FLOOD_WATER = "HW-Marken"; - - public static final String FLOOD_PROTECTION = - "HW-Schutzanlagen"; - - public static final String MINFO_DIR = "Morphologie"; - - public static final String BED_HEIGHT_DIR = "Sohlhoehen"; - - public static final String BED_HEIGHT_SINGLE_DIR = "Einzeljahre"; - - public static final String BED_HEIGHT_EPOCH_DIR = "Epochen"; - - public static final String SEDIMENT_DENSITY_DIR = "Sedimentdichte"; - - public static final String MORPHOLOGICAL_WIDTH_DIR = "morphologische_Breite"; - - public static final String FLOW_VELOCITY_DIR = "Geschwindigkeit_Schubspannung"; - - public static final String FLOW_VELOCITY_MODEL = "Modellrechnungen"; - - public static final String FLOW_VELOCITY_MEASUREMENTS = "v-Messungen"; - - public static final String SEDIMENT_YIELD_DIR = "Fracht"; - - public static final String SEDIMENT_YIELD_SINGLE_DIR = "Einzeljahre"; - - public static final String SEDIMENT_YIELD_EPOCH_DIR = "Epochen"; - - public static final String MINFO_FIXATIONS_DIR = "Fixierungsanalyse"; - - public static final String MINFO_WATERLEVELS_DIR = "Wasserspiegellagen"; - - public static final String MINFO_WATERLEVEL_DIFF_DIR = "Wasserspiegeldifferenzen"; - - public static final String MINFO_BASE_DIR = "Basisdaten"; - - public static final String MINFO_CORE_DATA_FILE = "Stammdaten_Messstellen.csv"; - - public static final String MINFO_SQ_DIR = "Feststofftransport-Abfluss-Beziehung"; - - protected String name; - - protected Long officialNumber; - - protected File wstFile; - - protected File bbInfoFile; - - protected List<ImportGauge> gauges; - - protected List<ImportAnnotation> annotations; - - protected List<ImportHYK> hyks; - - protected List<ImportCrossSection> crossSections; - - protected List<ImportWst> extraWsts; - - protected List<ImportWst> fixations; - - protected List<ImportWst> officialLines; - - protected List<ImportWst> floodWater; - - protected List<ImportWst> floodProtection; - - /** Wst-structures from waterlevel-csv files. */ - protected List<ImportWst> waterlevels; - - /** Wst-structures from waterlevel-difference-csv files. */ - protected List<ImportWst> waterlevelDifferences; - - protected List<ImportBedHeight> bedHeightSingles; - - protected List<ImportBedHeight> bedHeightEpochs; - - protected List<ImportSedimentDensity> sedimentDensities; - - protected List<ImportMorphWidth> morphologicalWidths; - - protected List<ImportFlowVelocityModel> flowVelocityModels; - - protected List<ImportFlowVelocityMeasurement> flowVelocityMeasurements; - - protected List<ImportSedimentYield> sedimentYields; - - protected List<ImportMeasurementStation> measurementStations; - - protected List<ImportSQRelation> sqRelations; - - protected ImportWst wst; - - protected ImportUnit wstUnit; - - protected AnnotationClassifier annotationClassifier; - - /** Database-mapped River instance. */ - protected River peer; - - - /** Callback-implementation for CrossSectionParsers: - * Accept files with different md5(?)sums than what has already been parsed, - * on successfull parse, add data. */ - class ImportRiverCrossSectionParserCallback implements CrossSectionParser.Callback { - Set<HashedFile> files = new HashSet<HashedFile>(); - String type; - - - /** - * Create new Callback, given type which is used for logging - * purposes only. - */ - public ImportRiverCrossSectionParserCallback (String type) { - this.type = type; - } - - - /** Accept file if not duplicate. */ - public boolean accept(File file) { - HashedFile hf = new HashedFile(file); - boolean success = files.add(hf); - if (!success) { - log.warn(type + " file '" + file + "' seems to be a duplicate."); - } - return success; - } - - - /** Add crosssection. */ - public void parsed(CrossSectionParser parser) { - log.debug("callback from " + type + " parser"); - - addCrossSections(parser); - } - } // ImportRiverCrossSectionParserCallback - - - public ImportRiver() { - hyks = new ArrayList<ImportHYK>(); - crossSections = new ArrayList<ImportCrossSection>(); - extraWsts = new ArrayList<ImportWst>(); - fixations = new ArrayList<ImportWst>(); - officialLines = new ArrayList<ImportWst>(); - floodWater = new ArrayList<ImportWst>(); - waterlevels = new ArrayList<ImportWst>(); - waterlevelDifferences = new ArrayList<ImportWst>(); - floodProtection = new ArrayList<ImportWst>(); - sedimentDensities = new ArrayList<ImportSedimentDensity>(); - morphologicalWidths = new ArrayList<ImportMorphWidth>(); - flowVelocityModels = new ArrayList<ImportFlowVelocityModel>(); - flowVelocityMeasurements = new ArrayList<ImportFlowVelocityMeasurement>(); - sedimentYields = new ArrayList<ImportSedimentYield>(); - measurementStations = new ArrayList<ImportMeasurementStation>(); - sqRelations = new ArrayList<ImportSQRelation>(); - } - - public ImportRiver( - String name, - File wstFile, - File bbInfoFile, - AnnotationClassifier annotationClassifier - ) { - this(); - this.name = name; - this.wstFile = wstFile; - this.bbInfoFile = bbInfoFile; - this.annotationClassifier = annotationClassifier; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getOfficialNumber() { - return this.officialNumber; - } - - public void setOfficialNumber(Long officialNumber) { - this.officialNumber = officialNumber; - } - - public File getWstFile() { - return wstFile; - } - - public void setWstFile(File wstFile) { - this.wstFile = wstFile; - } - - public File getBBInfo() { - return bbInfoFile; - } - - public void setBBInfo(File bbInfoFile) { - this.bbInfoFile = bbInfoFile; - } - - public ImportWst getWst() { - return wst; - } - - public void setWst(ImportWst wst) { - this.wst = wst; - } - - public File getMinfoDir() { - File riverDir = wstFile.getParentFile().getParentFile().getParentFile(); - return new File(riverDir, MINFO_DIR); - } - - public void parseDependencies() throws IOException { - parseGauges(); - parseAnnotations(); - parsePRFs(); - parseDA66s(); - parseDA50s(); - parseW80s(); - parseW80CSVs(); - parseHYKs(); - parseWst(); - parseExtraWsts(); - parseFixations(); - parseOfficialLines(); - parseFloodWater(); - parseFloodProtection(); - parseBedHeight(); - parseSedimentDensity(); - parseMorphologicalWidth(); - parseFlowVelocity(); - parseSedimentYield(); - parseWaterlevels(); - parseWaterlevelDifferences(); - parseMeasurementStations(); - parseSQRelation(); - } - - public void parseFloodProtection() throws IOException { - if (Config.INSTANCE.skipFloodProtection()) { - log.info("skip parsing flood protection"); - return; - } - - log.info("Parse flood protection wst file"); - - File riverDir = wstFile.getParentFile().getParentFile(); - - File dir = FileTools.repair(new File(riverDir, FLOOD_PROTECTION)); - - if (!dir.isDirectory() || !dir.canRead()) { - log.info("no directory '" + dir + "' found"); - return; - } - - File [] files = dir.listFiles(); - - if (files == null) { - log.warn("cannot read '" + dir + "'"); - return; - } - - for (File file: files) { - if (!file.isFile() || !file.canRead()) { - continue; - } - String name = file.getName().toLowerCase(); - if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { - continue; - } - log.info("found file '" + file.getName() + "'"); - WstParser wstParser = new WstParser(); - wstParser.parse(file); - ImportWst iw = wstParser.getWst(); - iw.setKind(5); - iw.setDescription(FLOOD_PROTECTION + "/" + iw.getDescription()); - floodProtection.add(iw); - } - } - - public void storeOfficialNumber() { - if (Config.INSTANCE.skipBWASTR()) { - log.info("skip storing official number."); - return; - } - getPeer().setOfficialNumber(officialNumber); - } - - public void parseBedHeight() throws IOException { - File minfoDir = getMinfoDir(); - File bedHeightDir = new File(minfoDir, BED_HEIGHT_DIR); - File singlesDir = new File(bedHeightDir, BED_HEIGHT_SINGLE_DIR); - File epochDir = new File(bedHeightDir, BED_HEIGHT_EPOCH_DIR); - - if (Config.INSTANCE.skipBedHeightSingle()) { - log.info("skip parsing bed height single."); - } - else { - log.info("Parse bed height single."); - parseBedHeightSingles(singlesDir); - } - - if (Config.INSTANCE.skipBedHeightEpoch()) { - log.info("skip parsing bed height epochs."); - } - else { - log.info("Parse bed height epochs."); - parseBedHeightEpochs(epochDir); - } - } - - - protected void parseSedimentDensity() throws IOException { - if (Config.INSTANCE.skipSedimentDensity()) { - log.info("skip parsing sediment density."); - return; - } - - log.debug("Parse sediment density"); - - File minfoDir = getMinfoDir(); - File sediment = new File(minfoDir, SEDIMENT_DENSITY_DIR); - - File[] files = sediment.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + sediment + "'"); - return; - } - - SedimentDensityParser parser = new SedimentDensityParser(); - - for (File file: files) { - parser.parse(file); - } - - sedimentDensities = parser.getSedimentDensities(); - - log.info("Parsed " + sedimentDensities.size() + " sediment densities."); - } - - - protected void parseMorphologicalWidth() throws IOException { - if (Config.INSTANCE.skipMorphologicalWidth()) { - log.info("skip parsing morphological width."); - return; - } - - log.debug("Parse morphological width"); - - File minfoDir = getMinfoDir(); - File morphDir = new File(minfoDir, MORPHOLOGICAL_WIDTH_DIR); - - File[] files = morphDir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + morphDir + "'"); - return; - } - - MorphologicalWidthParser parser = new MorphologicalWidthParser(); - - for (File file: files) { - parser.parse(file); - } - - morphologicalWidths = parser.getMorphologicalWidths(); - - log.info("Parsed " + morphologicalWidths.size() + " morph. widths files."); - } - - - protected void parseFlowVelocity() throws IOException { - if (Config.INSTANCE.skipFlowVelocity()) { - log.info("skip parsing flow velocity"); - return; - } - - log.debug("Parse flow velocity"); - - File minfoDir = getMinfoDir(); - File flowDir = new File(minfoDir, FLOW_VELOCITY_DIR); - File modelDir = new File(flowDir, FLOW_VELOCITY_MODEL); - File measureDir = new File(flowDir, FLOW_VELOCITY_MEASUREMENTS); - - File[] modelFiles = modelDir.listFiles(); - File[] measureFiles = measureDir.listFiles(); - - if (modelFiles == null) { - log.warn("Cannot read directory '" + modelDir + "'"); - } - else { - FlowVelocityModelParser parser = new FlowVelocityModelParser(); - - for (File model: modelFiles) { - log.debug("Parse file '" + model + "'"); - parser.parse(model); - } - - flowVelocityModels = parser.getModels(); - } - - if (measureFiles == null) { - log.warn("Cannot read directory '" + measureDir + "'"); - } - else { - FlowVelocityMeasurementParser parser = - new FlowVelocityMeasurementParser(); - - for (File measurement: measureFiles) { - log.debug("Parse file '" + measurement + "'"); - parser.parse(measurement); - } - - flowVelocityMeasurements = parser.getMeasurements(); - } - } - - - protected void parseSedimentYield() throws IOException { - if (Config.INSTANCE.skipSedimentYield()) { - log.info("skip parsing sediment yield data"); - return; - } - - log.debug("Parse sediment yield data"); - - File minfoDir = getMinfoDir(); - File sedimentYieldDir = new File(minfoDir, SEDIMENT_YIELD_DIR); - - File singleDir = new File(sedimentYieldDir, SEDIMENT_YIELD_SINGLE_DIR); - File epochDir = new File(sedimentYieldDir, SEDIMENT_YIELD_EPOCH_DIR); - - File[] singles = singleDir.listFiles(); - File[] epochs = epochDir.listFiles(); - - SedimentYieldParser parser = new SedimentYieldParser(); - - if (singles == null || singles.length == 0) { - log.warn("Cannot read directory '" + singleDir + "'"); - } - else { - for (File file: singles) { - if (file.isDirectory()) { - for (File child: file.listFiles()) { - parser.parse(child); - } - } - else { - parser.parse(file); - } - } - } - - if (epochs == null || epochs.length == 0) { - log.warn("Cannot read directory '" + epochDir + "'"); - } - else { - for (File file: epochs) { - if (file.isDirectory()) { - for (File child: file.listFiles()) { - parser.parse(child); - } - } - else { - parser.parse(file); - } - } - } - - sedimentYields = parser.getSedimentYields(); - } - - - protected void parseWaterlevels() throws IOException { - if (Config.INSTANCE.skipWaterlevels()) { - log.info("skip parsing waterlevels"); - return; - } - - log.info("Parse waterlevels"); - - File minfo = getMinfoDir(); - File fixDir = new File(minfo, MINFO_FIXATIONS_DIR); - File wspDir = new File(fixDir, MINFO_WATERLEVELS_DIR); - - File[] files = wspDir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory for wl '" + wspDir + "'"); - return; - } - - WaterlevelParser parser = new WaterlevelParser(); - - for (File file: files) { - parser.parse(file); - } - - // The parsed ImportWaterlevels are converted to - // 'fixation'-wsts now. - for(ImportWst iw: parser.getWaterlevels()) { - iw.setDescription("CSV/" + iw.getDescription()); - iw.setKind(6); - waterlevels.add(iw); - } - } - - protected void parseMeasurementStations() throws IOException { - if (Config.INSTANCE.skipMeasurementStations()) { - log.info("skip parsing measurement stations"); - return; - } - - log.info("Parse measurement stations"); - - File minfo = getMinfoDir(); - File minfoBaseDir = new File(minfo, MINFO_BASE_DIR); - File coredataFile = new File(minfoBaseDir, MINFO_CORE_DATA_FILE); - - if (coredataFile == null || !coredataFile.exists()) { - log.warn("No core data file '" + coredataFile.getAbsolutePath() + "' found"); - return; - } - - MeasurementStationsParser parser = new MeasurementStationsParser(); - try { - parser.parse(coredataFile); - measurementStations = parser.getMeasurementStations(); - - log.info("Successfully parsed " + measurementStations.size() + " measurement stations."); - } - catch (IOException ioe) { - log.error("unable to parse file '" + coredataFile.getName() + - ": " + ioe.getMessage()); - } - } - - - protected void parseWaterlevelDifferences() throws IOException { - if (Config.INSTANCE.skipWaterlevelDifferences()) { - log.info("skip parsing waterlevel differences"); - return; - } - - log.info("Parse waterlevel differences"); - - File minfo = getMinfoDir(); - File fixDir = new File(minfo, MINFO_FIXATIONS_DIR); - File diffDir = new File(fixDir, MINFO_WATERLEVEL_DIFF_DIR); - - File[] files = diffDir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + diffDir + "'"); - return; - } - - WaterlevelDifferencesParser parser = new WaterlevelDifferencesParser(); - - for (File file: files) { - parser.parse(file); - } - - // WaterlevelDifferences become Wsts now. - for(ImportWst iw: parser.getDifferences()) { - iw.setDescription("CSV/" + iw.getDescription()); - iw.setKind(7); - waterlevelDifferences.add(iw); - } - } - - - protected void parseSQRelation() throws IOException { - if (Config.INSTANCE.skipSQRelation()) { - log.info("skip parsing sq relation"); - return; - } - - log.info("Parse sq relations"); - - File minfo = getMinfoDir(); - File sqDir = new File(minfo, MINFO_SQ_DIR); - - File[] files = sqDir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + sqDir + "'"); - return; - } - - SQRelationParser parser = new SQRelationParser(); - - for (File file: files) { - parser.parse(file); - } - - sqRelations = parser.getSQRelations(); - - log.debug("Parsed " + sqRelations.size() + " SQ relations."); - } - - - protected void parseBedHeightSingles(File dir) throws IOException { - log.debug("Parse bed height singles"); - - File[] files = dir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + dir + "'"); - return; - } - - BedHeightSingleParser parser = new BedHeightSingleParser(); - - for (File file: files) { - parser.parse(file); - } - - bedHeightSingles = parser.getBedHeights(); - } - - - protected void parseBedHeightEpochs(File dir) throws IOException { - log.debug("Parse bed height epochs"); - - File[] files = dir.listFiles(); - - if (files == null) { - log.warn("Cannot read directory '" + dir + "'"); - return; - } - - BedHeightEpochParser parser = new BedHeightEpochParser(); - - for (File file: files) { - parser.parse(file); - } - - bedHeightEpochs = parser.getBedHeights(); - } - - - public void parseFloodWater() throws IOException { - if (Config.INSTANCE.skipFloodWater()) { - log.info("skip parsing flod water"); - return; - } - - log.info("Parse flood water wst file"); - - File riverDir = wstFile.getParentFile().getParentFile(); - - File dir = FileTools.repair(new File(riverDir, FLOOD_WATER)); - - if (!dir.isDirectory() || !dir.canRead()) { - log.info("no directory '" + dir + "' found"); - return; - } - - File [] files = dir.listFiles(); - - if (files == null) { - log.warn("cannot read '" + dir + "'"); - return; - } - - for (File file: files) { - if (!file.isFile() || !file.canRead()) { - continue; - } - String name = file.getName().toLowerCase(); - if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { - continue; - } - log.info("found file '" + file.getName() + "'"); - WstParser wstParser = new WstParser(); - wstParser.parse(file); - ImportWst iw = wstParser.getWst(); - iw.setKind(4); - iw.setDescription(FLOOD_WATER + "/" + iw.getDescription()); - floodWater.add(iw); - } - } - - public void parseOfficialLines() throws IOException { - if (Config.INSTANCE.skipOfficialLines()) { - log.info("skip parsing official lines"); - return; - } - - log.info("Parse official wst files"); - - File riverDir = wstFile.getParentFile().getParentFile(); - - for (String folder: OFFICIAL_LINES_FOLDERS) { - File dir = FileTools.repair(new File(riverDir, folder)); - - if (!dir.isDirectory() || !dir.canRead()) { - log.info("no directory '" + folder + "' found"); - continue; - } - - File file = FileTools.repair(new File(dir, OFFICIAL_LINES)); - if (!file.isFile() || !file.canRead()) { - log.warn("no official lines wst file found"); - continue; - } - log.debug("Found WST file: " + file); - - WstParser wstParser = new WstParser(); - wstParser.parse(file); - ImportWst iw = wstParser.getWst(); - iw.setKind(3); - iw.setDescription(folder + "/" + iw.getDescription()); - officialLines.add(iw); - } // for all folders - - } - - public void parseFixations() throws IOException { - if (Config.INSTANCE.skipFixations()) { - log.info("skip parsing fixations"); - return; - } - - log.info("Parse fixation wst files"); - - File riverDir = wstFile.getParentFile().getParentFile(); - - File fixDir = FileTools.repair( - new File(riverDir, FIXATIONS)); - - if (!fixDir.isDirectory() || !fixDir.canRead()) { - log.info("no fixation wst file directory found"); - return; - } - - File [] files = fixDir.listFiles(); - - if (files == null) { - log.warn("cannot read fixations wst file directory"); - return; - } - - for (File file: files) { - if (!file.isFile() || !file.canRead()) { - continue; - } - String name = file.getName().toLowerCase(); - if (!name.endsWith(".wst")) { - continue; - } - log.debug("Found WST file: " + file); - - WstParser wstParser = new WstParser(); - wstParser.parse(file); - ImportWst iw = wstParser.getWst(); - iw.setKind(2); - iw.setDescription(FIXATIONS+ "/" + iw.getDescription()); - fixations.add(iw); - } - } - - public void parseExtraWsts() throws IOException { - if (Config.INSTANCE.skipExtraWsts()) { - log.info("skip parsing extra WST files"); - return; - } - - log.info("Parse extra longitudinal wst files"); - - File riverDir = wstFile.getParentFile().getParentFile(); - - File extraDir = FileTools.repair( - new File(riverDir, EXTRA_LONGITUDINALS)); - - if (!extraDir.isDirectory() || !extraDir.canRead()) { - log.info("no extra longitudinal wst file directory found"); - return; - } - - File [] files = extraDir.listFiles(); - - if (files == null) { - log.warn("cannot read extra longitudinal wst file directory"); - return; - } - - for (File file: files) { - if (!file.isFile() || !file.canRead()) { - continue; - } - String name = file.getName().toLowerCase(); - if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { - continue; - } - log.debug("Found WST file: " + file); - - WstParser wstParser = new WstParser(); - wstParser.parse(file); - ImportWst iw = wstParser.getWst(); - iw.setKind(1); - iw.setDescription(EXTRA_LONGITUDINALS + "/" + iw.getDescription()); - extraWsts.add(iw); - } - - } - - public void parseWst() throws IOException { - if (Config.INSTANCE.skipWst()) { - log.info("skip parsing WST file"); - return; - } - - WstParser wstParser = new WstParser(); - wstParser.parse(wstFile); - wst = wstParser.getWst(); - } - - public void parseGauges() throws IOException { - if (Config.INSTANCE.skipGauges()) { - log.info("skip parsing gauges"); - return; - } - - File gltFile = new File(wstFile.getParentFile(), PEGEL_GLT); - gltFile = FileTools.repair(gltFile); - - if (!gltFile.isFile() || !gltFile.canRead()) { - log.warn("cannot read gauges from '" + gltFile + "'"); - return; - } - - PegelGltParser pgltp = new PegelGltParser(); - pgltp.parse(gltFile); - - gauges = pgltp.getGauges(); - - for (ImportGauge gauge: gauges) { - gauge.parseDependencies(); - } - } - - public void parseAnnotations() throws IOException { - if (Config.INSTANCE.skipAnnotations()) { - log.info("skip parsing annotations"); - return; - } - - File riverDir = wstFile.getParentFile().getParentFile(); - AnnotationsParser aparser = - new AnnotationsParser(annotationClassifier); - aparser.parse(riverDir); - - annotations = aparser.getAnnotations(); - } - - public void parseHYKs() { - if (Config.INSTANCE.skipHYKs()) { - log.info("skip parsing HYK files"); - return; - } - - log.info("looking for HYK files"); - HYKParser parser = new HYKParser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - parser.parseHYKs(riverDir, new HYKParser.Callback() { - - Set<HashedFile> hfs = new HashSet<HashedFile>(); - - @Override - public boolean hykAccept(File file) { - HashedFile hf = new HashedFile(file); - boolean success = hfs.add(hf); - if (!success) { - log.warn("HYK file '" + file + "' seems to be a duplicate."); - } - return success; - } - - @Override - public void hykParsed(HYKParser parser) { - log.debug("callback from HYK parser"); - ImportHYK hyk = parser.getHYK(); - hyk.setRiver(ImportRiver.this); - hyks.add(hyk); - } - }); - } - - - /** Add cross sections with description, years and lines to - * store. */ - private void addCrossSections(CrossSectionParser parser) { - String description = parser.getDescription(); - Integer year = parser.getYear(); - ImportTimeInterval ti = year != null - ? new ImportTimeInterval(yearToDate(year)) - : null; - - Map<Double, List<XY>> data = parser.getData(); - - List<ImportCrossSectionLine> lines = - new ArrayList<ImportCrossSectionLine>(data.size()); - - for (Map.Entry<Double, List<XY>> entry: data.entrySet()) { - Double km = entry.getKey(); - List<XY> points = entry.getValue(); - lines.add(new ImportCrossSectionLine(km, points)); - } - - crossSections.add(new ImportCrossSection( - ImportRiver.this, description, ti, lines)); - } - - /** Create a W80 Parser and parse w80 files found. */ - public void parseW80s() { - if (Config.INSTANCE.skipW80s()) { - log.info("skip parsing W80s"); - return; - } - W80Parser parser = new W80Parser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - ImportRiverCrossSectionParserCallback w80Callback = - new ImportRiverCrossSectionParserCallback("w80"); - parser.parseW80s(riverDir, w80Callback); - } - - /** Create a W80 Parser and parse w80 files found. */ - public void parseW80CSVs() { - if (Config.INSTANCE.skipW80CSVs()) { - log.info("skip parsing W80 csvs"); - return; - } - W80CSVParser parser = new W80CSVParser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - // Construct the Cross-Section-Data path. - File csDir = new File(riverDir.getPath() - + File.separator + "Geodaesie" - + File.separator + "Querprofile" - + File.separator + "QP-Daten"); - - ImportRiverCrossSectionParserCallback w80CSVCallback = - new ImportRiverCrossSectionParserCallback("w80-csv"); - parser.parseW80CSVs(csDir, w80CSVCallback); - } - - - /** - * Create and use a DA50Parser, parse the files found, add the - * ross-sections found. - */ - public void parseDA50s() { - if (Config.INSTANCE.skipDA50s()) { - log.info("skip parsing DA50s"); - return; - } - DA50Parser parser = new DA50Parser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - ImportRiverCrossSectionParserCallback da50Callback = - new ImportRiverCrossSectionParserCallback("da50"); - parser.parseDA50s(riverDir, da50Callback); - } - - - /** Create a DA66 Parser and parse the da66 files found. */ - // TODO this is a copy of parsePRFs, extract interfaces (e.g. CrossSectionParser). - public void parseDA66s() { - if (Config.INSTANCE.skipDA66s()) { - log.info("skip parsing DA66s"); - return; - } - - log.info("looking for DA66 files"); - DA66Parser parser = new DA66Parser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - ImportRiverCrossSectionParserCallback da66Callback = - new ImportRiverCrossSectionParserCallback("da66"); - parser.parseDA66s(riverDir, da66Callback); - } - - /** Create a PRFParser and let it parse the prf files found. */ - public void parsePRFs() { - if (Config.INSTANCE.skipPRFs()) { - log.info("skip parsing PRFs"); - return; - } - - log.info("looking for PRF files"); - PRFParser parser = new PRFParser(); - File riverDir = wstFile - .getParentFile() // Basisdaten - .getParentFile() // Hydrologie - .getParentFile(); // <river> - - ImportRiverCrossSectionParserCallback prfCallback = - new ImportRiverCrossSectionParserCallback("prf"); - parser.parsePRFs(riverDir, prfCallback); - } - - public static Date yearToDate(int year) { - Calendar cal = Calendar.getInstance(); - cal.set(year, 5, 15, 12, 0, 0); - long ms = cal.getTimeInMillis(); - cal.setTimeInMillis(ms - ms%1000); - return cal.getTime(); - } - - public void storeDependencies() { - storeWstUnit(); - storeAnnotations(); - storeHYKs(); - storeCrossSections(); - storeGauges(); - storeWst(); - storeExtraWsts(); - storeFixations(); - storeOfficialLines(); - storeFloodWater(); - storeFloodProtection(); - storeBedHeight(); - storeSedimentDensity(); - storeMorphologicalWidth(); - storeFlowVelocity(); - storeSedimentYield(); - storeWaterlevels(); - storeWaterlevelDifferences(); - storeMeasurementStations(); - storeSQRelations(); - storeOfficialNumber(); - } - - public void storeWstUnit() { - if (wst == null) { - wstUnit = new ImportUnit("NN + m"); - } - else { - wstUnit = wst.getUnit(); - } - } - - public void storeHYKs() { - if (!Config.INSTANCE.skipHYKs()) { - log.info("store HYKs"); - getPeer(); - for (ImportHYK hyk: hyks) { - hyk.storeDependencies(); - } - } - } - - public void storeCrossSections() { - if (!Config.INSTANCE.skipPRFs() - || !Config.INSTANCE.skipDA66s() - || !Config.INSTANCE.skipDA50s() - || !Config.INSTANCE.skipW80s() - || !Config.INSTANCE.skipW80CSVs()) { - log.info("store cross sections"); - getPeer(); - for (ImportCrossSection crossSection: crossSections) { - crossSection.storeDependencies(); - } - } - } - - public void storeWst() { - if (!Config.INSTANCE.skipWst()) { - River river = getPeer(); - wst.storeDependencies(river); - } - } - - public void storeFixations() { - if (!Config.INSTANCE.skipFixations()) { - log.info("store fixation wsts"); - River river = getPeer(); - for (ImportWst fWst: fixations) { - log.debug("Fixation name: " + fWst.getDescription()); - fWst.storeDependencies(river); - } - } - } - - - /** Store wsts from waterlevel-csv files. */ - public void storeWaterlevels() { - if (!Config.INSTANCE.skipWaterlevels()) - - log.info("store waterlevel wsts from csv"); - River river = getPeer(); - for (ImportWst wWst: waterlevels) { - log.debug("Waterlevel name: " + wWst.getDescription()); - wWst.storeDependencies(river); - } - } - - - /** Store wsts from waterleveldifference-csv files. */ - public void storeWaterlevelDifferences() { - if (!Config.INSTANCE.skipWaterlevelDifferences()) - - log.info("store waterleveldifferences wsts from csv"); - River river = getPeer(); - for (ImportWst dWst: waterlevelDifferences) { - log.debug("water.diff.: name " + dWst.getDescription()); - dWst.storeDependencies(river); - } - } - - - public void storeExtraWsts() { - if (!Config.INSTANCE.skipExtraWsts()) { - log.info("store extra wsts"); - River river = getPeer(); - for (ImportWst wst: extraWsts) { - log.debug("name: " + wst.getDescription()); - wst.storeDependencies(river); - } - } - } - - public void storeOfficialLines() { - if (!Config.INSTANCE.skipOfficialLines()) { - log.info("store official lines wsts"); - River river = getPeer(); - for (ImportWst wst: officialLines) { - log.debug("name: " + wst.getDescription()); - wst.storeDependencies(river); - } - } - } - - public void storeFloodWater() { - if (!Config.INSTANCE.skipFloodWater()) { - log.info("store flood water wsts"); - River river = getPeer(); - for (ImportWst wst: floodWater) { - log.debug("name: " + wst.getDescription()); - wst.storeDependencies(river); - } - } - } - - - public void storeFloodProtection() { - if (!Config.INSTANCE.skipFloodProtection()) { - log.info("store flood protection wsts"); - River river = getPeer(); - for (ImportWst wst: floodProtection) { - log.debug("name: " + wst.getDescription()); - wst.storeDependencies(river); - } - } - } - - - public void storeBedHeight() { - if (!Config.INSTANCE.skipBedHeightSingle()) { - log.info("store bed heights single"); - storeBedHeightSingle(); - } - - if (!Config.INSTANCE.skipBedHeightEpoch()) { - log.info("store bed height epoch."); - storeBedHeightEpoch(); - } - } - - - private void storeBedHeightSingle() { - River river = getPeer(); - - if (bedHeightSingles != null) { - for (ImportBedHeight tmp: bedHeightSingles) { - ImportBedHeightSingle single = (ImportBedHeightSingle) tmp; - - String desc = single.getDescription(); - - log.debug("name: " + desc); - - single.storeDependencies(river); - - } - } - else { - log.info("No single bed heights to store."); - } - } - - - private void storeBedHeightEpoch() { - River river = getPeer(); - - if (bedHeightEpochs != null) { - for (ImportBedHeight tmp: bedHeightEpochs) { - ImportBedHeightEpoch epoch = (ImportBedHeightEpoch) tmp; - - String desc = epoch.getDescription(); - - log.debug("name: " + desc); - - epoch.storeDependencies(river); - - } - } - else { - log.info("No epoch bed heights to store."); - } - } - - public void storeSedimentDensity() { - if (!Config.INSTANCE.skipSedimentDensity()) { - log.info("store sediment density"); - - River river = getPeer(); - - for (ImportSedimentDensity density: sedimentDensities) { - String desc = density.getDescription(); - - log.debug("name: " + desc); - - density.storeDependencies(river); - - } - } - } - - public void storeMorphologicalWidth() { - if (!Config.INSTANCE.skipMorphologicalWidth()) { - log.info("store morphological width"); - - River river = getPeer(); - - for (ImportMorphWidth width: morphologicalWidths) { - - width.storeDependencies(river); - - } - } - } - - public void storeFlowVelocity() { - if (!Config.INSTANCE.skipFlowVelocity()) { - log.info("store flow velocity"); - - River river = getPeer(); - - for (ImportFlowVelocityModel flowVelocityModel: flowVelocityModels){ - - flowVelocityModel.storeDependencies(river); - - } - - for (ImportFlowVelocityMeasurement m: flowVelocityMeasurements) { - - m.storeDependencies(river); - - } - } - } - - - public void storeSedimentYield() { - if (!Config.INSTANCE.skipSedimentYield()) { - log.info("store sediment yield data"); - - River river = getPeer(); - - for (ImportSedimentYield sedimentYield: sedimentYields) { - - sedimentYield.storeDependencies(river); - - } - } - } - - - public void storeMeasurementStations() { - if (!Config.INSTANCE.skipMeasurementStations()) { - log.info("store measurement stations"); - - River river = getPeer(); - - int count = 0; - - for (ImportMeasurementStation station: measurementStations) { - - boolean success = station.storeDependencies(river); - if (success) { - count++; - } - - } - - log.info("stored " + count + " measurement stations."); - } - } - - - public void storeSQRelations() { - if (!Config.INSTANCE.skipSQRelation()) { - log.info("store sq relations"); - - River river = getPeer(); - - int count = 0; - - for (ImportSQRelation sqRelation: sqRelations) { - - sqRelation.storeDependencies(river); - count++; - - } - - log.info("stored " + count + " sq relations."); - } - } - - - public void storeAnnotations() { - if (!Config.INSTANCE.skipAnnotations()) { - River river = getPeer(); - for (ImportAnnotation annotation: annotations) { - annotation.getPeer(river); - } - } - } - - public void storeGauges() { - if (!Config.INSTANCE.skipGauges()) { - log.info("store gauges:"); - River river = getPeer(); - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - for (ImportGauge gauge: gauges) { - log.info("\tgauge: " + gauge.getName()); - gauge.storeDependencies(river); - ImporterSession.getInstance().getDatabaseSession(); - session.flush(); - } - } - } - - public River getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from River where name=:name"); - - Unit u = null; - if (wstUnit != null) { - u = wstUnit.getPeer(); - } - - query.setString("name", name); - List<River> rivers = query.list(); - if (rivers.isEmpty()) { - log.info("Store new river '" + name + "'"); - peer = new River(name, u); - if (!Config.INSTANCE.skipBWASTR()) { - peer.setOfficialNumber(officialNumber); - } - session.save(peer); - } - else { - peer = rivers.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSQRelation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,109 +0,0 @@ -package de.intevation.flys.importer; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.exception.ConstraintViolationException; - -import de.intevation.flys.model.River; -import de.intevation.flys.model.SQRelation; -import de.intevation.flys.model.TimeInterval; - - -public class ImportSQRelation { - - private static Logger log = Logger.getLogger(ImportSQRelation.class); - - private ImportTimeInterval timeInterval; - - private String description; - - private List<ImportSQRelationValue> values; - - private SQRelation peer; - - public ImportSQRelation() { - this.values = new ArrayList<ImportSQRelationValue>(); - } - - public void storeDependencies(River river) { - log.info("store dependencies"); - - SQRelation peer = getPeer(river); - - if (peer != null) { - int count = 0; - - for (ImportSQRelationValue value : values) { - try { - value.storeDependencies(peer); - count++; - } - catch (SQLException sqle) { - log.warn("ISQ: Unable to store sq relation value.", sqle); - } - catch (ConstraintViolationException cve) { - log.warn("ISQ: Unable to store sq relation value.", cve); - } - } - - log.info("stored " + count + " sq relation values."); - } - } - - public SQRelation getPeer(River river) { - log.debug("getPeer()"); - - if (peer == null) { - TimeInterval timeInter = timeInterval.getPeer(); - - if (timeInter == null) { - log.warn("ISQ: Cannot determine sq relation without time interval"); - return null; - } - - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - Query query = session - .createQuery("FROM SQRelation WHERE river=:river AND timeInterval=:timeInter"); - - query.setParameter("river", river); - query.setParameter("timeInter", timeInter); - - List<SQRelation> sq = query.list(); - - if (sq.isEmpty()) { - log.info("create new SQ relation '" + description + "'"); - - peer = new SQRelation(river, timeInter, description); - session.save(peer); - } - else { - peer = sq.get(0); - } - } - - return peer; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - public void addValue(ImportSQRelationValue value) { - if (value != null) { - this.values.add(value); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSQRelationValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,140 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; -import java.sql.SQLException; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.exception.ConstraintViolationException; - -import de.intevation.flys.model.MeasurementStation; -import de.intevation.flys.model.SQRelation; -import de.intevation.flys.model.SQRelationValue; - - -public class ImportSQRelationValue { - - private static Logger log = Logger.getLogger(ImportSQRelationValue.class); - - - private SQRelationValue peer; - - private String parameter; - - private Double km; - private Double a; - private Double b; - private Double qMax; - private Double rSQ; - private Integer nTot; - private Integer nOutlier; - private Double cFerguson; - private Double cDuan; - - - public ImportSQRelationValue( - String parameter, - Double km, - Double a, - Double b, - Double qMax, - Double rSQ, - Integer nTot, - Integer nOutlier, - Double cFerguson, - Double cDuan - ) { - this.parameter = parameter; - this.km = km; - this.a = a; - this.b = b; - this.qMax = qMax; - this.rSQ = rSQ; - this.nTot = nTot; - this.nOutlier = nOutlier; - this.cFerguson = cFerguson; - this.cDuan = cDuan; - } - - - public void storeDependencies(SQRelation owner) - throws SQLException, ConstraintViolationException - { - getPeer(owner); - } - - - public SQRelationValue getPeer(SQRelation owner) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from MeasurementStation " + - " where station between :kml and :kmh"); - query.setDouble("kml", km - 1e-4); - query.setDouble("kmh", km + 1e-4); - - List<MeasurementStation> result = query.list(); - - if (result.isEmpty()) { - log.error("No measurement stations found at km " + km); - return null; - } - - Query query2 = session.createQuery( - "from SQRelationValue " + - " where sqRelation=:owner " + - " and parameter=:parameter" + - " and measurementStation=:measurementStation" + - " and a=:a" + - " and b=:b" + - " and qMax=:qMax" + - " and rSQ=:rSQ" + - " and cFerguson=:cFerguson" + - " and cDuan=:cDuan"); - - query2.setParameter("owner", owner); - query2.setString("parameter", parameter); - query2.setParameter("measurementStation", result.get(0)); - query2.setBigDecimal("a", toBigDecimal(a)); - query2.setBigDecimal("b", toBigDecimal(b)); - query2.setBigDecimal("qMax", toBigDecimal(qMax)); - query2.setBigDecimal("rSQ", toBigDecimal(rSQ)); - query2.setBigDecimal("cFerguson", toBigDecimal(cFerguson)); - query2.setBigDecimal("cDuan", toBigDecimal(cDuan)); - - List<SQRelationValue> values = query2.list(); - - if (values.isEmpty()) { - peer = new SQRelationValue( - owner, - parameter, - result.get(0), - a, - b, - qMax, - rSQ, - nTot, - nOutlier, - cFerguson, - cDuan - ); - - session.save(peer); - } - else { - peer = values.get(0); - } - } - return peer; - } - - private static final BigDecimal toBigDecimal(Double x) { - if (x == null) return null; - return new BigDecimal(x); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSedimentDensity.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,97 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.hibernate.Query; -import org.hibernate.Session; - -import de.intevation.flys.model.River; -import de.intevation.flys.model.SedimentDensity; - - -public class ImportSedimentDensity { - - private static Logger log = Logger.getLogger(ImportSedimentDensity.class); - - protected SedimentDensity peer; - - protected ImportDepth depth; - - protected String description; - - protected List<ImportSedimentDensityValue> values; - - public ImportSedimentDensity(String description) { - this.description = description; - this.values = new ArrayList<ImportSedimentDensityValue>(); - } - - public String getDescription() { - return description; - } - - public void setDepth(ImportDepth depth) { - this.depth = depth; - } - - public void addValue(ImportSedimentDensityValue value) { - values.add(value); - } - - public void storeDependencies(River river) { - log.info("store dependencies"); - - if (depth != null) { - depth.storeDependencies(); - } - - SedimentDensity peer = getPeer(river); - - if (peer != null) { - log.info("store sediment density values."); - for (ImportSedimentDensityValue value : values) { - value.storeDependencies(peer); - } - } - } - - public SedimentDensity getPeer(River river) { - log.info("get peer"); - - if (depth == null) { - log.warn("cannot store sediment density '" + description - + "': no depth"); - return null; - } - - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - - Query query = session.createQuery("from SedimentDensity where " - + " river=:river and " + " depth=:depth"); - - query.setParameter("river", river); - query.setParameter("depth", depth.getPeer()); - - List<SedimentDensity> density = query.list(); - - if (density.isEmpty()) { - log.debug("Create new SedimentDensity DB instance."); - - peer = new SedimentDensity(river, depth.getPeer(), - description); - - session.save(peer); - } - else { - peer = density.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSedimentDensityValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,101 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.SedimentDensity; -import de.intevation.flys.model.SedimentDensityValue; - - -public class ImportSedimentDensityValue { - - private static final Logger log = - Logger.getLogger(ImportSedimentDensityValue.class); - - - protected SedimentDensityValue peer; - - protected BigDecimal station; - - protected BigDecimal shoreOffset; - - protected BigDecimal density; - - private BigDecimal year; - - protected String description; - - - public ImportSedimentDensityValue( - BigDecimal station, - BigDecimal shoreOffset, - BigDecimal density, - BigDecimal year, - String description - ) { - this.station = station; - this.shoreOffset = shoreOffset; - this.density = density; - this.year = year; - this.description = description; - } - - - public void storeDependencies(SedimentDensity sedimentDensity) { - log.info("store dependencies"); - - getPeer(sedimentDensity); - } - - - public SedimentDensityValue getPeer(SedimentDensity sedimentDensity) { - log.info("get peer"); - - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - - Query query = session.createQuery( - "from SedimentDensityValue where " + - " sedimentDensity=:sedimentDensity and " + - " station=:station and " + - " shoreOffset=:shoreOffset and " + - " density=:density and " + - " year=:year and " + - " description=:description"); - - query.setParameter("sedimentDensity", sedimentDensity); - query.setParameter("station", station); - query.setParameter("shoreOffset", shoreOffset); - query.setParameter("density", density); - query.setParameter("year", year); - query.setParameter("description", description); - - List<SedimentDensityValue> values = query.list(); - if (values.isEmpty()) { - log.debug("Create new SedimentDensityValue DB instance."); - - peer = new SedimentDensityValue( - sedimentDensity, - station, - shoreOffset, - density, - year, - description); - - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSedimentYield.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,121 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.GrainFraction; -import de.intevation.flys.model.River; -import de.intevation.flys.model.SedimentYield; -import de.intevation.flys.model.TimeInterval; -import de.intevation.flys.model.Unit; - - -public class ImportSedimentYield { - - private static Logger log = Logger.getLogger(ImportSedimentYield.class); - - private ImportGrainFraction grainFraction; - - private ImportUnit unit; - - private ImportTimeInterval timeInterval; - - private String description; - - private List<ImportSedimentYieldValue> values; - - private SedimentYield peer; - - public ImportSedimentYield(String description) { - this.values = new ArrayList<ImportSedimentYieldValue>(); - this.description = description; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - public void setUnit(ImportUnit unit) { - this.unit = unit; - } - - public void setGrainFraction(ImportGrainFraction grainFraction) { - this.grainFraction = grainFraction; - } - - public void addValue(ImportSedimentYieldValue value) { - this.values.add(value); - } - - public void storeDependencies(River river) { - log.debug("store dependencies"); - - if (grainFraction != null) { - grainFraction.storeDependencies(); - } - - SedimentYield peer = getPeer(river); - - if (peer != null) { - int i = 0; - - for (ImportSedimentYieldValue value : values) { - value.storeDependencies(peer); - i++; - } - - log.info("stored " + i + " sediment yield values."); - } - } - - public SedimentYield getPeer(River river) { - log.debug("get peer"); - - GrainFraction gf = grainFraction != null ? grainFraction.getPeer() - : null; - - Unit u = unit != null ? unit.getPeer() : null; - - TimeInterval ti = timeInterval != null ? timeInterval.getPeer() : null; - - if (ti == null || u == null) { - log.warn("Skip invalid SedimentYield: time interval or unit null!"); - return null; - } - - if (peer == null) { - Session session = ImporterSession.getInstance() - .getDatabaseSession(); - Query query = session.createQuery("from SedimentYield where " - + " river=:river and " - + " grainFraction=:grainFraction and " + " unit=:unit and " - + " timeInterval=:timeInterval and " - + " description=:description"); - - query.setParameter("river", river); - query.setParameter("grainFraction", gf); - query.setParameter("unit", u); - query.setParameter("timeInterval", ti); - query.setParameter("description", description); - - List<SedimentYield> yields = query.list(); - if (yields.isEmpty()) { - log.debug("create new SedimentYield"); - - peer = new SedimentYield(river, u, ti, gf, description); - session.save(peer); - } - else { - peer = yields.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportSedimentYieldValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.SedimentYield; -import de.intevation.flys.model.SedimentYieldValue; - - -public class ImportSedimentYieldValue { - - private Double station; - private Double value; - - private SedimentYieldValue peer; - - - public ImportSedimentYieldValue(Double station, Double value) { - this.station = station; - this.value = value; - } - - - public void storeDependencies(SedimentYield sedimentYield) { - getPeer(sedimentYield); - } - - - public SedimentYieldValue getPeer(SedimentYield sedimentYield) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from SedimentYieldValue where " + - " sedimentYield=:sedimentYield and " + - " station=:station and " + - " value=:value" - ); - - query.setParameter("sedimentYield", sedimentYield); - query.setParameter("station", station); - query.setParameter("value", value); - - List<SedimentYieldValue> values = query.list(); - if (values.isEmpty()) { - peer = new SedimentYieldValue(sedimentYield, station, value); - session.save(peer); - } - else { - peer = values.get(0); - } - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportTimeInterval.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,98 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.TimeInterval; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; -import java.util.Date; - -import org.apache.log4j.Logger; - -public class ImportTimeInterval -{ - private static Logger log = Logger.getLogger(ImportTimeInterval.class); - - protected Date startTime; - protected Date stopTime; - - protected TimeInterval peer; - - public ImportTimeInterval() { - } - - public ImportTimeInterval(Date startTime) { - this.startTime = startTime; - this.stopTime = null; - } - - public ImportTimeInterval(Date startTime, Date stopTime) { - Date start; - Date stop; - if (startTime == null) { - start = stopTime; - stop = null; - } - else { - start = startTime; - stop = stopTime; - } - - if (stop != null && start.after(stop)) { - this.stopTime = start; - this.startTime = stop; - } - else { - this.startTime = start; - this.stopTime = stop; - } - } - - public Date getStartTime() { - return startTime; - } - - public void setStartTime(Date startTime) { - this.startTime = startTime; - } - - public Date getStopTime() { - return stopTime; - } - - public void setStopTime(Date stopTime) { - this.stopTime = stopTime; - } - - public TimeInterval getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - if (startTime == null) { - log.error("Null Start time will be ignored."); - } - Query query; - if (stopTime == null) { - query = session.createQuery( - "from TimeInterval where startTime=:a and stopTime is null"); - } - else { - query = session.createQuery( - "from TimeInterval where startTime=:a and stopTime=:b"); - query.setParameter("b", stopTime); - } - query.setParameter("a", startTime); - - List<TimeInterval> intervals = query.list(); - if (intervals.isEmpty()) { - peer = new TimeInterval(startTime, stopTime); - session.save(peer); - } - else { - peer = intervals.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportUnit.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.List; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.model.Unit; - - -public class ImportUnit -{ - private static final Logger log = Logger.getLogger(ImportUnit.class); - - protected String name; - - protected Unit peer; - - - public ImportUnit(String name) { - this.name = name; - } - - - public String getName() { - return name; - } - - - public Unit getPeer() { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery("from Unit where name=:name"); - query.setParameter("name", name); - - List<Unit> units = query.list(); - if (units.isEmpty()) { - log.info("Store new unit '" + name + "'"); - - peer = new Unit(name); - session.save(peer); - } - else { - peer = units.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportWst.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,130 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Wst; -import de.intevation.flys.model.River; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.ArrayList; -import java.util.List; - -public class ImportWst -{ - private static Logger log = Logger.getLogger(ImportWst.class); - - protected String description; - - protected Integer kind; - - protected List<ImportWstColumn> columns; - - protected ImportUnit unit; - - /** Wst as in db. */ - protected Wst peer; - - public ImportWst() { - kind = 0; - columns = new ArrayList<ImportWstColumn>(); - } - - public ImportWst(String description) { - this(); - this.description = description; - } - - public String getDescription() { - return description; - } - - public Integer getKind() { - return kind; - } - - public void setKind(Integer kind) { - this.kind = kind; - } - - - public void setDescription(String description) { - this.description = description; - } - - /** Create columns that can be accessed with getColumn. */ - public void setNumberColumns(int numColumns) { - for (int i = 0; i < numColumns; ++i) { - columns.add(new ImportWstColumn(this, null, null, i)); - } - } - - public int getNumberColumns() { - return columns.size(); - } - - public ImportWstColumn getColumn(int index) { - return columns.get(index); - } - - public List<ImportWstColumn> getColumns() { - return columns; - } - - /** Adds a column. Assumes that columns wst is this instance. */ - public void addColumn(ImportWstColumn column) { - columns.add(column); - } - - public ImportUnit getUnit() { - return unit; - } - - public void setUnit(ImportUnit unit) { - this.unit = unit; - } - - public void storeDependencies(River river) { - - log.info("store '" + description + "'"); - Wst wst = getPeer(river); - - for (ImportWstColumn column: columns) { - column.storeDependencies(river); - } - - Session session = ImporterSession.getInstance().getDatabaseSession(); - session.flush(); - } - - public void fixRangesOrder() { - for (ImportWstColumn column: columns) { - column.fixRangesOrder(); - } - } - - /** Get corresponding mapped wst (from database). */ - public Wst getPeer(River river) { - if (peer == null) { - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from Wst where " + - "river=:river and description=:description and kind=:kind"); - query.setParameter("river", river); - query.setParameter("description", description); - query.setParameter("kind", kind); - List<Wst> wsts = query.list(); - if (wsts.isEmpty()) { - peer = new Wst(river, description, kind); - session.save(peer); - } - else { - peer = wsts.get(0); - } - - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportWstColumn.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,160 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.Wst; -import de.intevation.flys.model.WstColumn; -import de.intevation.flys.model.River; -import de.intevation.flys.model.TimeInterval; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; -import java.util.ArrayList; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - - -/** Unmapped column of a WST. */ -public class ImportWstColumn -{ - private static Logger log = Logger.getLogger(ImportWstColumn.class); - - protected ImportWst wst; - protected String name; - protected String description; - protected Integer position; - - protected ImportTimeInterval timeInterval; - - protected List<ImportWstColumnQRange> columnQRanges; - protected List<ImportWstColumnValue> columnValues; - - protected WstColumn peer; - - public ImportWstColumn() { - columnQRanges = new ArrayList<ImportWstColumnQRange>(); - columnValues = new ArrayList<ImportWstColumnValue>(); - } - - public ImportWstColumn( - ImportWst wst, - String name, - String description, - Integer position - ) { - this(); - this.wst = wst; - this.name = name; - this.description = description; - this.position = position; - } - - public ImportWst getWst() { - return wst; - } - - public void setWst(ImportWst wst) { - this.wst = wst; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Integer getPosition() { - return position; - } - - public void setPosition(Integer position) { - this.position = position; - } - - public void addColumnValue(BigDecimal position, BigDecimal w) { - columnValues.add( - new ImportWstColumnValue(this, position, w)); - } - - public void addColumnQRange(ImportWstQRange columnQRange) { - columnQRanges.add( - new ImportWstColumnQRange(this, columnQRange)); - } - - - /** Get the Column Values stored in this column. */ - public List<ImportWstColumnValue> getColumnValues() { - return columnValues; - } - - - public void storeDependencies(River river) { - log.info("store column '" + name + "'"); - WstColumn column = getPeer(river); - - for (ImportWstColumnQRange columnQRange: columnQRanges) { - columnQRange.getPeer(river); - } - - for (ImportWstColumnValue columnValue: columnValues) { - columnValue.getPeer(river); - } - } - - public ImportTimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(ImportTimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - /** Get corresponding mapped wst-column (from database). */ - public WstColumn getPeer(River river) { - if (peer == null) { - Wst w = wst.getPeer(river); - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from WstColumn where " + - "wst=:wst and name=:name and description=:description" + - " and position=:position"); - query.setParameter("wst", w); - query.setParameter("name", name); - query.setParameter("description", description); - query.setParameter("position", position); - - TimeInterval ti = timeInterval != null - ? timeInterval.getPeer() - : null; - - List<WstColumn> columns = query.list(); - if (columns.isEmpty()) { - peer = new WstColumn(w, name, description, position, ti); - session.save(peer); - } - else { - peer = columns.get(0); - } - } - return peer; - } - - public void fixRangesOrder() { - for (ImportWstColumnQRange wcqr: columnQRanges) { - wcqr.fixRangesOrder(); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportWstColumnQRange.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.WstColumnQRange; -import de.intevation.flys.model.WstQRange; -import de.intevation.flys.model.WstColumn; -import de.intevation.flys.model.River; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportWstColumnQRange -{ - protected ImportWstColumn wstColumn; - protected ImportWstQRange qRange; - - protected WstColumnQRange peer; - - public ImportWstColumnQRange() { - } - - public ImportWstColumnQRange( - ImportWstColumn wstColumn, - ImportWstQRange qRange - ) { - this.wstColumn = wstColumn; - this.qRange = qRange; - } - - public ImportWstColumn getWstColumn() { - return wstColumn; - } - - public void setWstColumn(ImportWstColumn wstColumn) { - this.wstColumn = wstColumn; - } - - public ImportWstQRange getQRange() { - return qRange; - } - - public void setQRange(ImportWstQRange qRange) { - this.qRange = qRange; - } - - public void fixRangesOrder() { - qRange.fixRangesOrder(); - } - - public WstColumnQRange getPeer(River river) { - if (peer == null) { - WstColumn c = wstColumn.getPeer(river); - WstQRange q = qRange.getPeer(river); - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from WstColumnQRange where " + - "wstColumn=:c and wstQRange=:q"); - query.setParameter("c", c); - query.setParameter("q", q); - List<WstColumnQRange> cols = query.list(); - if (cols.isEmpty()) { - peer = new WstColumnQRange(c, q); - session.save(peer); - } - else { - peer = cols.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportWstColumnValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.flys.model.WstColumnValue; -import de.intevation.flys.model.WstColumn; -import de.intevation.flys.model.River; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -public class ImportWstColumnValue -{ - protected Logger logger = Logger.getLogger(ImportWstColumnValue.class); - - protected BigDecimal position; - protected BigDecimal w; - protected ImportWstColumn wstColumn; - - protected WstColumnValue peer; - - public ImportWstColumnValue() { - } - - public ImportWstColumnValue( - ImportWstColumn wstColumn, - BigDecimal position, - BigDecimal w - ) { - this.wstColumn = wstColumn; - this.position = position; - this.w = w; - } - - public BigDecimal getPosition() { - return position; - } - - public void setPosition(BigDecimal position) { - this.position = position; - } - - public BigDecimal getW() { - return w; - } - - public void setW(BigDecimal w) { - this.w = w; - } - - public ImportWstColumn getWstColumn() { - return wstColumn; - } - - public void setWstColumn(ImportWstColumn wstColumn) { - this.wstColumn = wstColumn; - } - - public WstColumnValue getPeer(River river) { - if (peer == null) { - WstColumn c = wstColumn.getPeer(river); - peer = ImporterSession.getInstance().getWstColumnValue( - c, position, w); - } - - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImportWstQRange.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import de.intevation.flys.model.WstQRange; -import de.intevation.flys.model.River; -import de.intevation.flys.model.Range; - -import org.hibernate.Session; -import org.hibernate.Query; - -import java.util.List; - -public class ImportWstQRange -{ - protected ImportRange range; - protected BigDecimal q; - - protected WstQRange peer; - - public ImportWstQRange() { - } - - public ImportWstQRange( - ImportRange range, - BigDecimal q - ) { - this.range = range; - this.q = q; - } - - public ImportRange getRange() { - return range; - } - - public void setRange(ImportRange range) { - this.range = range; - } - - public BigDecimal getQ() { - return q; - } - - public void setQ(BigDecimal q) { - this.q = q; - } - - public void fixRangesOrder() { - range.fixRangesOrder(); - } - - public WstQRange getPeer(River river) { - if (peer == null) { - Range r = range.getPeer(river); - Session session = ImporterSession.getInstance().getDatabaseSession(); - Query query = session.createQuery( - "from WstQRange where " + - "range=:range and q=:q"); - query.setParameter("range", r); - query.setParameter("q", q); - List<WstQRange> wstQRanges = query.list(); - if (wstQRanges.isEmpty()) { - peer = new WstQRange(r, q); - session.save(peer); - } - else { - peer = wstQRanges.get(0); - } - } - return peer; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/Importer.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,200 +0,0 @@ -package de.intevation.flys.importer; - -import de.intevation.artifacts.common.utils.XMLUtils; - -import de.intevation.flys.importer.parsers.AnnotationClassifier; -import de.intevation.flys.importer.parsers.BundesWasserStrassenParser; -import de.intevation.flys.importer.parsers.InfoGewParser; - -import java.io.File; -import java.io.IOException; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import java.sql.SQLException; - -import org.apache.log4j.Logger; - -import org.hibernate.Transaction; -import org.hibernate.HibernateException; - -import org.w3c.dom.Document; - -import de.intevation.flys.utils.StringUtil; - -/** Data Importer. Further processing happens per-river. */ -public class Importer -{ - /** Private logger. */ - private static Logger log = Logger.getLogger(Importer.class); - - private static String BWASTR_ID_CSV_FILE = "BWASTR_ID.csv"; - - protected List<ImportRiver> rivers; - - public Importer() { - } - - public Importer(List<ImportRiver> rivers) { - this.rivers = rivers; - } - - public List<ImportRiver> getRivers() { - return rivers; - } - - public void setRivers(List<ImportRiver> rivers) { - this.rivers = rivers; - } - - /** Write rivers and their dependencies/dependants to db. */ - public void writeRivers() { - log.debug("write rivers started"); - - for (ImportRiver river: rivers) { - log.debug("writing river '" + river.getName() + "'"); - river.storeDependencies(); - ImporterSession.getInstance().getDatabaseSession().flush(); - } - - log.debug("write rivers finished"); - } - - public void writeToDatabase() { - - Transaction tx = null; - - try { - tx = ImporterSession.getInstance() - .getDatabaseSession().beginTransaction(); - - try { - writeRivers(); - } - catch (HibernateException he) { - Throwable t = he.getCause(); - while (t instanceof SQLException) { - SQLException sqle = (SQLException) t; - log.error("SQL exeception chain:", sqle); - t = sqle.getNextException(); - } - throw he; - } - - tx.commit(); - } - catch (RuntimeException re) { - if (tx != null) { - tx.rollback(); - } - throw re; - } - } - - public static AnnotationClassifier getAnnotationClassifier() { - String annotationTypes = Config.INSTANCE.getAnnotationTypes(); - - if (annotationTypes == null) { - log.info("no annotation types file configured."); - return null; - } - - File file = new File(annotationTypes); - - log.info("use annotation types file '" + file + "'"); - - if (!(file.isFile() && file.canRead())) { - log.warn("annotation type file '" + file + "' is not readable."); - return null; - } - - Document rules = XMLUtils.parseDocument(file); - - if (rules == null) { - log.warn("cannot parse annotation types file."); - return null; - } - - return new AnnotationClassifier(rules); - } - - - /** Starting point for importing river data. */ - public static void main(String [] args) { - - InfoGewParser infoGewParser = new InfoGewParser( - getAnnotationClassifier()); - - log.info("Start parsing rivers..."); - - File bwastrFile = null; - - for (String gew: args) { - log.info("parsing info gew file: " + gew); - File gewFile = new File(gew); - if (bwastrFile == null) { - bwastrFile = new File(gewFile.getParentFile(), BWASTR_ID_CSV_FILE); - } - try { - infoGewParser.parse(gewFile); - } - catch (IOException ioe) { - log.error("error while parsing gew: " + gew, ioe); - System.exit(1); - } - } - - String gew = Config.INSTANCE.getInfoGewFile(); - if (gew != null && gew.length() > 0) { - log.info("parsing info gew file: " + gew); - File gewFile = new File(gew); - if (bwastrFile == null) { - bwastrFile = new File(gewFile.getParentFile(), BWASTR_ID_CSV_FILE); - } - try { - infoGewParser.parse(gewFile); - } - catch (IOException ioe) { - log.error("error while parsing gew: " + gew, ioe); - System.exit(1); - } - } - - // Look for official numbers. - BundesWasserStrassenParser bwastrIdParser = - new BundesWasserStrassenParser(); - - // Read bwastFile (river-dir + BWASTR_ID_CSV_FILE). - if (!Config.INSTANCE.skipBWASTR()) { - try{ - bwastrIdParser.parse(bwastrFile); - HashMap<String,Long> map = bwastrIdParser.getMap(); - - // Now link rivers with official numbers. - for(ImportRiver river: infoGewParser.getRivers()) { - for(Map.Entry<String, Long> entry: map.entrySet()) { - if (StringUtil.containsIgnoreCase(entry.getKey(), river.getName())) { - river.setOfficialNumber(entry.getValue()); - log.debug(river.getName() + " is mapped to bwastr " + entry.getValue()); - } - } - } - } catch (IOException ioe) { - log.warn("BWASTR-file could not be loaded."); - } - } - else { - log.debug("skip reading BWASTR_ID.csv"); - } - - if (!Config.INSTANCE.dryRun()) { - new Importer(infoGewParser.getRivers()).writeToDatabase(); - } - else { - log.info("Dry run, not writing to database."); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ImporterSession.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,187 +0,0 @@ -package de.intevation.flys.importer; - -import java.util.Iterator; -import java.util.Map; -import java.util.TreeMap; - -import java.math.BigDecimal; - -import org.hibernate.SessionFactory; -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.FlushMode; - -import de.intevation.flys.backend.SessionFactoryProvider; - -import de.intevation.flys.model.WstColumnValue; -import de.intevation.flys.model.WstColumn; -import de.intevation.flys.model.DischargeTableValue; -import de.intevation.flys.model.DischargeTable; -import de.intevation.flys.model.Range; -import de.intevation.flys.model.River; - -import org.apache.log4j.Logger; - -import de.intevation.artifacts.common.utils.LRUCache; - -public class ImporterSession -{ - private static Logger log = Logger.getLogger(ImporterSession.class); - - private static final ThreadLocal<ImporterSession> SESSION = - new ThreadLocal<ImporterSession>() { - @Override - protected ImporterSession initialValue() { - return new ImporterSession(); - } - }; - - protected Session databaseSession; - - protected LRUCache<Integer, Map<ValueKey, WstColumnValue>> - wstColumnValues; - - protected LRUCache<Integer, Map<ValueKey, DischargeTableValue>> - dischargeTableValues; - - protected LRUCache<Integer, Map<ValueKey, Range>> - ranges; - - public static ImporterSession getInstance() { - return SESSION.get(); - } - - public ImporterSession() { - SessionFactory sessionFactory = - SessionFactoryProvider.createSessionFactory(); - databaseSession = sessionFactory.openSession(); - //databaseSession.setFlushMode(FlushMode.MANUAL); - - wstColumnValues = - new LRUCache<Integer, Map<ValueKey, WstColumnValue>>(); - - dischargeTableValues = - new LRUCache<Integer, Map<ValueKey, DischargeTableValue>>(); - - ranges = new LRUCache<Integer, Map<ValueKey, Range>>(); - } - - public Session getDatabaseSession() { - return databaseSession; - } - - public WstColumnValue getWstColumnValue( - WstColumn column, - BigDecimal position, - BigDecimal w - ) { - Integer c = column.getId(); - - Map<ValueKey, WstColumnValue> map = wstColumnValues.get(c); - - if (map == null) { - map = new TreeMap<ValueKey, WstColumnValue>( - ValueKey.EPSILON_COMPARATOR); - wstColumnValues.put(c, map); - Query query = databaseSession.createQuery( - "from WstColumnValue where wstColumn.id=:cid"); - query.setParameter("cid", c); - for (Iterator iter = query.iterate(); iter.hasNext();) { - WstColumnValue wcv = (WstColumnValue)iter.next(); - map.put(new ValueKey(wcv.getPosition(), wcv.getW()), wcv); - } - } - - ValueKey key = new ValueKey(position, w); - - WstColumnValue wcv = map.get(key); - - if (wcv != null) { - return wcv; - } - - wcv = new WstColumnValue(column, position, w); - - databaseSession.save(wcv); - - map.put(key, wcv); - - return wcv; - } - - public DischargeTableValue getDischargeTableValue( - DischargeTable table, - BigDecimal q, - BigDecimal w - ) { - Integer t = table.getId(); - - Map<ValueKey, DischargeTableValue> map = - dischargeTableValues.get(t); - - if (map == null) { - map = new TreeMap<ValueKey, DischargeTableValue>( - ValueKey.EPSILON_COMPARATOR); - dischargeTableValues.put(t, map); - Query query = databaseSession.createQuery( - "from DischargeTableValue where dischargeTable.id=:tid"); - query.setParameter("tid", t); - for (Iterator iter = query.iterate(); iter.hasNext();) { - DischargeTableValue dctv = (DischargeTableValue)iter.next(); - map.put(new ValueKey(dctv.getQ(), dctv.getW()), dctv); - } - } - - ValueKey key = new ValueKey(q, w); - - DischargeTableValue dctv = map.get(key); - - if (dctv != null) { - return dctv; - } - - dctv = new DischargeTableValue(table, q, w); - - databaseSession.save(dctv); - - map.put(key, dctv); - - return dctv; - } - - public Range getRange(River river, BigDecimal a, BigDecimal b) { - Integer r = river.getId(); - - Map<ValueKey, Range> map = ranges.get(r); - - if (map == null) { - map = new TreeMap<ValueKey, Range>( - ValueKey.EPSILON_COMPARATOR); - ranges.put(r, map); - Query query = databaseSession.createQuery( - "from Range where river.id=:rid"); - query.setParameter("rid", r); - for (Iterator iter = query.iterate(); iter.hasNext();) { - Range range = (Range)iter.next(); - map.put(new ValueKey(range.getA(), range.getB()), range); - } - } - - ValueKey key = new ValueKey(a, b); - - Range range = map.get(key); - - if (range != null) { - return range; - } - - range = new Range(a, b, river); - - databaseSession.save(range); - - map.put(key, range); - - return range; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/ValueKey.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -package de.intevation.flys.importer; - -import java.math.BigDecimal; - -import java.util.Comparator; - -public class ValueKey -{ - public static final double EPSILON = 1e-6; - - public static final Comparator<ValueKey> EPSILON_COMPARATOR = - new Comparator<ValueKey>() - { - public int compare(ValueKey x, ValueKey y) { - int cmp = ValueKey.compare(x.a, y.a); - if (cmp != 0) return cmp; - return ValueKey.compare(x.b, y.b); - } - }; - - public static int compare(BigDecimal a, BigDecimal b) { - if (a == null && b == null) return 0; - if (a != null && b == null) return +1; - if (a == null && b != null) return -1; - - double diff = a.doubleValue() - b.doubleValue(); - if (diff < -EPSILON) return -1; - return diff > EPSILON ? +1 : 0; - } - - protected BigDecimal a; - protected BigDecimal b; - - public ValueKey() { - } - - public ValueKey(BigDecimal a, BigDecimal b) { - this.a = a; - this.b = b; - } - - @Override - public int hashCode() { - return ((a != null ? a.hashCode() : 0) << 16) - | (b != null ? b.hashCode() : 0); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof ValueKey)) { - return false; - } - ValueKey o = (ValueKey)other; - return !( - (a == null && o.a != null) - || (a != null && o.a == null) - || (a != null && !a.equals(o.a)) - || (b == null && o.b != null) - || (b != null && o.b == null) - || (b != null && !b.equals(o.b))); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/XY.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -package de.intevation.flys.importer; - - -/** Two doubles and an int index. */ -public class XY -implements Comparable<XY> -{ - public static final double X_EPSILON = 1e-4; - - protected double x; - protected double y; - protected int index; - - public XY() { - } - - public XY(double x, double y, int index) { - this.x = x; - this.y = y; - this.index = index; - } - - @Override - public int compareTo(XY other) { - if (x + X_EPSILON < other.x) return -1; - if (x > other.x + X_EPSILON) return +1; - if (index < other.index) return -1; - if (index > other.index) return +1; - return 0; - } - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public int getIndex() { - return index; - } - - public void setIndex(int index) { - this.index = index; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/AnnotationClassifier.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,232 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.w3c.dom.Element; - -import javax.xml.xpath.XPathConstants; - -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import org.apache.log4j.Logger; - -import de.intevation.artifacts.common.utils.XMLUtils; - -import de.intevation.flys.importer.ImportAnnotationType; -import de.intevation.flys.importer.Importer; - -public class AnnotationClassifier -{ - private static Logger log = Logger.getLogger(Importer.class); - - public static final String TYPES_XPATH = - "/annotation/types/type"; - - public static final String FILE_PATTERNS_XPATH = - "/annotation/patterns/file"; - - public static final String DESCRIPTION_PATTERNS_XPATH = - "/annotation/patterns/line"; - - - public static class Pair { - - protected Pattern pattern; - protected ImportAnnotationType annType; - - public Pair(Pattern pattern, ImportAnnotationType annType) { - this.pattern = pattern; - this.annType = annType; - } - - public ImportAnnotationType match(String s) { - Matcher m = pattern.matcher(s); - return m.matches() ? annType : null; - } - } // class Pair - - - protected Map<String, ImportAnnotationType> types; - protected List<Pair> filePatterns; - protected List<Pair> descPatterns; - - protected ImportAnnotationType defaultType; - - public AnnotationClassifier() { - } - - public AnnotationClassifier(Document rules) { - types = new HashMap<String, ImportAnnotationType>(); - filePatterns = new ArrayList<Pair>(); - descPatterns = new ArrayList<Pair>(); - - buildRules(rules); - } - - protected void buildRules(Document rules) { - buildTypes(rules); - buildFilePatterns(rules); - buildDescriptionPatterns(rules); - } - - protected void buildTypes(Document rules) { - - NodeList typeList = (NodeList)XMLUtils.xpath( - rules, - TYPES_XPATH, - XPathConstants.NODESET, - null); - - if (typeList == null) { - log.info("no rules found."); - return; - } - - for (int i = 0, N = typeList.getLength(); i < N; ++i) { - Element typeElement = (Element)typeList.item(i); - String name = typeElement.getAttribute("name"); - if (name.length() == 0) { - log.warn("ANNCLASS: rule has no name"); - continue; - } - - ImportAnnotationType aic = new ImportAnnotationType(name); - - types.put(name, aic); - - if (typeElement.getAttribute("default").equals("true")) { - defaultType = aic; - } - } - } - - protected void buildFilePatterns(Document rules) { - - NodeList patternList = (NodeList)XMLUtils.xpath( - rules, - FILE_PATTERNS_XPATH, - XPathConstants.NODESET, - null); - - if (patternList == null) { - log.info("no file patterns found."); - return; - } - - for (int i = 0, N = patternList.getLength(); i < N; ++i) { - Element element = (Element)patternList.item(i); - Pair pair = buildPair(element); - if (pair != null) { - filePatterns.add(pair); - } - } - } - - protected void buildDescriptionPatterns(Document rules) { - - NodeList patternList = (NodeList)XMLUtils.xpath( - rules, - DESCRIPTION_PATTERNS_XPATH, - XPathConstants.NODESET, - null); - - if (patternList == null) { - log.info("no line patterns found."); - return; - } - - for (int i = 0, N = patternList.getLength(); i < N; ++i) { - Element element = (Element)patternList.item(i); - Pair pair = buildPair(element); - if (pair != null) { - descPatterns.add(pair); - } - } - } - - protected Pair buildPair(Element element) { - String pattern = element.getAttribute("pattern"); - String type = element.getAttribute("type"); - - if (pattern.length() == 0) { - log.warn("ANNCLASS: pattern has no 'pattern' attribute."); - return null; - } - - if (type.length() == 0) { - log.warn("ANNCLASS: pattern has no 'type' attribute."); - return null; - } - - ImportAnnotationType annType = types.get(type); - - if (annType == null) { - log.warn("ANNCLASS: pattern has unknown type '" + type + "'"); - return null; - } - - Pattern p; - - try { - p = Pattern.compile(pattern, - Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); - } - catch (IllegalArgumentException iae) { - log.warn("ANNCLASS: pattern '" + pattern + "' is invalid.", iae); - return null; - } - - return new Pair(p, annType); - } - - public ImportAnnotationType getDefaultType() { - return defaultType; - } - - public ImportAnnotationType classifyFile(String filename) { - return classifyFile(filename, null); - } - - public ImportAnnotationType classifyFile( - String filename, - ImportAnnotationType def - ) { - if (filename.toLowerCase().endsWith(".km")) { - filename = filename.substring(0, filename.length()-3); - } - - for (Pair pair: filePatterns) { - ImportAnnotationType annType = pair.match(filename); - if (annType != null) { - return annType; - } - } - - return def; - } - - public ImportAnnotationType classifyDescription(String description) { - return classifyDescription(description, null); - } - - public ImportAnnotationType classifyDescription( - String description, - ImportAnnotationType def - ) { - for (Pair pair: descPatterns) { - ImportAnnotationType annType = pair.match(description); - if (annType != null) { - return annType; - } - } - - return def; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/AnnotationsParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,198 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.util.HashMap; -import java.util.TreeSet; -import java.util.List; -import java.util.ArrayList; - -import java.io.IOException; -import java.io.File; -import java.io.LineNumberReader; -import java.io.InputStreamReader; -import java.io.FileInputStream; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.ImportAnnotation; -import de.intevation.flys.importer.ImportRange; -import de.intevation.flys.importer.ImportEdge; -import de.intevation.flys.importer.ImportAnnotationType; -import de.intevation.flys.importer.ImportAttribute; -import de.intevation.flys.importer.ImportPosition; - -public class AnnotationsParser -{ - private static Logger log = Logger.getLogger(AnnotationsParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final String [] TO_SCAN = { - "Basisdaten", - "Streckendaten", - ".." + File.separator + - "Morphologie" + File.separator + "Streckendaten" - }; - - protected HashMap<String, ImportAttribute> attributes; - protected HashMap<String, ImportPosition> positions; - protected TreeSet<ImportAnnotation> annotations; - protected AnnotationClassifier classifier; - - public AnnotationsParser() { - this(null); - } - - public AnnotationsParser(AnnotationClassifier classifier) { - attributes = new HashMap<String, ImportAttribute>(); - positions = new HashMap<String, ImportPosition>(); - annotations = new TreeSet<ImportAnnotation>(); - this.classifier = classifier; - } - - public void parseFile(File file) throws IOException { - log.info("parsing km file: '" + file + "'"); - - ImportAnnotationType defaultIAT = null; - - if (classifier != null) { - defaultIAT = classifier.classifyFile( - file.getName(), - classifier.getDefaultType()); - } - - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = null; - while ((line = in.readLine()) != null) { - if ((line = line.trim()).length() == 0 - || line.startsWith("*")) { - continue; - } - - String [] parts = line.split("\\s*;\\s*"); - - if (parts.length < 3) { - log.warn("ANN: not enough columns in line " - + in.getLineNumber()); - continue; - } - - ImportPosition position = positions.get(parts[0]); - if (position == null) { - position = new ImportPosition(parts[0]); - positions.put(parts[0], position); - } - - ImportAttribute attribute = attributes.get(parts[1]); - if (attribute == null) { - attribute = new ImportAttribute(parts[1]); - attributes.put(parts[1], attribute); - } - - String [] r = parts[2].replace(",", ".").split("\\s*#\\s*"); - - BigDecimal from, to; - - try { - from = new BigDecimal(r[0]); - to = r.length < 2 ? null : new BigDecimal(r[1]); - if (to != null && from.compareTo(to) > 0) { - BigDecimal t = from; from = to; to = t; - } - } - catch (NumberFormatException nfe) { - log.warn("ANN: invalid number in line " + in.getLineNumber()); - continue; - } - - ImportEdge edge = null; - - if (parts.length == 4) { // Only 'Unterkante' - try { - edge = new ImportEdge( - null, - new BigDecimal(parts[3].trim().replace(',', '.'))); - } - catch (NumberFormatException nfe) { - log.warn("ANN: cannot parse 'Unterkante' in line " + - in.getLineNumber()); - } - } - else if (parts.length > 4) { // 'Unterkante' and 'Oberkante' - String bottom = parts[3].trim().replace(',', '.'); - String top = parts[4].trim().replace(',', '.'); - try { - BigDecimal b = bottom.length() == 0 - ? null - : new BigDecimal(bottom); - BigDecimal t = top.length() == 0 - ? null - : new BigDecimal(top); - edge = new ImportEdge(t, b); - } - catch (NumberFormatException nfe) { - log.warn( - "ANN: cannot parse 'Unterkante' or 'Oberkante' in line " - + in.getLineNumber()); - } - } - - ImportRange range = new ImportRange(from, to); - - ImportAnnotationType type = classifier != null - ? classifier.classifyDescription(line, defaultIAT) - : null; - - ImportAnnotation annotation = new ImportAnnotation( - attribute, position, range, edge, type); - - if (!annotations.add(annotation)) { - log.info("ANN: duplicated annotation '" + parts[0] + - "' in line " + in.getLineNumber()); - } - } - } - finally { - if (in != null) { - in.close(); - } - } - } - - public void parse(File root) throws IOException { - - for (String toScan: TO_SCAN) { - File directory = FileTools.repair(new File(root, toScan)); - if (!directory.isDirectory()) { - log.warn("ANN: '" + directory + "' is not a directory."); - continue; - } - File [] files = directory.listFiles(); - if (files == null) { - log.warn("ANN: cannot list directory '" + directory + "'"); - continue; - } - - for (File file: files) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".km")) { - parseFile(file); - } - } - } // for all directories to scan - } - - public List<ImportAnnotation> getAnnotations() { - return new ArrayList<ImportAnnotation>(annotations); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/AtFileParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,222 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.IOException; -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportDischargeTable; -import de.intevation.flys.importer.ImportDischargeTableValue; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.util.Date; -import java.util.Calendar; - -import de.intevation.flys.importer.ImportTimeInterval; - -/** Parse *.at (Abflusstafeln?) files. */ -public class AtFileParser { - - public static final String ENCODING = "ISO-8859-1"; - - private static Logger logger = Logger.getLogger(AtFileParser.class); - - // regular expression from hell to find out time range - public static final Pattern DATE_LINE = Pattern.compile( - "^\\*\\s*Abflu[^t]+tafel?\\s*([^\\d]+)" + - "(\\d{1,2})?\\.?(\\d{1,2})?\\.?(\\d{2,4})\\s*(?:(?:bis)|-)?\\s*" + - "(?:(\\d{1,2})?\\.?(\\d{1,2})?\\.?(\\d{2,4}))?\\s*.*$"); - - public AtFileParser() { - } - - - public ImportDischargeTable parse(File file) throws IOException { - return parse(file, "", 0); - } - - public ImportDischargeTable parse( - File file, - String prefix, - int kind - ) - throws IOException { - - logger.info("parsing AT file: " + file); - - BufferedReader br = null; - - String line = null; - - boolean beginning = true; - - ImportDischargeTable dischargeTable = - new ImportDischargeTable(kind, prefix + file.getName()); - - Date from = null; - Date to = null; - - try { - br = new BufferedReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - while ((line = br.readLine()) != null) { - - String tmp = line.trim(); - - if (tmp.length() == 0) { - continue; - } - - Matcher m = DATE_LINE.matcher(tmp); - if (m.matches()) { - from = guessDate(m.group(2), m.group(3), m.group(4)); - to = guessDate(m.group(5), m.group(6), m.group(7)); - if (from == null) { - Date t = from; from = to; to = t; - } - continue; - } - - if (tmp.startsWith("#! name=")) { - // XXX Skip the name, because we don't know where to save - // it at the moment - - //String name = tmp.substring(8); - continue; - } - - if (tmp.startsWith("#") || tmp.startsWith("*")) { - continue; - } - - String[] splits = tmp.replace(',', '.').split("\\s+"); - - if ((splits.length < 2) || (splits.length > 11)) { - logger.warn("Found an invalid row in the AT file."); - continue; - } - - String strW = splits[0].trim(); - double W = Double.parseDouble(strW); - - /* shift is used to differenciate between lines with - * exactly 10 Qs and lines with less than 10 Qs. The shift - * is only modified when it is the first line. - */ - int shift = -1; - - if (splits.length != 11 && beginning) { - shift = 10 - splits.length; - } - - - for (int i = 1; i < splits.length; i++) { - double iW = W + shift + i; - double iQ = Double.parseDouble(splits[i].trim()); - - dischargeTable.addDischargeTableValue( - new ImportDischargeTableValue( - new BigDecimal(iQ/100.0), - new BigDecimal(iW/100.0))); - } - - beginning = false; - } - } - catch (NumberFormatException pe) { - logger.warn("AT: invalid number " + pe.getMessage()); - } - finally { - if (br != null) { - br.close(); - } - } - - if (from != null) { - if (to != null && from.compareTo(to) > 0) { - Date t = from; from = to; to = t; - } - logger.info("from: " + from + " to: " + to); - ImportTimeInterval interval = new ImportTimeInterval(from, to); - dischargeTable.setTimeInterval(interval); - } - - logger.info("Finished parsing AT file: " + file); - - return dischargeTable; - } - - public static Date guessDate(String day, String month, String year) { - // TODO evaluate whether DateGuesser class can do that. - if (day == null && month == null && year == null) { - return null; - } - - logger.debug("day: " + day + " month: " + month + " year: " + year); - - int dayI = 15; - if (day != null) { - try { - dayI = Integer.parseInt(day.trim()); - } - catch (NumberFormatException nfe) { - } - } - - int monthI = 6; - if (month != null) { - try { - monthI = Integer.parseInt(month.trim()); - } - catch (NumberFormatException nfe) { - } - } - - int yearI = 1900; - if (year != null) { - try { - yearI = Integer.parseInt(year.trim()); - if (yearI < 100) { - if (yearI < 20) { - yearI += 2000; - } - else { - yearI += 1900; - } - } - } - catch (NumberFormatException nfe) { - } - } - - Calendar cal = Calendar.getInstance(); - cal.set(yearI, monthI-1, dayI, 12, 0, 0); - long ms = cal.getTimeInMillis(); - cal.setTimeInMillis(ms - ms%1000); - return cal.getTime(); - } - - - /** Parse one or more files, (useful for debugging), */ - public static void main(String [] args) { - - AtFileParser parser = new AtFileParser(); - - try { - for (String arg: args) { - parser.parse(new File(arg)); - } - } catch(Exception e) { - logger.error("Exception caught " + e); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/BedHeightEpochParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.math.BigDecimal; - -import java.text.ParseException; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportBedHeight; -import de.intevation.flys.importer.ImportBedHeightEpoch; -import de.intevation.flys.importer.ImportBedHeightEpochValue; - - -/** Parses BedHeightEpochs from csv file. */ -public class BedHeightEpochParser extends BedHeightParser { - - /** Our own logger. */ - private static final Logger log = - Logger.getLogger(BedHeightEpochParser.class); - - - @Override - protected ImportBedHeight newImportBedHeight(String description) { - return new ImportBedHeightEpoch(description); - } - - - /** - * Handle a non-comment, none-Metadata line of csv file, adding - * ImportBedHeightEpochValues to the given ImportBedHeight object. - */ - @Override - protected void handleDataLine(ImportBedHeight obj, String line) { - String[] values = line.split(SEPERATOR_CHAR); - - if (values == null || values.length == 0 || values[0].length() == 0) { - // There might be quite some ";" found. - //log.warn("Skip invalid data line: " + line); - return; - } - - BigDecimal km; - - try { - km = new BigDecimal(nf.parse(values[0]).doubleValue()); - } - catch (ParseException e) { - log.warn("Unparseable number in data row: " + line); - return; - } - - - // Handle "gap" lines like '255,0;' - if (values.length < 2) { - ImportBedHeightEpochValue value = new ImportBedHeightEpochValue( - km, - null - ); - - obj.addValue(value); - return; - } - - try { - ImportBedHeightEpochValue value = new ImportBedHeightEpochValue( - km, - new BigDecimal(nf.parse(values[1]).doubleValue()) - ); - - obj.addValue(value); - } - catch (ParseException e) { - log.warn("Unparseable number in data row: " + line); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/BedHeightParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,411 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; - -import java.math.BigDecimal; - -import java.text.NumberFormat; -import java.text.ParseException; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportBedHeight; -import de.intevation.flys.importer.ImportBedHeightType; -import de.intevation.flys.importer.ImportElevationModel; -import de.intevation.flys.importer.ImportLocationSystem; -import de.intevation.flys.importer.ImportRange; -import de.intevation.flys.importer.ImportTimeInterval; -import de.intevation.flys.importer.ImportUnit; -import de.intevation.flys.model.BedHeightType; -import de.intevation.flys.importer.ImporterSession; - -public abstract class BedHeightParser { - - private static final Logger log = - Logger.getLogger(BedHeightParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final Locale DEFAULT_LOCALE = Locale.GERMAN; - - public static final String START_META_CHAR = "#"; - public static final String SEPERATOR_CHAR = ";"; - - public static final Pattern META_YEAR = - Pattern.compile("^Jahr: [^0-9]*(\\d*).*"); - - public static final Pattern META_TIMEINTERVAL = - Pattern.compile("^Zeitraum: Epoche (\\d*)-(\\d*).*"); - - public static final Pattern META_TYPE = - Pattern.compile("^Aufnahmeart: (.*).*"); - - public static final Pattern META_LOCATION_SYSTEM = - Pattern.compile("^Lagesystem: (.*).*"); - - public static final Pattern META_CUR_ELEVATION_SYSTEM = - Pattern.compile("^H.hensystem:\\s(\\w++) (.* )??\\[(.*)\\].*"); - - public static final Pattern META_OLD_ELEVATION_SYSTEM = - Pattern.compile("^urspr.ngliches H.hensystem:\\s(\\w++) (.* )??\\[(.*)\\].*"); - - public static final Pattern META_SOUNDING_WIDTH = - Pattern.compile("^ausgewertete Peilbreite: (\\d*).*"); - - public static final Pattern META_RANGE = - Pattern.compile("^Strecke:\\D*(\\d++.?\\d*) ?- ?(\\d++.?\\d*).*"); - - public static final Pattern META_EVALUATION_BY = - Pattern.compile("^Auswerter: (.*).*"); - - public static final Pattern META_COMMENTS = - Pattern.compile("^Weitere Bemerkungen: (.*).*"); - - - protected static NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); - - - protected List<ImportBedHeight> bedHeights; - - - protected abstract ImportBedHeight newImportBedHeight(String description); - - /** Handle a line of file that contains data (in contrast to comments, meta). */ - protected abstract void handleDataLine( - ImportBedHeight importBedHeight, - String line - ); - - - - public BedHeightParser() { - this.bedHeights = new ArrayList<ImportBedHeight>(); - } - - - public List<ImportBedHeight> getBedHeights() { - return bedHeights; - } - - - public void parse(File file) throws IOException { - log.info("Parsing bed height single file '" + file + "'"); - - ImportBedHeight obj = newImportBedHeight(file.getName()); - - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = null; - while ((line = in.readLine()) != null) { - if ((line = line.trim()).length() == 0) { - continue; - } - - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(obj, line); - } - else { - handleDataLine(obj, line); - } - } - - log.info("File contained " + obj.getValueCount() + " values."); - bedHeights.add(obj); - } - finally { - if (in != null) { - in.close(); - } - } - } - - - protected static String stripMetaLine(String line) { - String tmp = line.substring(1, line.length()); - - if (tmp.startsWith(" ")) { - return tmp.substring(1, tmp.length()); - } - else { - return tmp; - } - } - - - public static Date getDateFromYear(int year) { - Calendar cal = Calendar.getInstance(); - cal.set(year, 0, 1); - - return cal.getTime(); - } - - - protected void handleMetaLine(ImportBedHeight obj, String line) { - String meta = stripMetaLine(line); - - if (handleMetaYear(obj, meta)) { - return; - } - else if (handleMetaTimeInterval(obj, meta)) { - return; - } - else if (handleMetaSoundingWidth(obj, meta)) { - return; - } - else if (handleMetaComment(obj, meta)) { - return; - } - else if (handleMetaEvaluationBy(obj, meta)) { - return; - } - else if (handleMetaRange(obj, meta)) { - return; - } - else if (handleMetaType(obj, meta)) { - return; - } - else if (handleMetaLocationSystem(obj, meta)) { - return; - } - else if (handleMetaCurElevationModel(obj, meta)) { - return; - } - else if (handleMetaOldElevationModel(obj, meta)) { - return; - } - else { - log.warn("BHP: Meta line did not match any known type: " + line); - } - } - - - protected boolean handleMetaYear(ImportBedHeight obj, String line) { - Matcher m = META_YEAR.matcher(line); - - if (m.matches()) { - String tmp = m.group(1); - if (tmp.length() > 0) { - obj.setYear(Integer.parseInt(tmp)); - } - else { - log.warn("BHP: No year given."); - } - return true; - } - - return false; - } - - - protected boolean handleMetaTimeInterval(ImportBedHeight obj, String line) { - Matcher m = META_TIMEINTERVAL.matcher(line); - - if (m.matches()) { - String lo = m.group(1); - String up = m.group(2); - - log.debug("Found time interval: " + lo + " - " + up); - - try { - int lower = Integer.valueOf(lo); - int upper = Integer.valueOf(up); - - Date fromYear = getDateFromYear(lower); - Date toYear = getDateFromYear(upper); - - obj.setTimeInterval(new ImportTimeInterval(fromYear, toYear)); - } - catch (NumberFormatException e) { - log.warn("BHP: could not parse timeinterval", e); - } - - return true; - } - - return false; - } - - - protected boolean handleMetaSoundingWidth(ImportBedHeight obj, String line) { - Matcher m = META_SOUNDING_WIDTH.matcher(line); - - if (m.matches()) { - String tmp = m.group(1); - - try { - obj.setSoundingWidth(Integer.valueOf(tmp)); - return true; - } - catch (NumberFormatException e) { - log.warn("BHP: Could not parse sounding width: " + line, e); - log.warn("-> Set default value '0'"); - } - obj.setSoundingWidth(0); - } - - return false; - } - - - protected boolean handleMetaComment(ImportBedHeight obj, String line) { - Matcher m = META_COMMENTS.matcher(line); - - if (m.matches()) { - String tmp = m.group(1); - - obj.setDescription(tmp); - - return true; - } - - return false; - } - - - protected boolean handleMetaEvaluationBy( - ImportBedHeight obj, - String line - ) { - Matcher m = META_EVALUATION_BY.matcher(line); - - if (m.matches()) { - String tmp = m.group(1); - tmp = tmp.replace(";", ""); - - obj.setEvaluationBy(tmp); - - return true; - } - - return false; - } - - - protected boolean handleMetaRange(ImportBedHeight obj, String line) { - Matcher m = META_RANGE.matcher(line); - - if (m.matches() && m.groupCount() >= 2) { - String a = m.group(1).replace(";", ""); - String b = m.group(2).replace(";", ""); - - try { - BigDecimal lower = new BigDecimal(nf.parse(a).doubleValue()); - BigDecimal upper = new BigDecimal(nf.parse(b).doubleValue()); - - obj.setRange(new ImportRange(lower, upper)); - - return true; - } - catch (ParseException e) { - log.warn("BHP: could not parse range", e); - } - } - - return false; - } - - - protected boolean handleMetaType(ImportBedHeight obj, String line) { - Matcher m = META_TYPE.matcher(line); - - if (m.matches()) { - String tmp = m.group(1).replace(";", ""); - - BedHeightType bht = BedHeightType.fetchBedHeightTypeForType( - tmp, ImporterSession.getInstance().getDatabaseSession()); - - if (bht != null) { - obj.setType(new ImportBedHeightType(bht)); - return true; - } - - log.warn("Unknown bed height type: '" + tmp + "'"); - } - - return false; - } - - - protected boolean handleMetaLocationSystem( - ImportBedHeight obj, - String line - ) { - Matcher m = META_LOCATION_SYSTEM.matcher(line); - - if (m.matches()) { - String tmp = m.group(1).replace(";", ""); - - obj.setLocationSystem(new ImportLocationSystem(tmp, tmp)); - - return true; - } - - return false; - } - - - protected boolean handleMetaCurElevationModel( - ImportBedHeight obj, - String line - ) { - Matcher m = META_CUR_ELEVATION_SYSTEM.matcher(line); - - if (m.matches()) { - String name = m.group(1); - String num = m.group(2); - String unit = m.group(3); - - obj.setCurElevationModel(new ImportElevationModel( - name + " " + num, - new ImportUnit(unit) - )); - - return true; - } - - return false; - } - - - protected boolean handleMetaOldElevationModel( - ImportBedHeight obj, - String line - ) { - Matcher m = META_OLD_ELEVATION_SYSTEM.matcher(line); - - if (m.matches()) { - String name = m.group(1); - String num = m.group(2); - String unit = m.group(3); - - obj.setOldElevationModel(new ImportElevationModel( - name + " " + num, - new ImportUnit(unit) - )); - - return true; - } - - return false; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/BedHeightSingleParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,105 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.math.BigDecimal; - -import java.text.ParseException; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportBedHeight; -import de.intevation.flys.importer.ImportBedHeightSingle; -import de.intevation.flys.importer.ImportBedHeightSingleValue; - - -public class BedHeightSingleParser extends BedHeightParser { - - private static final Logger log = - Logger.getLogger(BedHeightSingleParser.class); - - - - @Override - protected ImportBedHeight newImportBedHeight(String description) { - return new ImportBedHeightSingle(description); - } - - - - /** - * Create ImportBedHeightSingleValue from a line of csv file, add - * it to the ImportBedHeight. - */ - @Override - protected void handleDataLine(ImportBedHeight obj, String line) { - String[] values = line.split(SEPERATOR_CHAR); - - if (values == null || (values.length != 1 && values.length < 6)) { - //log.warn("BSP: Error while parsing data line: '" + line + "'"); - return; - } - - BigDecimal km; - - try { - km = new BigDecimal(nf.parse(values[0]).doubleValue()); - } - catch (ParseException e) { - // We expect a lot of ";;;;;;" lines. - //log.warn("BSP: Error while parsing km of data row.", e); - return; - } - - // Handle gaps like "10,0;;;;;". - if (values.length == 1) { - ImportBedHeightSingleValue value = new ImportBedHeightSingleValue( - (ImportBedHeightSingle) obj, - km, - null, null, null, null, null); - obj.addValue(value); - return; - } - - // Because we cannot enforce consistency of values with complete data - // via null constraints in the database (as there are "gap" values), - // do this checks manually. - if (values[3].length() == 0 || values[4].length() == 0 - || values[5].length() == 0) { - //log.warn("BSP: Error while parsing data row (manual null constraint violated)."); - return; - } - - try { - ImportBedHeightSingleValue value = new ImportBedHeightSingleValue( - (ImportBedHeightSingle) obj, - km, - new BigDecimal(nf.parse(values[1]).doubleValue()), - new BigDecimal(nf.parse(values[2]).doubleValue()), - new BigDecimal(nf.parse(values[3]).doubleValue()), - parseBigDecimal(values[4], line), - new BigDecimal(nf.parse(values[5]).doubleValue()) - ); - - obj.addValue(value); - } - catch (ParseException e) { - log.warn("BSP: unparseable value in data row.", e); - } - } - - private BigDecimal parseBigDecimal(String value, String line) { - BigDecimal result = null; - try { - Double dValue = Double.valueOf(value.replace(",", ".")); - result = new BigDecimal(dValue.doubleValue()); - } - catch (NumberFormatException nfe) { - log.warn( - "Could not parse " + - value + - " in bed heigt single row: " - + line); - } - return result; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/BundesWasserStrassenParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.util.HashMap; - -import org.apache.log4j.Logger; - -/** Parse CSV file that contains official numbers for rivers. */ -public class BundesWasserStrassenParser extends LineParser { - - /** Private logger. */ - private static final Logger logger = - Logger.getLogger(BundesWasserStrassenParser.class); - - /** Map from rivernames to Official numbers. */ - private HashMap<String,Long> numberMap; - - - public BundesWasserStrassenParser() { - numberMap = new HashMap<String,Long>(); - } - - - /** No need to reset. */ - @Override - protected void reset() { - } - - - /** No action needed on eof. */ - @Override - protected void finish() { - } - - - /** Handle a line of the bwastr-id file. */ - @Override - protected void handleLine(int lineNum, String line) { - String[] vals = line.split(","); - // Try both "," and ";" as separator. - if (vals.length != 2) { - vals = line.split(";"); - if (vals.length != 2) { - logger.warn("Invalid bwastr-id line:\n" + line); - return; - } - } - try { - String name = unwrap(vals[0].toLowerCase()); - String numberStr = unwrap(vals[1]); - Long number = Long.valueOf(numberStr); - numberMap.put(name, number); - } - catch (NumberFormatException e) { - logger.warn("Invalid number in bwastr-id line:\n" + line); - } - } - - - /** Get river -> official number mapping. */ - public HashMap<String,Long> getMap() { - return numberMap; - } - - - /** Remove leading and trailing quotes. */ - protected String unwrap(String input) { - if (input.startsWith("\"")) { - input = input.substring(1); - } - if (input.endsWith("\"")) { - input = input.substring(0, input.length() - 1); - } - return input; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/CrossSectionParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,22 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.flys.importer.XY; - -import java.io.File; -import java.util.List; -import java.util.Map; - -public interface CrossSectionParser { - - public String getDescription(); - - public Integer getYear(); - - public Map<Double,List<XY>> getData(); - - public interface Callback { - boolean accept(File file); - void parsed(CrossSectionParser parser); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/DA50Parser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,145 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.util.ArrayList; -import java.util.Map; -import java.util.List; -import java.util.TreeMap; - -import java.io.File; -import java.io.IOException; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.XY; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.utils.EpsilonComparator; - - -/** - * To create cross-sections, generate: Map<double,list<xy>> from files - * in da50 format. - */ -public class DA50Parser extends LineParser implements CrossSectionParser -{ - /** Private logger. */ - private static Logger logger = Logger.getLogger(DA50Parser.class); - - /** The current line to which add points. */ - private List<XY> currentLine; - - /** Data collected so far, last element will be currentLine. */ - protected Map<Double, List<XY>> data; - - - /** Trivial constructor. */ - public DA50Parser() { - data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); - } - - - /** Get the description of the cross section parsed. */ - @Override - public String getDescription() { - return FileTools.removeExtension(getFileName()); - } - - - /** Get the year of this cross sections measurement. */ - @Override - public Integer getYear() { - return null; - } - - - /** - * Return the data parsed. - * @return map of stations (km) to list of points. - */ - @Override - public Map<Double, List<XY>> getData() { - return data; - } - - - /** Walk a directory tree and attempt parsing all *.d50 files. */ - public void parseDA50s(File root, final Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - // TODO check presence of TIM file. - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".d50") - && (callback == null || callback.accept(file))) { - reset(); - try { - parse(file); - logger.info("parsing done"); - if (callback != null) { - callback.parsed(DA50Parser.this); - } - } - catch (IOException ioe) { - logger.error("IOException while parsing file"); - return false; - } - } - return true; - } - }); - } - - - /** Called before consuming first line of file. */ - public void reset() { - data.clear(); - currentLine = new ArrayList<XY>(); - } - - - /** - * Called for each line. Try to extract info from a da50 line. - */ - @Override - protected void handleLine(int lineNum, String line) { - String pointId = line.substring(0,2); - String streetId = line.substring(2,9); - String station = line.substring(9,18); - String free = line.substring(18,20); - String gkLRight = line.substring(20,30); - String gkLHigh = line.substring(30,40); - String gkRRight = line.substring(40,50); - String gkRHigh = line.substring(50,60); - String distance = line.substring(60,70); - - // TODO Intersect/Correlate these with e.g. TIM files. - // TODO note that as-is these points are really useless. - currentLine = new ArrayList<XY>(); - currentLine.add(new XY(0, 10,0)); - currentLine.add(new XY(Double.parseDouble(distance), 10, 1)); - } - - - /** Called when file is fully consumed. */ - @Override - protected void finish() { - logger.info("Parsed " + data.size() + " lines"); - } - - - /** Parses files given as arguments. */ - public static void main(String [] args) { - - DA50Parser parser = new DA50Parser(); - - logger.warn("Start parsing files."); - for (String arg: args) { - parser.parseDA50s(new File(arg), null); - logger.warn("Parsing a file."); - } - logger.error("Finished parsing files."); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/DA66Parser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,459 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.XY; - -import de.intevation.flys.utils.EpsilonComparator; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - - -/** - * To create cross-sections, generate: Map<double,list<xy>> from files - * in da66 format. - */ -public class DA66Parser extends LineParser implements CrossSectionParser -{ - /** Private logger. */ - private static Logger logger = Logger.getLogger(DA66Parser.class); - - private static String HEAD_HEAD = "00"; - private static String HEAD_GEOM = "66"; // "Values" - private static String HEAD_ENDG = "88"; // Probably never used. - - /** Regex to match lines of files in da66 format. */ - private static final Pattern LINE_PATTERN = - Pattern.compile("^([0-9 -]{2})" + // Type (00|66|88) - "([0-9 -]{5})" + // unset - "([0-9 -]{2})" + // id - "([0-9 -]{9})" + // station - "([0-9 -]{2})" + // running number - "([0-9 -]{1})?" + // point id - /* - Would be great if we could express the pattern as this: - ([0-9 -]{1})([0-9 -JKMLMNOPQR]{7})([0-9 -]{7})+ - */ - "([0-9 -JKMLMNOPQR]{7})?" + // y - "([0-9 -]{7})?" + // z - "([0-9 -]{1})?" + // point id - "([0-9 -JKMLMNOPQR]{7})?" + // y - "([0-9 -]{7})?" + // z - "([0-9 -]{1})?" + // point id - "([0-9 -JKMLMNOPQR]{7})?" + // y - "([0-9 -]{7})?" + // z - "([0-9 -]{1})?" + // point id - "([0-9 -JKMLMNOPQR]{7})?" + // y - "([0-9 -]{7})?" // z - ); - - - /** Indices to match group of main regex. */ - private static enum FIELD { - HEAD ( 1), - UNSET ( 2), - ID ( 3), - STATION ( 4), - RUNNR ( 5), - POINT_1_ID( 6), - POINT_1_Y ( 7), - POINT_1_Z ( 8), - POINT_2_ID( 9), - POINT_2_Y (10), - POINT_2_Z (11), - POINT_3_ID(12), - POINT_3_Y (13), - POINT_3_Z (14), - POINT_4_ID(15), - POINT_4_Y (16), - POINT_4_Z (17); - - private int idx; - FIELD(int idx) { - this.idx = idx; - } - int getIdx() { - return idx; - } - } - - - /** Header lines of da66 can define a type. */ - private static enum Type { - DATE ( 0), - HEKTOSTONE_LEFT ( 1), //grm. "Standlinie" - HEKTOSTONE_RIGHT ( 2), - CHANNEL_LEFT ( 3), //grm. "Fahrrinne" - CHANNEL_RIGHT ( 4), - CHANNEL_2_LEFT ( 5), - CHANNEL_2_RIGHT ( 6), - GIW_1972 ( 7), - GROIN_DIST_LEFT ( 8), //grm. "Buhnenkopfabstand links" - GROIN_HEIGHT_LEFT ( 9), - GROIN_SLOPE_LEFT (10), - GROIN_DIST_RIGHT (11), - GROIN_HEIGHT_RIGHT (12), - GROIN_SLOPE_RIGHT (13), - STRIKE_LEFT (14), //grm. "Streichlinie links" - AXIS (15), - STRIKE_RIGHT (16), - GROIN_BACK_SLOPE_LEFT (17), //grm. "Buhnenrueckenneigung" - GROIN_BACK_SLOPE_RIGHT (18), - GIW_1932 (19), - GIW_1982 (20), - STAND_ISLAND_1 (21), - STAND_ISLAND_2 (22), - STAND_ISLAND_3 (23), - STAND_ISLAND_4 (24), - UNSPECIFIED_1 (25), - UNSPECIFIED_2 (26), - HHW (27), - OLD_PROFILE_NULL (28), - AW_1978 (29), - SIGN_LEFT (30), - SIGN_RIGHT (31), - DIST_SIGNAL_CHANNEL_LEFT (32), - DIST_SIGNAL_CHANNEL_RIGHT(33), - UNSPECIFIED_3 (34), - UNSPECIFIED_4 (35), - UNSPECIFIED_5 (36), - UNSPECIFIED_6 (37), - SHORE_LEFT (38), - SHORE_RIGHT (39), - UNSPECIFIED_7 (40); - - private final int id; - Type(int id) { - this.id = id; - } - public int getId() { - return id; - } - } - - - /** Available types. */ - private static HashMap<Integer, Type> typeMap; - - - /** Types we can deal with. */ - private static List<Type> implementedTypes; - - - static { - typeMap = new HashMap<Integer, Type>(); - for (Type t: Type.values()) { - typeMap.put(new Integer(t.getId()), t); - } - // TODO populate and respect header type. - implementedTypes = new ArrayList<Type>(); - //implementedTypes.add(..); - } - - - /** The current line to which add points. */ - private List<XY> currentLine; - - - /** Data collected so far, last element will be currentLine. */ - protected Map<Double, List<XY>> data; - - - /** Trivial constructor. */ - public DA66Parser() { - data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); - } - - - /** Get the description of the cross section parsed. */ - @Override - public String getDescription() { - return FileTools.removeExtension(getFileName()); - } - - - /** Get the year of this cross sections measurement. */ - @Override - public Integer getYear() { - return null; - } - - - /** - * Return the data parsed. - * @return map of stations (km) to list of points. - */ - @Override - public Map<Double, List<XY>> getData() { - return data; - } - - - /** - * Walk a directory tree, parse its *.da66 files and store the - * data found. - */ - public void parseDA66s(File root, final Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".d66") - && (callback == null || callback.accept(file))) { - reset(); - try { - parse(file); - logger.info("parsing done"); - if (callback != null) { - callback.parsed(DA66Parser.this); - } - } - catch (IOException ioe) { - logger.error("IOException while parsing file"); - return false; - } - } - return true; - } - }); - } - - - /** - * Get the Index of the last cross-section lines point. - * @return last points index, -1 if not available. - */ - private int lastPointIdx() { - if (currentLine == null || currentLine.isEmpty()) { - return -1; - } - XY lastPoint = this.currentLine.get(currentLine.size()-1); - return lastPoint.getIndex(); - } - - - /** Returns station, deciding if it could in cm, in which case convert. */ - private double stationInKm(double station) { - if (station > 10000) { - return station/100000d; - } - else { - return station; - } - } - - - /** Apply the convention how to deal with numbers < -99.999 .*/ - private String applyLetterConvention(String orig) { - if (orig.endsWith("-")) { - return "-" + orig.replace("-",""); - } - else if (orig.endsWith("J")) { - return "-" + orig.replace("J","1"); - } - else if (orig.endsWith("K")) { - return "-" + orig.replace("K","2"); - } - else if (orig.endsWith("L")) { - return "-" + orig.replace("L","3"); - } - else if (orig.endsWith("M")) { - return "-" + orig.replace("M","4"); - } - else if (orig.endsWith("N")) { - return "-" + orig.replace("N","5"); - } - else if (orig.endsWith("O")) { - return "-" + orig.replace("O","6"); - } - else if (orig.endsWith("P")) { - return "-" + orig.replace("P","7"); - } - else if (orig.endsWith("Q")) { - return "-" + orig.replace("Q","8"); - } - else if (orig.endsWith("R")) { - return "-" + orig.replace("R","9"); - } - else { - return orig; - } - } - - /** - * Add a Point (YZ,Index) to the current cross section line. - * @param y The y coordinate of new point. - * @param z The z coordinate of new point. - * @param idx Ignored, the parameter of new point. - * @return true if point could been added, false otherwise (e.g. not - * parsable y or z values. - */ - private boolean addPoint(String y, String z, String idx) { - if (z == null || y == null || idx == null) { - logger.error("Incomplete point definition"); - return false; - } - - double iy; - double iz; - // Handle letter convention. - y = applyLetterConvention(y); - try { - iy = Double.parseDouble(y) / 1000d; - iz = Double.parseDouble(z) / 1000d; - } - catch(java.lang.NumberFormatException nfe) { - logger.error("Could not parse Number: " + nfe.getMessage()); - return false; - } - - // We ignore idx, and increment instead. - int index; - int lastPointIdx = lastPointIdx(); - if (lastPointIdx <= 0) { - index = 1; - } else { - index = lastPointIdx + 1; - } - - currentLine.add(new XY(iy, iz, index)); - return true; - } - - - /** Called before consuming first line of file. */ - public void reset() { - data.clear(); - currentLine = new ArrayList<XY>(); - } - - - /** - * Called for each line. Try to extract info from a da66 line. - */ - @Override - protected void handleLine(int lineNum, String line) { - String head = line.substring(0,2); - if (HEAD_HEAD.equals(head)) { - //logger.debug("New station"); - Matcher m = LINE_PATTERN.matcher(line); - if (m.find()) { - // Actually matches! - // TODO 'move' last line to match river axis - // TODO find river axis intersection - currentLine = new ArrayList<XY>(); - double station = stationInKm(Double.parseDouble(m.group(FIELD.STATION.getIdx()))); - data.put(station, currentLine); - } - else { - logger.error("HEAD line bad."); - } - } - else if (HEAD_GEOM.equals(head)) { - Matcher m = LINE_PATTERN.matcher(line); - if (m.find()) { - //logger.info("Station: " + m.group(FIELD.STATION.getIdx())); - // TODO if last station differs, error and abort - if (m.group(FIELD.POINT_1_ID.getIdx()) != null) { - // Point 1 - if(addPoint( - m.group(FIELD.POINT_1_Y.getIdx()), - m.group(FIELD.POINT_1_Z.getIdx()), - m.group(FIELD.POINT_1_ID.getIdx()))) { - // Point added. - } - else { - // Problematic point. - logger.error("A point could not be added"); - } - } - if (m.group(FIELD.POINT_2_ID.getIdx()) != null) { - // Point 2 - if(addPoint( - m.group(FIELD.POINT_2_Y.getIdx()), - m.group(FIELD.POINT_2_Z.getIdx()), - m.group(FIELD.POINT_2_ID.getIdx()))) { - // Point added. - } - else { - // Problematic point. - logger.error("A point could not be added"); - } - } - if (m.group(FIELD.POINT_3_ID.getIdx()) != null) { - // Point 3 - if(addPoint( - m.group(FIELD.POINT_3_Y.getIdx()), - m.group(FIELD.POINT_3_Z.getIdx()), - m.group(FIELD.POINT_3_ID.getIdx()))) { - // Point added. - } - else { - // Problematic point. - logger.error("A point could not be added"); - } - } - if (m.group(FIELD.POINT_4_ID.getIdx()) != null) { - // Point 4 - if(addPoint( - m.group(FIELD.POINT_4_Y.getIdx()), - m.group(FIELD.POINT_4_Z.getIdx()), - m.group(FIELD.POINT_4_ID.getIdx()))) { - // Point added. - } - else { - // Problematic point. - logger.error("A point could not be added"); - } - } - } - else { - logger.warn("Line could not be parsed: "); - logger.warn(line); - } - } - else if (HEAD_GEOM.equals(head)) { - logger.debug("Hit a 88"); - } - else { - logger.error("Do not know how to treat da66 line:"); - logger.error(line); - } - } - - - /** Called when file is fully consumed. */ - @Override - protected void finish() { - // TODO 'move' last line to match river axis - logger.info("Parsed " + data.size() + " lines"); - } - - - /** Parses files given as arguments. */ - public static void main(String [] args) { - - DA66Parser parser = new DA66Parser(); - - logger.warn("Start parsing files."); - for (String arg: args) { - parser.parseDA66s(new File(arg), null); - logger.warn("Parsing a file."); - } - logger.error("Finished parsing files."); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/FlowVelocityMeasurementParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,102 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.flys.importer.ImportFlowVelocityMeasurement; -import de.intevation.flys.importer.ImportFlowVelocityMeasurementValue; - -import java.math.BigDecimal; - -import java.text.DateFormat; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -public class FlowVelocityMeasurementParser extends LineParser { - - private static final Logger log = - Logger.getLogger(FlowVelocityMeasurementParser.class); - - private static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - private static final DateFormat df = - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - - - private List<ImportFlowVelocityMeasurement> measurements; - - private ImportFlowVelocityMeasurement current; - - - public FlowVelocityMeasurementParser() { - measurements = new ArrayList<ImportFlowVelocityMeasurement>(); - } - - - public List<ImportFlowVelocityMeasurement> getMeasurements() { - return measurements; - } - - @Override - protected void reset() { - current = new ImportFlowVelocityMeasurement(); - } - - - @Override - protected void finish() { - current.setDescription(fileName); - measurements.add(current); - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - public void handleMetaLine(String line) { - } - - - public void handleDataLine(String line) { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols.length < 8) { - log.warn("skip invalid data line: '" + line + "'"); - return; - } - - try { - double km = nf.parse(cols[1]).doubleValue(); - double w = nf.parse(cols[5]).doubleValue(); - double q = nf.parse(cols[6]).doubleValue(); - double v = nf.parse(cols[7]).doubleValue(); - - String timestr = cols[3] + " " + cols[4]; - String description = cols.length > 8 ? cols[8] : null; - - current.addValue(new ImportFlowVelocityMeasurementValue( - df.parse(timestr), - new BigDecimal(km), - new BigDecimal(w), - new BigDecimal(q), - new BigDecimal(v), - description - )); - } - catch (ParseException pe) { - log.warn("Unparseable flow velocity values:", pe); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/FlowVelocityModelParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,269 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; - -import java.math.BigDecimal; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportDischargeZone; -import de.intevation.flys.importer.ImportFlowVelocityModel; -import de.intevation.flys.importer.ImportFlowVelocityModelValue; -import de.intevation.flys.utils.EpsilonComparator; - - -public class FlowVelocityModelParser extends LineParser { - - private static final Logger log = - Logger.getLogger(FlowVelocityModelParser.class); - - private static final Pattern META_REGEX = - Pattern.compile(".*Rechnung (.*) \\(Pegel (.*)\\).*"); - - private static final Pattern META_GAUGE = - Pattern.compile("(.*) Q=(\\w*)m3/s"); - - private static final Pattern META_MAINVALUE_A = - Pattern.compile("([a-zA-Z]+)+(\\d+)*"); - - private static final Pattern META_MAINVALUE_B = - Pattern.compile("(([a-zA-Z]+)+(\\d+)*)\\s*-\\s*(([a-zA-Z]+)+(\\d+)*)"); - - private static final Pattern META_MAINVALUE_C = - Pattern.compile("([0-9]++)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*)"); - - private static final Pattern META_MAINVALUE_D = - Pattern.compile("(([0-9]*)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*)) bis (([0-9]*)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*))"); - - private static final Pattern META_MAINVALUE_E = - Pattern.compile("(([a-zA-Z]+)+(\\d+)*) bis (([a-zA-Z]+)+(\\d+)*)"); - - private static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - - private List<ImportFlowVelocityModel> models; - - private ImportFlowVelocityModel current; - - protected String description; - - protected TreeSet<Double> kmExists; - - - public FlowVelocityModelParser() { - models = new ArrayList<ImportFlowVelocityModel>(); - kmExists = new TreeSet<Double>(EpsilonComparator.CMP); - } - - - public List<ImportFlowVelocityModel> getModels() { - return models; - } - - @Override - public void parse(File file) throws IOException { - description = file.getName(); - - super.parse(file); - } - - @Override - protected void reset() { - current = new ImportFlowVelocityModel(description); - kmExists.clear(); - } - - - @Override - protected void finish() { - models.add(current); - - // description = null; - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - protected void handleMetaLine(String line) { - Matcher m = META_REGEX.matcher(line); - - if (m.matches()) { - String mainValueStr = m.group(1); - String gaugeStr = m.group(2); - - Object[] valueData = handleMainValueString(mainValueStr); - Object[] gaugeData = handleGaugeString(gaugeStr); - - if (valueData == null || valueData.length < 2) { - log.warn("skip invalid MainValue part: '" + line + "'"); - return; - } - - if (gaugeData == null || gaugeData.length < 2) { - log.warn("skip invalid gauge part: '" + line + "'"); - return; - } - - if (log.isDebugEnabled()) { - log.debug("Found meta information:"); - log.debug(" Gauge: " + gaugeData[0]); - log.debug(" Value: " + gaugeData[1]); - log.debug(" Lower: " + valueData[0]); - log.debug(" upper: " + valueData[1]); - } - - current.setDischargeZone(new ImportDischargeZone( - (String) gaugeData[0], - (BigDecimal) gaugeData[1], - (String) valueData[0], - (String) valueData[1] - )); - } - } - - - protected Object[] handleMainValueString(String mainValueStr) { - Matcher mA = META_MAINVALUE_A.matcher(mainValueStr); - if (mA.matches()) { - String name = mA.group(0); - - return new Object[] { name, name }; - } - - Matcher mB = META_MAINVALUE_B.matcher(mainValueStr); - if (mB.matches()) { - String lower = mB.group(1); - String upper = mB.group(4); - - return new Object[] { lower, upper }; - } - - Matcher mC = META_MAINVALUE_C.matcher(mainValueStr); - if (mC.matches()) { - String facA = mC.group(1); - String nameA = mC.group(2); - String facB = mC.group(3); - String nameB = mC.group(4); - - String fac = facA != null ? facA : facB; - String name = nameA != null ? nameA : nameB; - - String mainValue = fac + " " + name; - - return new Object[] { mainValue, mainValue }; - } - - Matcher mD = META_MAINVALUE_D.matcher(mainValueStr); - if (mD.matches()) { - String loFacA = mD.group(2); - String loNameA = mD.group(3); - String loFacB = mD.group(4); - String loNameB = mD.group(5); - - String upFacA = mD.group(7); - String upNameA = mD.group(8); - String upFacB = mD.group(9); - String upNameB = mD.group(10); - - String loFac = loFacA != null ? loFacA : loFacB; - String loName = loNameA != null ? loNameA : loNameB; - - String upFac = upFacA != null ? upFacA : upFacB; - String upName = upNameA != null ? upNameA : upNameB; - - String loMainValue = loFac + " " + loName; - String upMainValue = upFac + " " + upName; - - return new Object[] { loMainValue, upMainValue }; - } - - Matcher mE = META_MAINVALUE_E.matcher(mainValueStr); - if (mE.matches()) { - String lower = mE.group(1); - String upper = mE.group(4); - - return new Object[] { lower, upper }; - } - - return null; - } - - - protected Object[] handleGaugeString(String gaugeStr) { - Matcher m = META_GAUGE.matcher(gaugeStr); - - if (m.matches()) { - String name = m.group(1); - String qStr = m.group(2); - - try { - return new Object[] { - name, - new BigDecimal(nf.parse(qStr).doubleValue()) }; - } - catch (ParseException pe) { - log.warn("Could not parse Q value: '" + qStr + "'"); - } - } - - return null; - } - - - protected void handleDataLine(String line) { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols.length < 5) { - log.warn("skip invalid data line: '" + line + "'"); - return; - } - - try { - double km = nf.parse(cols[0]).doubleValue(); - - Double key = Double.valueOf(km); - - if (kmExists.contains(key)) { - log.warn("duplicate stattion '" + km + "': -> ignored"); - return; - } - - double q = nf.parse(cols[1]).doubleValue(); - double total = nf.parse(cols[2]).doubleValue(); - double main = nf.parse(cols[3]).doubleValue(); - double stress = nf.parse(cols[4]).doubleValue(); - - current.addValue(new ImportFlowVelocityModelValue( - new BigDecimal(km), - new BigDecimal(q), - new BigDecimal(total), - new BigDecimal(main), - new BigDecimal(stress) - )); - - kmExists.add(key); - } - catch (ParseException pe) { - log.warn("Unparseable flow velocity values:", pe); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/HYKParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,344 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.ImportHYK; -import de.intevation.flys.importer.ImportHYKEntry; -import de.intevation.flys.importer.ImportHYKFormation; -import de.intevation.flys.importer.ImportHYKFlowZone; -import de.intevation.flys.importer.ImportHYKFlowZoneType; - -import java.io.File; -import java.io.IOException; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; - -import java.util.HashMap; -import java.util.Map; -import java.util.Date; -import java.util.Calendar; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -public class HYKParser -{ - private static Logger log = Logger.getLogger(HYKParser.class); - - public interface Callback { - boolean hykAccept(File file); - void hykParsed(HYKParser parser); - } // interface Callback - - public static enum State { - LINE_1, LINE_2, LINE_3, LINE_4, LINE_5, LINE_6 - }; - - private static final String ENCODING = "ISO-8859-1"; - - protected Map<String, ImportHYKFlowZoneType> flowZoneTypes; - - protected ImportHYK hyk; - - public HYKParser() { - flowZoneTypes = new HashMap<String, ImportHYKFlowZoneType>(); - } - - public ImportHYK getHYK() { - return hyk; - } - - private static Date yearToDate(Integer year) { - if (year == null) { - return null; - } - Calendar cal = Calendar.getInstance(); - cal.set(year, 0, 1, 12, 0, 0); - long ms = cal.getTimeInMillis(); - cal.setTimeInMillis(ms - ms%1000); - return cal.getTime(); - } - - public boolean parse(File file) { - - boolean debug = log.isDebugEnabled(); - - log.info("Parsing HYK file '" + file + "'"); - - LineNumberReader in = null; - - String description = - file.getParentFile().getName() + "/" + file.getName(); - - hyk = new ImportHYK(null, description); - - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line; - - State state = State.LINE_1; - - int numFormations = 0; - - BigDecimal km = null; - BigDecimal top = null; - BigDecimal bottom = null; - BigDecimal distanceVL = null; - BigDecimal distanceHF = null; - BigDecimal distanceVR = null; - - Integer year = null; - int numZones = 0; - - ImportHYKFlowZoneType [] fzts = null; - BigDecimal [] coords = null; - int coordPos = 0; - - ImportHYKEntry entry = null; - ImportHYKFormation formation = null; - - while ((line = in.readLine()) != null) { - - if (line.startsWith("*") || line.startsWith("----")) { - continue; - } - - line = line.trim(); - - if (state != State.LINE_5 && line.length() == 0) { - continue; - } - - String [] parts = line.split("\\s+"); - - if (debug) { - log.debug("'" + line + "': " + state); - } - - switch (state) { - case LINE_1: - if (parts.length < 2) { - log.error("HYK 1: not enough elements in line " + - in.getLineNumber()); - return false; - } - - if (parts.length == 2) { - // no year given - year = null; - } - else { - try { - year = Integer.valueOf(parts[1]); - } - catch (NumberFormatException nfe) { - log.error( - "year is not an integer in line " + - in.getLineNumber()); - return false; - } - } - try { - km = new BigDecimal(parts[0]); - numFormations = Integer.parseInt( - parts[parts.length > 2 ? 2 : 1]); - } - catch (NumberFormatException nfe) { - log.error( - "parsing number of formations " + - "or km failed in line " + in.getLineNumber()); - return false; - } - entry = new ImportHYKEntry(hyk, km, yearToDate(year)); - hyk.addEntry(entry); - - state = State.LINE_2; - break; - - case LINE_2: - if (parts.length < 3) { - log.error("HYK 2: not enough elements in line " + - in.getLineNumber()); - return false; - } - try { - numZones = Integer.parseInt(parts[0]); - bottom = new BigDecimal(parts[1]); - top = new BigDecimal(parts[2]); - } - catch (NumberFormatException nfe) { - log.error( - "HYK: parsing num zones, bottom or top height " + - "failed in line " + in.getLineNumber()); - return false; - } - formation = new ImportHYKFormation(); - formation.setBottom(bottom); - formation.setTop(top); - entry.addFormation(formation); - - state = State.LINE_3; - break; - - case LINE_3: - if (parts.length != numZones) { - log.error( - "HYK: number of flow zones mismatches " + - "in line " + in.getLineNumber()); - return false; - } - - fzts = new ImportHYKFlowZoneType[parts.length]; - for (int i = 0; i < fzts.length; ++i) { - fzts[i] = getFlowZoneType(parts[i]); - } - coords = new BigDecimal[numZones]; - state = State.LINE_4; - break; - - case LINE_4: - try { - int N = Math.min(parts.length, coords.length); - for (coordPos = 0; coordPos < N; ++coordPos) { - coords[coordPos] = - new BigDecimal(parts[coordPos]); - } - } - catch (NumberFormatException nfe) { - log.error("HYK: cannot parse number in line " + - in.getLineNumber()); - return false; - } - state = State.LINE_5; - break; - - case LINE_5: - if (parts.length + coordPos < coords.length) { - log.error("HYK 5: not enough elements in line " + - in.getLineNumber()); - return false; - } - try { - for (int i = 0; - i < parts.length && coordPos < coords.length; - ++i, ++coordPos - ) { - coords[coordPos] = new BigDecimal(parts[i]); - } - } - catch (NumberFormatException nfe) { - log.error("HYK: cannot parse number in line " + - in.getLineNumber()); - return false; - } - for (int i = 0; i < coords.length; ++i) { - BigDecimal a = coords[i]; - BigDecimal b = coords[i == coords.length-1 ? i : i+1]; - if (a.compareTo(b) > 0) { - log.warn("HYK: zone coordinates swapped in line " + - in.getLineNumber()); - BigDecimal c = a; a = b; b = c; - } - ImportHYKFlowZone zone = new ImportHYKFlowZone( - formation, fzts[i], a, b); - formation.addFlowZone(zone); - } - state = State.LINE_6; - break; - - case LINE_6: - if (parts.length < 3) { - log.error("HYK 6: not enough elements in line " + - in.getLineNumber()); - return false; - } - try { - distanceVL = new BigDecimal(parts[0]); - distanceHF = new BigDecimal(parts[1]); - distanceVR = new BigDecimal(parts[2]); - } - catch (NumberFormatException nfe) { - log.error("HYK: cannot parse number in line " + - in.getLineNumber()); - return false; - } - formation.setDistanceVL(distanceVL); - formation.setDistanceHF(distanceHF); - formation.setDistanceVR(distanceVR); - - // continue with next formation. - state = --numFormations > 0 // formations left? - ? State.LINE_2 - : State.LINE_1; - break; - } - } - } - catch (IOException ioe) { - log.error("HYK: Error reading file.", ioe); - return false; - } - finally { - if (in != null) { - try { - in.close(); - } - catch (IOException ioe) { - log.error("HYK: Error closing file.", ioe); - } - } - } - return true; - } - - protected ImportHYKFlowZoneType getFlowZoneType(String name) { - name = name.toUpperCase(); - ImportHYKFlowZoneType fzt = flowZoneTypes.get(name); - if (fzt == null) { - log.info("New flow zone type: " + name); - fzt = new ImportHYKFlowZoneType(name); - flowZoneTypes.put(name, fzt); - } - return fzt; - } - - protected void reset() { - hyk = null; - } - - public void parseHYKs(File root, final Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".hyk") - && (callback == null || callback.hykAccept(file))) { - reset(); - boolean success = parse(file); - log.info("parsing " + (success ? "succeeded" : "failed")); - if (success && callback != null) { - callback.hykParsed(HYKParser.this); - } - } - return true; - } - }); - } - - public static void main(String [] args) { - - HYKParser parser = new HYKParser(); - - for (String arg: args) { - parser.parseHYKs(new File(arg), null); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/InfoGewParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,138 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; - -import java.util.List; -import java.util.ArrayList; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import org.apache.log4j.Logger; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.ImportRiver; - - -/** Processes files mentioned in an info file for a river. */ -public class InfoGewParser -{ - private static Logger log = Logger.getLogger(InfoGewParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final Pattern GEWAESSER = - Pattern.compile("^\\s*Gew\u00e4sser\\s*:\\s*(.+)"); - - public static final Pattern WST_DATEI = - Pattern.compile("^\\s*WSTDatei\\s*:\\s*(.+)"); - - public static final Pattern BB_INFO = - Pattern.compile("^\\s*B\\+B-Info\\s*:\\s*(.+)"); - - protected ArrayList<ImportRiver> rivers; - - protected AnnotationClassifier annotationClassifier; - - public InfoGewParser() { - this(null); - } - - public InfoGewParser(AnnotationClassifier annotationClassifier) { - rivers = new ArrayList<ImportRiver>(); - this.annotationClassifier = annotationClassifier; - } - - public List<ImportRiver> getRivers() { - return rivers; - } - - public static final String normalize(String f) { - return f.replace("\\", "/").replace("/", File.separator); - } - - /** Handle a gew, wst, or bb_info file. */ - public void parse(File file) throws IOException { - - LineNumberReader in = null; - - File root = file.getParentFile(); - - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = null; - - String riverName = null; - File wstFile = null; - File bbInfoFile = null; - - while ((line = in.readLine()) != null) { - if ((line = line.trim()).length() == 0) { - continue; - } - Matcher m = GEWAESSER.matcher(line); - - if (m.matches()) { - String river = m.group(1); - log.info("Found river '" + river + "'"); - if (riverName != null) { - rivers.add(new ImportRiver( - riverName, - wstFile, - bbInfoFile, - annotationClassifier)); - } - riverName = river; - wstFile = null; - bbInfoFile = null; - } - else if ((m = WST_DATEI.matcher(line)).matches()) { - String wstFilename = m.group(1); - File wst = new File(wstFilename = normalize(wstFilename)); - if (!wst.isAbsolute()) { - wst = new File(root, wstFilename); - } - wst = FileTools.repair(wst); - log.info("Found wst file '" + wst + "'"); - if (!wst.isFile() || !wst.canRead()) { - log.warn("cannot access WST file '" + wstFilename + "'"); - continue; - } - wstFile = wst; - } - else if ((m = BB_INFO.matcher(line)).matches()) { - //TODO: Make it relative to the wst file. - String bbInfo = m.group(1); - bbInfoFile = new File(normalize(bbInfo)); - } - } - if (riverName != null) { - rivers.add(new ImportRiver( - riverName, - wstFile, - bbInfoFile, - annotationClassifier)); - } - } - finally { - if (in != null) { - in.close(); - } - } - - for (ImportRiver river: rivers) { - river.parseDependencies(); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/LineParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,139 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; - -import java.text.DateFormat; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import org.apache.log4j.Logger; - - -/** - * Base-Class for prasers for line-based file formats. - * Calls reset(), then read line by line, calling handleLine() for each, - * then calls finish(). - */ -public abstract class LineParser { - - /** Private logger. */ - private static final Logger log = Logger.getLogger(LineParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final Locale DEFAULT_LOCALE = Locale.GERMAN; - - public static final String START_META_CHAR = "#"; - public static final String SEPERATOR_CHAR = ";"; - - - protected abstract void handleLine(int lineNum, String line); - - protected abstract void reset(); - - protected abstract void finish(); - - /** Name of file parsed. */ - protected String fileName; - - protected File inputFile; - - - /** - * This method reads each line of <i>file</i>. At the beginning, - * <i>reset()</i> is called; afterwards for each line <i>handleLine()</i> is - * called; at the end <i>finish</i> is called. - * - * @param file The file which should be parsed. - */ - public void parse(File file) throws IOException { - log.info("Parsing file '" + file + "'"); - - inputFile = file; - - fileName = file.getName(); - - reset(); - - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = null; - int lineNum = 1; - while ((line = in.readLine()) != null) { - if ((line = line.trim()).length() == 0) { - lineNum++; - continue; - } - - handleLine(lineNum++, line); - } - } - finally { - if (in != null) { - in.close(); - } - } - - finish(); - } - - - /** Returns the name of the file parsed. */ - protected String getFileName() { - return fileName; - } - - /** Returns the file currently parsed. */ - protected File getInputFile() { - return inputFile; - } - - - protected static String stripMetaLine(String line) { - String tmp = line.substring(1, line.length()); - - if (tmp.startsWith(" ")) { - return tmp.substring(1, tmp.length()); - } - else { - return tmp; - } - } - - public static double getDouble(String doubleString) throws ParseException { - NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); - Number value = nf.parse(doubleString); - - return value.doubleValue(); - } - - public static Date getDate(String dateString) throws ParseException { - DateFormat df = SimpleDateFormat.getDateInstance( - SimpleDateFormat.MEDIUM, DEFAULT_LOCALE); - - return df.parse(dateString); - } - - - public static Date getDateFromYear(int year) { - Calendar cal = Calendar.getInstance(); - cal.set(year, 0, 1); - - return cal.getTime(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/MeasurementStationsParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,187 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.math.BigDecimal; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportMeasurementStation; -import de.intevation.flys.importer.ImportRange; -import de.intevation.flys.importer.ImportTimeInterval; - - -public class MeasurementStationsParser extends LineParser { - - public static class MeasurementStationParserException extends Exception { - - private static final long serialVersionUID = 1L; - - public MeasurementStationParserException(String msg) { - super(msg); - } - } - - public static final int MIN_COLUMNS = 10; - - private static final Logger log = Logger - .getLogger(MeasurementStationsParser.class); - - private List<ImportMeasurementStation> measurementStations; - private ImportMeasurementStation current; - - @Override - protected void reset() { - this.measurementStations = new ArrayList<ImportMeasurementStation>(); - } - - @Override - protected void finish() { - } - - @Override - protected void handleLine(int lineNum, String line) { - if (line == null || line.startsWith(START_META_CHAR)) { - log.info("skip meta information at line " + lineNum); - return; - } - - try { - current = new ImportMeasurementStation(); - handleDataLine(line); - measurementStations.add(current); - } - catch (MeasurementStationParserException e) { - log.warn("Problem in line " + lineNum + ": " + e.getMessage()); - } - } - - public List<ImportMeasurementStation> getMeasurementStations() { - return measurementStations; - } - - protected void handleDataLine(String line) - throws MeasurementStationParserException { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols == null || cols.length < MIN_COLUMNS) { - int num = cols != null ? cols.length : 0; - throw new MeasurementStationParserException("Not enough columns: " - + num); - } - - current.name = getName(cols); - current.station = getStation(cols); - current.range = getRange(cols); - current.measurementType = getMeasurementType(cols); - current.riverside = getRiverside(cols); - current.gauge = getGauge(cols); - current.observationTimerange = getObservationTimerange(cols); - current.operator = getOperator(cols); - current.description = getDescription(cols); - - log.debug("Found new measurement station '" + current.name + "' at km " - + current.station); - } - - protected String getName(String[] cols) - throws MeasurementStationParserException { - if (cols[0] == null || cols[0].length() == 0) { - throw new MeasurementStationParserException("invalid name '" - + cols[0] + "'"); - } - - return cols[0]; - } - - protected double getStation(String[] cols) - throws MeasurementStationParserException { - if (cols[1] == null || cols[1].length() == 0) { - throw new MeasurementStationParserException("invalid station '" - + cols[1] + "'"); - } - - try { - return getDouble(cols[1]); - } - catch (ParseException e) { - throw new MeasurementStationParserException( - "unable to parse station: " + e.getMessage()); - } - } - - protected ImportRange getRange(String[] cols) { - if (cols[4] == null || cols[4].length() == 0) { - log.warn("No upper value for range found in '" + cols[4] + "'"); - return null; - } - - if (cols[5] == null || cols[5].length() == 0) { - log.warn("No upper value for range found in '" + cols[5] + "'"); - return null; - } - - try { - double lower = getDouble(cols[4]); - double upper = getDouble(cols[5]); - - return new ImportRange(new BigDecimal(lower), new BigDecimal(upper)); - } - catch (ParseException e) { - log.warn("unable to parse range: " + e.getMessage()); - return null; - } - } - - protected String getMeasurementType(String[] cols) - throws MeasurementStationParserException { - if (cols[2] == null || cols[2].length() == 0) { - throw new MeasurementStationParserException( - "invalid measurement type '" + cols[2] + "'"); - } - - return cols[2]; - } - - protected String getRiverside(String[] cols) { - return cols[3]; - } - - protected String getGauge(String[] cols) { - if (cols[6] == null || cols[6].length() == 0) { - log.warn("invalid gauge found: '" + cols[6] + "'"); - } - - return cols[6]; - } - - protected ImportTimeInterval getObservationTimerange(String[] cols) { - if (cols[8] == null || cols[8].length() == 0) { - log.warn("Found invalid observation time '" + cols[8] + "'"); - } - - try { - Date date = getDate(cols[8]); - - if (date != null) { - return new ImportTimeInterval(date); - } - log.warn("Observation time date invalid: '" + cols[8] + "'"); - } - catch (ParseException pe) { - log.warn("Observation time date not parseable: '" + cols[8] + "'"); - return null; - } - return null; - } - - protected String getOperator(String[] cols) { - return cols[9]; - } - - protected String getDescription(String[] cols) { - return cols.length > 10 ? cols[10] : null; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/MorphologicalWidthParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.math.BigDecimal; - -import java.text.NumberFormat; -import java.text.ParseException; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportMorphWidth; -import de.intevation.flys.importer.ImportMorphWidthValue; -import de.intevation.flys.importer.ImportUnit; - - -public class MorphologicalWidthParser extends LineParser { - - private static final Logger log = - Logger.getLogger(MorphologicalWidthParser.class); - - public static final NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); - - public static final Pattern META_UNIT = - Pattern.compile("^Einheit: \\[(.*)\\].*"); - - protected List<ImportMorphWidth> morphWidths; - - protected ImportMorphWidth current; - - - public MorphologicalWidthParser() { - morphWidths = new ArrayList<ImportMorphWidth>(); - } - - - @Override - protected void reset() { - current = new ImportMorphWidth(); - } - - - @Override - protected void finish() { - if (current != null) { - morphWidths.add(current); - } - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - protected void handleMetaLine(String line) { - if (handleMetaUnit(line)) { - return; - } - else { - log.warn("MWP: Unknown meta line: '" + line + "'"); - } - } - - - protected boolean handleMetaUnit(String line) { - Matcher m = META_UNIT.matcher(line); - - if (m.matches()) { - String unit = m.group(1); - - current.setUnit(new ImportUnit(unit)); - - return true; - } - - return false; - } - - - protected void handleDataLine(String line) { - String[] vals = line.split(SEPERATOR_CHAR); - - if (vals == null || vals.length < 2) { - log.warn("MWP: skip invalid data line: '" + line + "'"); - return; - } - - try { - BigDecimal km = new BigDecimal(nf.parse(vals[0]).doubleValue()); - BigDecimal width = new BigDecimal(nf.parse(vals[1]).doubleValue()); - - String desc = vals.length > 2 ? vals[2] : null; - - current.addValue(new ImportMorphWidthValue( - km, - width, - desc - )); - } - catch (ParseException pe) { - log.warn("MWP: unparseable number in data row: " + line); - } - } - - - public List<ImportMorphWidth> getMorphologicalWidths() { - return morphWidths; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/PRFParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,419 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.util.Map; -import java.util.TreeMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.io.File; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.XY; - -import de.intevation.artifacts.common.utils.FileTools; - - -/** - * Parse files in .prf format and generate a mapping of double - * (km) to List of Points (XY). - */ -public class PRFParser implements CrossSectionParser -{ - private static Logger log = Logger.getLogger(PRFParser.class); - - public static final String ENCODING = - System.getProperty("flys.backend.prf.encoding", "ISO-8859-1"); - - public static final Pattern DATA_PATTERN = - Pattern.compile( - "\\((\\d+)x\\s*,\\s*(\\d+)\\(" + - "\\s*f(\\d+)\\.(\\d+)\\s*,\\s*f(\\d+)\\.(\\d+)\\s*\\)?\\)?"); - - public static final Pattern KM_PATTERN = - Pattern.compile("\\((\\d+)x\\s*,\\s*f(\\d+)\\.(\\d+)\\s*\\)?"); - - public static final Pattern YEAR_PATTERN = - Pattern.compile("(\\d{4})"); - - public static final int MIN_YEAR = 1800; - public static final int MAX_YEAR = 2100; - - public static class DataFormat { - - protected int deleteChars; - protected int maxRepetitions; - protected int firstIntegerPlaces; - protected int firstFractionPlaces; - protected int secondIntegerPlaces; - protected int secondFractionPlaces; - - protected double firstShift; - protected double secondShift; - - public DataFormat() { - } - - public DataFormat(Matcher m) { - deleteChars = Integer.parseInt(m.group(1)); - maxRepetitions = Integer.parseInt(m.group(2)); - firstIntegerPlaces = Integer.parseInt(m.group(3)); - firstFractionPlaces = Integer.parseInt(m.group(4)); - secondIntegerPlaces = Integer.parseInt(m.group(5)); - secondFractionPlaces = Integer.parseInt(m.group(6)); - - firstShift = Math.pow(10, firstFractionPlaces); - secondShift = Math.pow(10, secondFractionPlaces); - } - - public int extractData(String line, List<XY> kmData) { - int L = line.length(); - if (L <= deleteChars) { - return -1; - } - - int pos = deleteChars; - - boolean debug = log.isDebugEnabled(); - - - int rep = 0; - for (;rep < maxRepetitions; ++rep) { - if (pos >= L || pos + firstIntegerPlaces >= L) { - break; - } - String first = line.substring( - pos, pos + firstIntegerPlaces); - - String second = line.substring( - pos + firstIntegerPlaces, - Math.min(L, pos+firstIntegerPlaces+secondIntegerPlaces)); - - double x, y; - try { - x = Double.parseDouble(first); - y = Double.parseDouble(second); - } - catch (NumberFormatException nfe) { - // broken line -> substract from dataset skip - return -1; - } - - if (first.indexOf('.') < 0) { - x /= firstShift; - } - - if (firstFractionPlaces > 0) { - x = (int)(x*firstShift)/firstShift; - } - - if (second.indexOf('.') < 0) { - y /= secondShift; - } - - if (secondFractionPlaces > 0) { - y = (int)(y*secondShift)/secondShift; - } - - kmData.add(new XY(x, y, kmData.size())); - - pos += firstIntegerPlaces + secondIntegerPlaces; - } - - return rep == maxRepetitions ? 1 : 0; - } - } // class DataFormat - - public static class KMFormat { - - protected int deleteChars; - protected int integerPlaces; - protected int fractionPlaces; - - protected double shift; - - public KMFormat() { - } - - public KMFormat(Matcher m) { - deleteChars = Integer.parseInt(m.group(1)); - integerPlaces = Integer.parseInt(m.group(2)); - fractionPlaces = Integer.parseInt(m.group(3)); - - shift = Math.pow(10, fractionPlaces); - } - - public double extractKm(String line) throws NumberFormatException { - - if (line.length() <= deleteChars) { - throw new NumberFormatException("line too short"); - } - - String kmS = - line.substring(deleteChars, deleteChars+integerPlaces); - - double km = Double.parseDouble(kmS.trim()); - - if (kmS.indexOf('.') < 0) { - km /= shift; - } - - return fractionPlaces > 0 - ? ((int)(km*shift))/shift - : km; - } - } // class KMFormat - - protected Map<Double, List<XY>> data; - - protected Integer year; - - protected String description; - - - public PRFParser() { - data = new TreeMap<Double, List<XY>>(); - } - - @Override - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - @Override - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public Map<Double, List<XY>> getData() { - return data; - } - - public void setData(Map<Double, List<XY>> data) { - this.data = data; - } - - protected void sortLists() { - for (List<XY> xy: data.values()) { - Collections.sort(xy); - } - } - - public static final Integer findYear(String s) { - Matcher m = YEAR_PATTERN.matcher(s); - while (m.find()) { - int year = Integer.parseInt(m.group(1)); - if (year >= MIN_YEAR && year <= MAX_YEAR) { - return Integer.valueOf(year); - } - } - return null; - } - - public boolean parse(File file) { - - if (!(file.isFile() && file.canRead())) { - log.warn("PRF: cannot open file '" + file + "'"); - return false; - } - - log.info("parsing PRF file: '" + file + "'"); - - description = FileTools.removeExtension(file.getName()); - - year = findYear(file.getName()); - - if (year == null) { - File parent = file.getParentFile(); - if (parent != null) { - description = parent.getName() + "/" + description; - year = findYear(parent.getName()); - } - } - - if (year != null) { - log.info("year of sounding: " + year); - } - - LineNumberReader in = null; - - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = in.readLine(); - - if (line == null || (line = line.trim()).length() == 0) { - log.warn("PRF: file is empty."); - return false; - } - - Matcher m = DATA_PATTERN.matcher(line); - - if (!m.matches()) { - log.warn("PRF: First line does not look like a PRF data pattern."); - return false; - } - - DataFormat dataFormat = new DataFormat(m); - - if ((line = in.readLine()) == null - || (line = line.trim()).length() == 0) { - log.warn("PRF: premature EOF. Expected integer in line 2"); - return false; - } - - try { - if (Integer.parseInt(line) != dataFormat.maxRepetitions) { - log.warn("PRF: Expected " + - dataFormat.maxRepetitions + " in line 2"); - return false; - } - } - catch (NumberFormatException nfe) { - log.warn("PRF: invalid integer in line 2", nfe); - return false; - } - - if ((line = in.readLine()) == null) { - log.warn( - "PRF: premature EOF. Expected pattern for km extraction"); - return false; - } - - m = KM_PATTERN.matcher(line); - - if (!m.matches()) { - log.warn( - "PRF: line 4 does not look like a PRF km extraction pattern."); - return false; - } - - KMFormat kmFormat = new KMFormat(m); - - if ((line = in.readLine()) == null - || (line = line.trim()).length() == 0) { - log.warn("PRF: premature EOF. Expected skip row count."); - return false; - } - - int lineSkipCount; - try { - if ((lineSkipCount = Integer.parseInt(line)) < 0) { - throw new IllegalArgumentException(lineSkipCount + " < 0"); - } - } - catch (NumberFormatException nfe) { - log.warn( - "PRF: line 5 is not an positive integer."); - return false; - } - - int skip = lineSkipCount; - - while ((line = in.readLine()) != null) { - if (skip > 0) { - --skip; - continue; - } - double km; - try { - km = kmFormat.extractKm(line); - } - catch (NumberFormatException iae) { - log.warn("PRF: cannot extract km in line " + in.getLineNumber()); - return false; - } - - Double station = Double.valueOf(km); - - List<XY> kmData = data.get(station); - - if (kmData == null) { - //log.debug("found new km: " + station); - kmData = new ArrayList<XY>(); - data.put(station, kmData); - } - - int c = dataFormat.extractData(line, kmData); - if (c < 1) { - skip = lineSkipCount + c; - } - } - - // sort all the lists by x and index - sortLists(); - } - catch (IOException ioe) { - log.error("Error reading PRF file.", ioe); - return false; - } - finally { - if (in != null) { - try { - in.close(); - } - catch (IOException ioe) { - log.error("Error closing PRF file.", ioe); - } - } - } - - return true; - } - - public void reset() { - data.clear(); - year = null; - description = null; - } - - public void parsePRFs(File root, final CrossSectionParser.Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".prf") - && (callback == null || callback.accept(file))) { - reset(); - boolean success = parse(file); - log.info("parsing " + (success ? "succeeded" : "failed")); - if (success && callback != null) { - callback.parsed(PRFParser.this); - } - } - return true; - } - }); - } - - public static void main(String [] args) { - - PRFParser parser = new PRFParser(); - - for (String arg: args) { - parser.parsePRFs(new File(arg), null); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/PegelGltParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,102 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; - -import java.util.List; -import java.util.ArrayList; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import java.math.BigDecimal; - -import org.apache.log4j.Logger; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.ImportGauge; -import de.intevation.flys.importer.ImportRange; - -public class PegelGltParser -{ - private static Logger log = Logger.getLogger(PegelGltParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final String KM = "km:"; - - protected List<ImportGauge> gauges; - - public PegelGltParser() { - gauges = new ArrayList<ImportGauge>(); - } - - public List<ImportGauge> getGauges() { - return gauges; - } - - public void parse(File file) throws IOException { - - File parent = file.getParentFile(); - - log.info("parsing GLT file '" + file + "'"); - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = null; - while ((line = in.readLine()) != null) { - if ((line = line.trim()).length() == 0) { - continue; - } - - int kmPos = line.indexOf(KM); - if (kmPos < 0) { - log.warn("GLT: no gauge found in line " + in.getLineNumber()); - continue; - } - - String gaugeName = line.substring(0, kmPos).trim(); - log.info("Found gauge '" + gaugeName + "'"); - - line = line.substring(kmPos + KM.length()).trim(); - - String [] parts = line.split("\\s+"); - if (parts.length < 4) { - log.warn("GLT: line " + in.getLineNumber() - + " has not enough columns."); - continue; - } - - BigDecimal from = new BigDecimal(parts[0].replace(",", ".")); - BigDecimal to = new BigDecimal(parts[1].replace(",", ".")); - if (from.compareTo(from) > 0) { - BigDecimal t = from; from = to; to = t; - } - ImportRange range = new ImportRange(from, to); - File staFile = FileTools.repair(new File(parent, parts[2])); - File atFile = FileTools.repair(new File(parent, parts[3])); - - if (log.isDebugEnabled()) { - log.debug("\tfrom: " + from); - log.debug("\tto: " + to); - log.debug("\tsta: " + staFile); - log.debug("\tat: " + atFile); - } - - gauges.add(new ImportGauge(range, staFile, atFile)); - } - } - finally { - if (in != null) { - in.close(); - } - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/SQRelationParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportSQRelation; -import de.intevation.flys.importer.ImportSQRelationValue; -import de.intevation.flys.importer.ImportTimeInterval; - - -public class SQRelationParser extends LineParser { - - private static final Logger log = - Logger.getLogger(SQRelationParser.class); - - private static final Pattern TIMERANGE_REGEX = - Pattern.compile(".*Zeitraum.*\\s(\\w*)-(\\w*).*"); - - private static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - - private List<ImportSQRelation> relations; - - private ImportSQRelation current; - - private String currentDescription; - - - public SQRelationParser() { - relations = new ArrayList<ImportSQRelation>(); - } - - - public List<ImportSQRelation> getSQRelations() { - return relations; - } - - @Override - public void parse(File file) throws IOException { - this.currentDescription = file.getName(); - super.parse(file); - } - - - @Override - protected void reset() { - current = new ImportSQRelation(); - } - - - @Override - protected void finish() { - if (current != null) { - current.setDescription(currentDescription); - relations.add(current); - } - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - protected void handleMetaLine(String line) { - Matcher m = TIMERANGE_REGEX.matcher(line); - - if (m.matches()) { - String lo = m.group(1); - String hi = m.group(2); - - log.debug("Found timerange " + lo + " - " + hi); - - try { - int low = nf.parse(lo).intValue(); - int high = nf.parse(hi).intValue(); - - current.setTimeInterval(new ImportTimeInterval( - getDateFromYear(low), - getDateFromYear(high) - )); - } - catch (ParseException nfe) { - log.warn("Cannot parse time range.", nfe); - } - } - } - - - protected void handleDataLine(String line) { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols.length < 14) { - log.warn("skip invalid data line: '" + line + "'"); - return; - } - - Double km = parseDouble(cols[3], line); - Double a = parseDouble(cols[6], line); - Double b = parseDouble(cols[7], line); - Double qMax = parseDouble(cols[8], line); - Double rSq = parseDouble(cols[9], line); - Integer nTot = parseInteger(cols[10], line); - Integer nOutlier = parseInteger(cols[11], line); - Double cFer = parseDouble(cols[12], line); - Double cDuan = parseDouble(cols[13], line); - if (km == null || a == null || b == null || - qMax == null || cols[1].length() == 0) { - if (km == null) { - log.error("No km for measurement station: Can not reference measurement station: " - + line); - } - if ( a == null || b == null || - qMax == null || cols[1].length() == 0) { - log.error("Incomplete SQ-relation row (missing a, b, Qmax or parameter): " - + line); - } - return; - } - current.addValue(new ImportSQRelationValue( - cols[1], - km, - a, - b, - qMax, - rSq, - nTot, - nOutlier, - cFer, - cDuan)); - } - - private Double parseDouble(String value, String line) { - Double result = null; - try { - result = Double.valueOf(value.replace(",", ".")); - } - catch (NumberFormatException nfe) { - log.warn("Unparseable " + value + " in sq relation row: " + line); - } - return result; - } - - private Integer parseInteger(String value, String line) { - Integer result = null; - try { - result = Integer.valueOf(value); - } - catch (NumberFormatException nfe) { - log.warn("Unparseable " + value + " in sq relation row: " + line); - } - return result; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/SedimentDensityParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,162 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.flys.importer.ImportDepth; -import de.intevation.flys.importer.ImportSedimentDensity; -import de.intevation.flys.importer.ImportSedimentDensityValue; - -import java.io.File; -import java.io.IOException; - -import java.math.BigDecimal; - -import java.text.NumberFormat; -import java.text.ParseException; - -import java.util.ArrayList; -import java.util.List; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -public class SedimentDensityParser extends LineParser { - - private static final Logger log = - Logger.getLogger(SedimentDensityParser.class); - - public static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - public static final Pattern META_DEPTH = - Pattern.compile("^Tiefe: (\\w++)-(\\w++)( (\\w++))?.*"); - - protected List<ImportSedimentDensity> sedimentDensities; - - protected ImportSedimentDensity current; - - protected String currentDescription; - - - public SedimentDensityParser() { - sedimentDensities = new ArrayList<ImportSedimentDensity>(); - } - - - @Override - public void parse(File file) throws IOException { - currentDescription = file.getName(); - - super.parse(file); - } - - - @Override - protected void reset() { - current = new ImportSedimentDensity(currentDescription); - } - - - @Override - protected void finish() { - if (current != null) { - sedimentDensities.add(current); - } - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - protected void handleMetaLine(String line) { - if (handleMetaDepth(line)) { - return; - } - else { - log.warn("Unknown meta line: '" + line + "'"); - } - } - - - protected boolean handleMetaDepth(String line) { - Matcher m = META_DEPTH.matcher(line); - - if (m.matches()) { - String lo = m.group(1); - String up = m.group(2); - - log.info("Found sediment density depth: " + lo + " - " + up + " cm"); - - try { - ImportDepth depth = new ImportDepth( - new BigDecimal(nf.parse(lo).doubleValue()), - new BigDecimal(nf.parse(up).doubleValue()) - ); - - current.setDepth(depth); - - return true; - } - catch (ParseException pe) { - log.warn("Unparseable numbers in: '" + line + "'"); - } - } - else { - log.debug("Meta line doesn't contain depth information: " + line); - } - - return false; - } - - - protected void handleDataLine(String line) { - String[] vals = line.split(SEPERATOR_CHAR); - - if (vals == null || vals.length < 3) { - log.warn("skip invalid data line: '" + line + "'"); - return; - } - - BigDecimal km = null; - BigDecimal shoreOffset = null; - BigDecimal density = null; - try { - km = new BigDecimal(nf.parse(vals[0]).doubleValue()); - density = new BigDecimal(nf.parse(vals[2]).doubleValue()); - if (!vals[1].isEmpty()) { - shoreOffset = new BigDecimal(nf.parse(vals[1]).doubleValue()); - } - } - catch (ParseException pe) { - log.warn("Unparseable numbers in '" + line + "'"); - } - - if (km == null || density == null) { - log.warn("SDP: No km nor density given. Skip line"); - return; - } - - BigDecimal year = null; - - current.addValue(new ImportSedimentDensityValue( - km, - shoreOffset, - density, - year, - currentDescription)); - } - - - public List<ImportSedimentDensity> getSedimentDensities() { - return sedimentDensities; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/SedimentYieldParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,393 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; - -import java.text.NumberFormat; -import java.text.ParseException; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportGrainFraction; -import de.intevation.flys.importer.ImportSedimentYield; -import de.intevation.flys.importer.ImportSedimentYieldValue; -import de.intevation.flys.importer.ImportTimeInterval; -import de.intevation.flys.importer.ImportUnit; -import de.intevation.flys.model.GrainFraction; - - -public class SedimentYieldParser extends LineParser { - - private static final Logger log = - Logger.getLogger(SedimentYieldParser.class); - - - public static final NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); - - - public static final String FRAKTION_START = "Fraktion:"; - - public static final String FRACTION_COARSE_STR = - ".*Grobkorn.*"; - - public static final String FRACTION_FINE_MIDDLE_STR = - ".*Fein-Mittel-Kies.*"; - - public static final String FRACTION_SAND = - ".*Sand.*"; - - public static final String FRACTION_SUSP_SAND = - ".*susp_Sand.*"; - - public static final String FRACTION_SUSP_SAND_BED = - ".*bettbild_Anteil_susp_Sand.*"; - - public static final String FRACTION_SUSP_SAND_BED_EPOCH = - ".*susp_Sand_bettbildAnteil.*"; - - public static final String FRACTION_SUSPENDED_SEDIMENT = - ".*Schwebstoff.*"; - - public static final String FRACTION_TOTAL = - ".*gesamt.*"; - - - public static final Pattern TIMEINTERVAL_SINGLE = - Pattern.compile("\\D*([0-9]+?)\\D*"); - - public static final Pattern TIMEINTERVAL_EPOCH = - Pattern.compile("\\D*([0-9]+?)\\s*-\\s*([0-9]+?)\\D*"); - - public static final Pattern META_FRACTION = - Pattern.compile("^Fraktion: (.*)"); - - public static final Pattern META_UNIT = - Pattern.compile("^Einheit: \\[(.*)\\].*"); - - public static final Pattern META_COLUMN_NAMES = - Pattern.compile("^Fluss-km.*"); - - public static final Pattern META_GRAIN_FRACTION_A = - Pattern.compile("\\D*(([0-9]+?,[0-9]+?)\\s*-|([0-9]++)\\s*-)(([0-9]+?,[0-9]+?)|([0-9]++))\\s*([a-zA-Z]+?)\\W*\\D*"); - - public static final Pattern META_GRAIN_FRACTION_B = - Pattern.compile("(<|>){1}\\s*(\\w++)\\s*(([0-9]+?,[0-9]+?)\\s*-|([0-9]++)\\s*-)(([0-9]+?,[0-9]+?)|([0-9]++))\\s*([a-zA-Z]+?)"); - - public static final Pattern META_GRAIN_FRACTION_C = - Pattern.compile("(<|>){1}\\s*((([0-9]+?,[0-9]+?)|([0-9]++))\\s*(\\w+))"); - - - protected List<ImportSedimentYield> sedimentYields; - - protected ImportSedimentYield[] current; - - protected ImportGrainFraction grainFraction; - - protected ImportUnit unit; - - protected String description; - - protected String[] columnNames; - - - public SedimentYieldParser() { - sedimentYields = new ArrayList<ImportSedimentYield>(); - } - - - @Override - public void parse(File file) throws IOException { - description = file.getName(); - - super.parse(file); - } - - - @Override - protected void reset() { - current = null; - grainFraction = null; - unit = null; - } - - - @Override - protected void finish() { - if (current != null) { - for (ImportSedimentYield isy: current) { - sedimentYields.add(isy); - } - } - - description = null; - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - protected void handleMetaLine(String line) { - if (handleMetaUnit(line)) { - return; - } - else if (handleMetaFraction(line)) { - return; - } - else if (handleColumnNames(line)) { - return; - } - else { - log.warn("SYP: Unknown meta line: '" + line + "'"); - } - } - - - protected boolean handleMetaUnit(String line) { - Matcher m = META_UNIT.matcher(line); - - if (m.matches()) { - unit = new ImportUnit(m.group(1)); - return true; - } - - return false; - } - - - public boolean handleMetaFraction(String line) { - Matcher m = META_FRACTION.matcher(line); - - if (m.matches()) { - String tmp = m.group(1); - - this.grainFraction = buildGrainFraction(tmp); - - return true; - } - else if (line.startsWith(FRAKTION_START)) { - String newLine = line.replace(FRAKTION_START, "").trim(); - if (newLine.length() == 0) { - log.debug("Found total grain fraction."); - this.grainFraction = new ImportGrainFraction(GrainFraction.TOTAL); - - return true; - } - } - - return false; - } - - - public boolean handleColumnNames(String line) { - Matcher m = META_COLUMN_NAMES.matcher(line); - - if (m.matches()) { - columnNames = line.split(SEPERATOR_CHAR); - - initializeSedimentYields(); - - return true; - } - - return false; - } - - - protected void handleDataLine(String line) { - String[] vals = line.split(SEPERATOR_CHAR); - - if (vals == null || vals.length < columnNames.length-1) { - log.warn("SYP: skip invalid data line: '" + line + "'"); - return; - } - - try { - Double km = nf.parse(vals[0]).doubleValue(); - - for (int i = 1, n = columnNames.length-1; i < n; i++) { - String curVal = vals[i]; - - if (curVal != null && curVal.length() > 0) { - current[i-1].addValue(new ImportSedimentYieldValue( - km, nf.parse(vals[i]).doubleValue() - )); - } - } - } - catch (ParseException pe) { - log.warn("SYP: unparseable number in data row '" + line + "':", pe); - } - } - - - private void initializeSedimentYields() { - // skip first column (Fluss-km) and last column (Hinweise) - current = new ImportSedimentYield[columnNames.length-2]; - - for (int i = 0, n = columnNames.length; i < n-2; i++) { - current[i] = new ImportSedimentYield(this.description); - current[i].setTimeInterval(getTimeInterval(columnNames[i+1])); - current[i].setUnit(unit); - current[i].setGrainFraction(grainFraction); - } - } - - - private ImportTimeInterval getTimeInterval(String column) { - try { - Matcher a = TIMEINTERVAL_EPOCH.matcher(column); - if (a.matches()) { - int yearA = nf.parse(a.group(1)).intValue(); - int yearB = nf.parse(a.group(2)).intValue(); - - return new ImportTimeInterval( - getDateFromYear(yearA), - getDateFromYear(yearB) - ); - } - - Matcher b = TIMEINTERVAL_SINGLE.matcher(column); - if (b.matches()) { - int year = nf.parse(b.group(1)).intValue(); - - return new ImportTimeInterval(getDateFromYear(year)); - } - - log.warn("SYP: Unknown time interval string: '" + column + "'"); - } - catch (ParseException pe) { - log.warn("SYP: Could not parse years: " + column, pe); - } - - return null; - } - - - private ImportGrainFraction buildGrainFraction(String gfStr) { - Matcher a = META_GRAIN_FRACTION_A.matcher(gfStr); - if (a.matches()) { - String lowerA = a.group(2); - String lowerB = a.group(3); - - String upperA = a.group(4); - String upperB = a.group(5); - - String lower = lowerA != null ? lowerA : lowerB; - String upper = upperA != null ? upperA : upperB; - - try { - return new ImportGrainFraction( - getGrainFractionTypeName(this.description), - nf.parse(lower).doubleValue(), - nf.parse(upper).doubleValue() - ); - } - catch (ParseException pe) { - log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); - } - } - - Matcher b = META_GRAIN_FRACTION_B.matcher(gfStr); - if (b.matches()) { - String lowerA = b.group(4); - String lowerB = b.group(5); - String upperA = b.group(6); - String upperB = b.group(7); - - String lower = lowerA != null ? lowerA : lowerB; - String upper = upperA != null ? upperA : upperB; - - try { - return new ImportGrainFraction( - getGrainFractionTypeName(this.description), - nf.parse(lower).doubleValue(), - nf.parse(upper).doubleValue() - ); - } - catch (ParseException pe) { - log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); - } - } - - Matcher c = META_GRAIN_FRACTION_C.matcher(gfStr); - if (c.matches()) { - String oper = c.group(1); - String valueStr = c.group(3); - - try { - Double value = nf.parse(valueStr).doubleValue(); - - if (oper.equals(">")) { - return new ImportGrainFraction( - getGrainFractionTypeName(this.description), - value, - null - ); - } - else { - return new ImportGrainFraction( - getGrainFractionTypeName(this.description), - null, - value - ); - } - } - catch (ParseException pe) { - log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); - } - } - - log.warn("SYP: Unknown grain fraction: '" + gfStr + "'"); - - return null; - } - - - public static String getGrainFractionTypeName(String filename) { - if (Pattern.matches(FRACTION_COARSE_STR, filename)) { - return GrainFraction.COARSE; - } - else if (Pattern.matches(FRACTION_FINE_MIDDLE_STR, filename)) { - return GrainFraction.FINE_MIDDLE; - } - else if (Pattern.matches(FRACTION_SUSP_SAND_BED, filename) || - Pattern.matches(FRACTION_SUSP_SAND_BED_EPOCH, filename)) { - return GrainFraction.SUSP_SAND_BED; - } - else if (Pattern.matches(FRACTION_SUSP_SAND, filename)) { - return GrainFraction.SUSP_SAND; - } - else if (Pattern.matches(FRACTION_SAND, filename)) { - return GrainFraction.SAND; - } - else if (Pattern.matches(FRACTION_SUSPENDED_SEDIMENT, filename)) { - return GrainFraction.SUSPENDED_SEDIMENT; - } - else if (Pattern.matches(FRACTION_TOTAL, filename)) { - return GrainFraction.TOTAL; - } - else { - log.warn("SYP: Unknown grain fraction '" + filename + "'"); - return "unknown"; - } - } - - - public List<ImportSedimentYield> getSedimentYields() { - return sedimentYields; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/StaFileParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,338 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import java.math.BigDecimal; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.util.Date; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportMainValueType; -import de.intevation.flys.importer.ImportMainValue; -import de.intevation.flys.importer.ImportNamedMainValue; -import de.intevation.flys.importer.ImportGauge; -import de.intevation.flys.importer.ImportTimeInterval; -import de.intevation.flys.utils.DateGuesser; - -public class StaFileParser -{ - private static Logger log = Logger.getLogger(StaFileParser.class); - - public static final String ENCODING = "ISO-8859-1"; - - public static final String TYPES = - System.getProperty("flys.backend.main.value.types", "QWTD"); - - public static final boolean NOT_PARSE_GAUGE_NUMBERS = - Boolean.getBoolean("flys.backend.sta.not.parse.gauge.numbers"); - - public static final Pattern QWTD_ = - Pattern.compile("\\s*([^\\s]+)\\s+([^\\s]+)\\s+([" + - Pattern.quote(TYPES) + "]).*"); - - public static final class NameAndTimeInterval { - private String name; - private ImportTimeInterval timeInterval; - - public NameAndTimeInterval(String name) { - this(name, null); - } - - public NameAndTimeInterval(String name, ImportTimeInterval timeInterval) { - this.name = name; - this.timeInterval = timeInterval; - } - - public String getName() { - return name; - } - - public ImportTimeInterval getTimeInterval() { - return timeInterval; - } - } // class NameAndTimeInterval - - public StaFileParser() { - } - - public boolean parse(ImportGauge gauge) throws IOException { - - File file = gauge.getStaFile(); - - log.info("parsing STA file: " + file); - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String line = in.readLine(); - - if (line == null) { - log.warn("STA file is empty."); - return false; - } - - if (line.length() < 37) { - log.warn("First line in STA file is too short."); - return false; - } - - String gaugeName = line.substring(16, 28).trim(); - - Long gaugeNumber = null; - - if (!NOT_PARSE_GAUGE_NUMBERS) { - String gaugeNumberString = line.substring(8, 16).trim(); - - try { - gaugeNumber = Long.parseLong(gaugeNumberString); - } - catch (NumberFormatException nfe) { - log.warn("STA: '" + gaugeNumberString + - "' is not a valid long number."); - } - } - - gauge.setName(gaugeName); - gauge.setOfficialNumber(gaugeNumber); - - if (log.isDebugEnabled()) { - log.debug( - "name/number: '" + gaugeName + "' '" + gaugeNumber + "'"); - } - - String [] values = line.substring(38).trim().split("\\s+", 2); - - if (values.length < 2) { - log.warn("STA: Not enough columns for aeo and datum."); - } - try { - gauge.setAeo(new BigDecimal(values[0].replace(",", "."))); - gauge.setDatum(new BigDecimal(values[1].replace(",", "."))); - } - catch (NumberFormatException nfe) { - log.warn("STA: cannot parse aeo or datum."); - return false; - } - - line = in.readLine(); - - if (line == null) { - log.warn("STA file has not enough lines"); - return false; - } - - if (line.length() < 36) { - log.warn("STA: second line is too short"); - return false; - } - - try { - gauge.setStation( - new BigDecimal(line.substring(29, 36).trim())); - } - catch (NumberFormatException nfe) { - log.warn("STA: parsing of the datum of the gauge failed"); - return false; - } - - // overread the next six lines - for (int i = 0; i < 6; ++i) { - if ((line = in.readLine()) == null) { - log.warn("STA file is too short"); - return false; - } - } - - HashMap<String, ImportMainValueType> types = - new HashMap<String, ImportMainValueType>(); - - ArrayList<ImportNamedMainValue> namedMainValues = - new ArrayList<ImportNamedMainValue>(); - - ArrayList<ImportMainValue> mainValues = - new ArrayList<ImportMainValue>(); - - while ((line = in.readLine()) != null) { - Matcher m = QWTD_.matcher(line); - if (m.matches()) { - BigDecimal value; - try { - value = new BigDecimal(m.group(2).replace(",", ".")); - } - catch (NumberFormatException nfe) { - log.warn("STA: value not parseable in line " - + in.getLineNumber()); - continue; - } - String typeString = m.group(3); - log.debug("\t type: " + typeString); - ImportMainValueType type = types.get(typeString); - if (type == null) { - type = new ImportMainValueType(typeString); - types.put(typeString, type); - } - String name = m.group(1); - NameAndTimeInterval nat = parseName(name); - ImportNamedMainValue namedMainValue = - new ImportNamedMainValue(type, nat.getName()); - namedMainValues.add(namedMainValue); - - ImportMainValue mainValue = new ImportMainValue( - gauge, - namedMainValue, - value, - nat.getTimeInterval()); - - mainValues.add(mainValue); - } - else { - // TODO: treat as a comment - } - } - gauge.setMainValueTypes( - new ArrayList<ImportMainValueType>(types.values())); - gauge.setNamedMainValues(namedMainValues); - gauge.setMainValues(mainValues); - } - finally { - if (in != null) { - in.close(); - } - } - log.info("finished parsing STA file: " + file); - return true; - } - - protected NameAndTimeInterval parseName(String name) { - List<String> result = new ArrayList<String>(); - - unbracket(name, 0, result); - - int length = result.size(); - - if (length < 1) { // Should not happen. - return new NameAndTimeInterval(name); - } - - if (length == 1) { // No date at all -> use first part. - return new NameAndTimeInterval(result.get(0).trim()); - } - - if (length == 2) { // e.g. W(1994) or W(1994 - 1999) - String type = result.get(0).trim(); - - ImportTimeInterval timeInterval = getTimeInterval( - result.get(1).trim()); - - if (timeInterval == null) { // No date at all. - type = name; - } - - return new NameAndTimeInterval(type, timeInterval); - } - - if (length == 3) { // e.g W(Q(1994)) or W(Q(1994 - 1999)) - - String type = - result.get(0).trim() + "(" + - result.get(1).trim() + ")"; - - ImportTimeInterval timeInterval = getTimeInterval( - result.get(2).trim()); - - if (timeInterval == null) { // No date at all. - type = name; - } - - return new NameAndTimeInterval(type, timeInterval); - } - - // more than 3 elements return unmodified. - - return new NameAndTimeInterval(name); - } - - private static ImportTimeInterval getTimeInterval(String datePart) { - - int minus = datePart.indexOf('-'); - - if (minus < 0) { // '-' not found - - Date date = null; - try { - date = DateGuesser.guessDate(datePart); - } - catch (IllegalArgumentException iae) { - log.warn("STA: Invalid date '" + datePart + "'"); - return null; - } - - return new ImportTimeInterval(date); - } - - // Found '-' so we have <from> - <to> - String startPart = datePart.substring(0, minus).trim(); - String endPart = datePart.substring(minus).trim(); - - Date startDate = null; - Date endDate = null; - - try { - startDate = DateGuesser.guessDate(startPart); - } - catch (IllegalArgumentException iae) { - log.warn("STA: Invalid start date '" + startPart + "'"); - } - - try { - endDate = DateGuesser.guessDate(endPart); - } - catch (IllegalArgumentException iae) { - log.warn("STA: Invalid end date '" + endPart + "'"); - } - - if (startDate == null) { - log.warn("STA: Need start date."); - return null; - } - - return new ImportTimeInterval(startDate, endDate); - } - - private static int unbracket(String s, int index, List<String> result) { - StringBuilder sb = new StringBuilder(); - int length = s.length(); - while (index < length) { - char c = s.charAt(index); - switch (c) { - case '(': - index = unbracket(s, index+1, result); - break; - case ')': - result.add(0, sb.toString()); - return index+1; - default: - sb.append(c); - ++index; - } - } - result.add(0, sb.toString()); - - return index; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/W80CSVParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,291 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.XY; - -import de.intevation.flys.importer.parsers.tim.Coordinate; - -import de.intevation.flys.utils.DateGuesser; -import de.intevation.flys.utils.EpsilonComparator; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.log4j.Logger; - - -/** - * To create cross-sections, generate: Map<double,list<xy>> from files - * in w80/csv format. - */ -public class W80CSVParser extends LineParser implements CrossSectionParser -{ - /** Private logger. */ - private static Logger logger = Logger.getLogger(W80CSVParser.class); - - - /** The current line to which add points. */ - private List<XY> currentLine; - - - /** Data collected so far, last element will be currentLine. */ - protected Map<Double, List<XY>> data; - - - /** Anchor to project to. */ - private static class Anchor extends Coordinate { - - private static final double EPSILON = 1e-5; - - private double station; - - public Anchor(double x, double y, double z, double station) { - super(x, y, z); - this.station = station; - } - - public boolean sameStation(double station) { - return Math.abs(this.station - station) < EPSILON; - } - } - - - /** Reference point for simple projection. */ - private Anchor anchor; - - - /** - * Reference point for distance calculations, introduced to - * deal with bends in the lines. - * Array has two entrys: first is GK-Right, second GK-High. - */ - private double[] lastPointGK; - - - /** Measurement date of anchor as listed in w80 file. */ - private Date anchorDate; - - - private double distanceToLastPoint(double gkr, double gkh) { - double dx = gkr - lastPointGK[0]; - double dy = gkh - lastPointGK[1]; - double d = dx*dx + dy*dy; - - return Math.sqrt(d); - } - - - /** Trivial constructor. */ - public W80CSVParser() { - data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); - } - - - /** - * Get the description of the cross section parsed - - * directory name of current file. - */ - @Override - public String getDescription() { - return getInputFile().getParentFile().getName(); - } - - - /** Get the year of this cross sections measurement. */ - @Override - public Integer getYear() { - if (anchorDate == null) { - return null; - } - Calendar dateCalendar = Calendar.getInstance(); - dateCalendar.setTime(anchorDate); - return dateCalendar.get(Calendar.YEAR); - } - - - /** - * Return the data parsed. - * @return map of stations (km) to list of points. - */ - @Override - public Map<Double, List<XY>> getData() { - return data; - } - - - /** Recursively descend root, ask the callback for every file - * found and parse it if callback acks. When done, notify callback. */ - public void parseW80CSVs(File root, final Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".csv") - && (callback == null || callback.accept(file))) { - reset(); - try { - parse(file); - logger.info("parsing done"); - if (callback != null) { - callback.parsed(W80CSVParser.this); - } - } - catch (IOException ioe) { - logger.error("IOException while parsing file"); - return false; - } - } - return true; - } - }); - } - - - /** Called before consuming first line of file. */ - public void reset() { - data.clear(); - currentLine = new ArrayList<XY>(); - anchor = null; - anchorDate = null; - lastPointGK = new double[] {0d,0d}; - } - - - /** - * Get the Index of the last cross-section lines point. - * @return last points index, -1 if not available. - */ - private int getLastPointIdx() { - if (currentLine == null || currentLine.isEmpty()) { - return -1; - } - XY lastPoint = this.currentLine.get(currentLine.size()-1); - return lastPoint.getIndex(); - } - - - private double getLastPointX() { - if (currentLine == null || currentLine.isEmpty()) { - return 0d; - } - XY lastPoint = this.currentLine.get(currentLine.size()-1); - return lastPoint.getX(); - } - - - /** - * Add a Point (YZ,Index) to the current cross section line. - * @param y The y coordinate of new point. - * @param z The z coordinate of new point. - * @param idx Ignored, the parameter of new point. - * @return true if point could been added, false otherwise (e.g. not - * parsable y or z values. - */ - private boolean addPoint(double gkr, double gkh, double height, String idx) { - // Calculate distance between this and lst point (add distances). - double d = distanceToLastPoint(gkr, gkh); - double totalX = getLastPointX() + d; - - // We ignore idx, and increment instead. - int index; - int lastPointIdx = getLastPointIdx(); - if (lastPointIdx <= 0) { - index = 1; - } else { - index = lastPointIdx + 1; - } - - this.lastPointGK[0] = gkr; - this.lastPointGK[1] = gkh; - currentLine.add(new XY(totalX, height/1000d, index)); - return true; - } - - // As per documentation: - // BW;WPA;ST;UF;PN;LS;BL-LS;Y;X;Z;DL;LZK;SY;SX;SZ;BML;HS;BL-HS;H;DH;HZK;SH;WVA;BMH;BMP;DST;DB;LDS;LKZ; - - - /** - * Called for each line. Try to extract info from a w80 line. - * @param lineNum Number of line (starting with 1). - */ - @Override - protected void handleLine(int lineNum, String line) { - // First two lines are 'comment'-like. - if (lineNum == 1 || lineNum == 2) { - return; - } - // The 'shore' field shows which side of the river the shore is measured. - // Therefore, the points have to be added in the correct order (also - // because later distances are calculated which cannot be - // negative. - String[] fields = line.split(";"); - String station = fields[2]; - String shore = fields[3]; - // TODO: There is 'station' and a 'shore'-code behind. - // 1 = left, 2 = right. none = middle - String pointIndex = line.substring(16,21); - // For GK, first seven digits are of interest. - String gkRight = fields[7]; - String gkHigh = fields[8]; - String date = fields[10]; - String height = fields[18]; - String dateH = line.substring(54,60); - String dateDec = line.substring(64,70); - - double stationKm = Double.parseDouble(station) / 1000d; - double gkRightKm = Double.parseDouble(gkRight.replace(",","."));//.substring(0,7)); - double gkHighKm = Double.parseDouble(gkHigh.replace(",","."));//.substring(0,7)); - double heightM = Double.parseDouble(height.replace(",",".")); - - // New (or first) line. - if (anchor == null || !anchor.sameStation(stationKm)) { - anchor = new Anchor(gkRightKm, gkHighKm, heightM, stationKm); - lastPointGK[0] = gkRightKm; - lastPointGK[1] = gkHighKm; - currentLine = new ArrayList<XY>(); - data.put(stationKm, currentLine); - currentLine.add(new XY(0d, heightM, 0)); - try { - anchorDate = DateGuesser.guessDate(date); - } - catch (IllegalArgumentException iae) { - logger.warn("W80CSV: Invalid date '" + date + "'."); - } - } - else { - addPoint(gkRightKm, gkHighKm, heightM, pointIndex); - } - } - - - /** Called when file is fully consumed. */ - @Override - protected void finish() { - logger.info("Parsed " + data.size() + " lines"); - } - - - /** Parses files given as arguments. */ - public static void main(String [] args) { - - W80CSVParser parser = new W80CSVParser(); - - logger.warn("Start parsing files."); - for (String arg: args) { - logger.warn("Parsing a file."); - parser.parseW80CSVs(new File(arg), null); - } - logger.error("Finished parsing files."); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/W80Parser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,289 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import de.intevation.artifacts.common.utils.FileTools; - -import de.intevation.flys.importer.XY; - -import de.intevation.flys.importer.parsers.tim.Coordinate; - -import de.intevation.flys.utils.DateGuesser; -import de.intevation.flys.utils.EpsilonComparator; - -import java.io.File; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.log4j.Logger; - - -/** - * To create cross-sections, generate: Map<double,list<xy>> from files - * in w80 format. - */ -public class W80Parser extends LineParser implements CrossSectionParser -{ - /** Private logger. */ - private static Logger logger = Logger.getLogger(W80Parser.class); - - - /** The current line to which add points. */ - private List<XY> currentLine; - - - /** Data collected so far, last element will be currentLine. */ - protected Map<Double, List<XY>> data; - - - /** Anchor to project to. */ - private static class Anchor extends Coordinate { - - private static final double EPSILON = 1e-5; - - private double station; - - public Anchor(double x, double y, double z, double station) { - super(x, y, z); - this.station = station; - } - - public boolean sameStation(double station) { - return Math.abs(this.station - station) < EPSILON; - } - } - - - /** Reference point for simple projection. */ - private Anchor anchor; - - - /** - * Reference point for distance calculations, introduced to - * deal with bends in the lines. - * Array has two entrys: first is GK-Right, second GK-High. - */ - private double[] lastPointGK; - - - /** Measurement date of anchor as listed in w80 file. */ - private Date anchorDate; - - - private double distanceToLastPoint(double gkr, double gkh) { - double dx = gkr - lastPointGK[0]; - double dy = gkh - lastPointGK[1]; - double d = dx*dx + dy*dy; - - return Math.sqrt(d); - } - - - /** Trivial constructor. */ - public W80Parser() { - data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); - } - - - /** Get the description of the cross section parsed. */ - @Override - public String getDescription() { - return FileTools.removeExtension(getFileName()); - } - - - /** Get the year of this cross sections measurement. */ - @Override - public Integer getYear() { - if (anchorDate == null) { - return null; - } - Calendar dateCalendar = Calendar.getInstance(); - dateCalendar.setTime(anchorDate); - return dateCalendar.get(Calendar.YEAR); - } - - - /** - * Return the data parsed. - * @return map of stations (km) to list of points. - */ - @Override - public Map<Double, List<XY>> getData() { - return data; - } - - - public void parseW80s(File root, final Callback callback) { - - FileTools.walkTree(root, new FileTools.FileVisitor() { - @Override - public boolean visit(File file) { - if (file.isFile() && file.canRead() - && file.getName().toLowerCase().endsWith(".w80") - && (callback == null || callback.accept(file))) { - reset(); - try { - parse(file); - logger.info("parsing done"); - if (callback != null) { - callback.parsed(W80Parser.this); - } - } - catch (IOException ioe) { - logger.error("IOException while parsing file"); - return false; - } - } - return true; - } - }); - } - - - /** Called before consuming first line of file. */ - public void reset() { - data.clear(); - currentLine = new ArrayList<XY>(); - anchor = null; - anchorDate = null; - lastPointGK = new double[] {0d,0d}; - } - - - /** - * Get the Index of the last cross-section lines point. - * @return last points index, -1 if not available. - */ - private int getLastPointIdx() { - if (currentLine == null || currentLine.isEmpty()) { - return -1; - } - XY lastPoint = this.currentLine.get(currentLine.size()-1); - return lastPoint.getIndex(); - } - - - private double getLastPointX() { - if (currentLine == null || currentLine.isEmpty()) { - return 0d; - } - XY lastPoint = this.currentLine.get(currentLine.size()-1); - return lastPoint.getX(); - } - - - /** - * Add a Point (YZ,Index) to the current cross section line. - * @param y The y coordinate of new point. - * @param z The z coordinate of new point. - * @param idx Ignored, the parameter of new point. - * @return true if point could been added, false otherwise (e.g. not - * parsable y or z values. - */ - private boolean addPoint(double gkr, double gkh, double height, String idx) { - // Calculate distance between this and lst point (add distances). - double d = distanceToLastPoint(gkr, gkh); - double totalX = getLastPointX() + d; - - // We ignore idx, and increment instead. - int index; - int lastPointIdx = getLastPointIdx(); - if (lastPointIdx <= 0) { - index = 1; - } else { - index = lastPointIdx + 1; - } - - this.lastPointGK[0] = gkr; - this.lastPointGK[1] = gkh; - currentLine.add(new XY(totalX, height/1000d, index)); - return true; - } - - - /** - * Called for each line. Try to extract info from a w80 line. - */ - @Override - protected void handleLine(int lineNum, String line) { - // The 'shore' field shows which side of the river the shore is measured. - // Therefore, the points have to be added in the correct order (also - // because later distances are calculated which cannot be - // negative. - String pointId = line.substring(0,20); - String station = line.substring(9,15); - String shore = line.substring(15,16); - // TODO: There is 'station' and a 'shore'-code behind. - // 1 = left, 2 = right. none = middle - String pointIndex = line.substring(16,21); - // For GK, first seven digits are of interest. - String gkRight = line.substring(20,30); - String gkHigh = line.substring(30,40); - String date = line.substring(40,46); - /* Fields not (yet?) of interest for FLYS - String locType = line.substring(46,47); - */ - String height = line.substring(47,54); - String dateH = line.substring(54,60); - /* Fields not (yet?) of interest for FLYS - String typeH = line.substring(60,61); - String kindH = line.substring(61,64); - */ - String dateDec = line.substring(64,70); - /* Fields not (yet?) of interest for FLYS - String note = line.substring(70,78); - String actual = line.substring(78); - */ - - double stationKm = Double.parseDouble(station) / 1000d; - double gkRightKm = Double.parseDouble(gkRight.substring(0,7)); - double gkHighKm = Double.parseDouble(gkHigh.substring(0,7)); - double heightM = Double.parseDouble(height); - - // New (or first) line. - if (anchor == null || !anchor.sameStation(stationKm)) { - anchor = new Anchor(gkRightKm, gkHighKm, heightM, stationKm); - lastPointGK[0] = gkRightKm; - lastPointGK[1] = gkHighKm; - currentLine = new ArrayList<XY>(); - data.put(stationKm, currentLine); - currentLine.add(new XY(0d, heightM, 0)); - try { - anchorDate = DateGuesser.guessDate(date); - } - catch (IllegalArgumentException iae) { - logger.warn("W80: Invalid date '" + date + "'."); - } - } - else { - addPoint(gkRightKm, gkHighKm, heightM, pointIndex); - } - } - - - /** Called when file is fully consumed. */ - @Override - protected void finish() { - logger.info("Parsed " + data.size() + " lines"); - } - - - /** Parses files given as arguments. */ - public static void main(String [] args) { - - W80Parser parser = new W80Parser(); - - logger.warn("Start parsing files."); - for (String arg: args) { - logger.warn("Parsing a file."); - parser.parseW80s(new File(arg), null); - } - logger.error("Finished parsing files."); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/WaterlevelDifferencesParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,197 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportUnit; - -import de.intevation.flys.importer.ImportWst; -import de.intevation.flys.importer.ImportWstColumn; - - -/** - * Parse WaterlevelDifferences CSV file. - */ -public class WaterlevelDifferencesParser extends LineParser { - - private static final Logger log = - Logger.getLogger(WaterlevelDifferencesParser.class); - - private static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - public static final Pattern META_UNIT = - Pattern.compile("^Einheit: \\[(.*)\\].*"); - - /** List of parsed differences as ImportWst s. */ - private List<ImportWst> differences; - - private ImportWstColumn[] columns; - - /** The currently processed dataset. */ - private ImportWst current; - - - public WaterlevelDifferencesParser() { - differences = new ArrayList<ImportWst>(); - } - - - /** Get the differences as wst parsed so far. */ - public List<ImportWst> getDifferences() { - return differences; - } - - - /** - * Parse a csv waterleveldifferenceparser and create a ImportWst object - * from it. - */ - @Override - public void parse(File file) throws IOException { - current = new ImportWst(file.getName()); - current.setKind(7); - - super.parse(file); - } - - - /** No rewind implemented. */ - @Override - protected void reset() { - } - - - @Override - protected void finish() { - if (columns != null && current != null) { - // TODO figure out if its needed, as the columns - // are registered at their construction time. - for (ImportWstColumn col: columns) { - // TODO place a current.addColumn(col); here? - } - - differences.add(current); - } - - current = null; - columns = null; - } - - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - } - else { - handleDataLine(line); - } - } - - - private void handleMetaLine(String meta) { - if (handleMetaUnit(meta)) { - return; - } - else { - handleMetaColumnNames(meta); - } - } - - - private boolean handleMetaUnit(String meta) { - Matcher m = META_UNIT.matcher(meta); - - if (m.matches()) { - String unit = m.group(1); - log.debug("Found unit: '" + unit + "'"); - - current.setUnit(new ImportUnit(unit)); - - return true; - } - - return false; - } - - - private boolean handleMetaColumnNames(String meta) { - Pattern META_COLUMN_NAMES = Pattern.compile("Fluss-km;(.*)"); - Matcher m = META_COLUMN_NAMES.matcher(meta); - - if (m.matches()) { - String colStr = m.group(1); - String[] cols = colStr.split(SEPERATOR_CHAR); - - log.debug("Found " + cols.length + " columns."); - - initColumns(cols); - - return true; - } - - return false; - } - - - private void initColumns(String[] cols) { - current.setNumberColumns(cols.length); - columns = current.getColumns().toArray(new ImportWstColumn[cols.length]); - - for (int i = 0; i < cols.length; i++) { - String name = cols[i].replace("\"", ""); - - log.debug("Create new column '" + name + "'"); - current.getColumn(i).setName(name); - current.getColumn(i).setDescription(name); - } - } - - - private void handleDataLine(String line) { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols == null || cols.length < 2) { - log.warn("skip invalid waterlevel-diff line: '" + line + "'"); - return; - } - - try { - Double station = nf.parse(cols[0]).doubleValue(); - - for (int i = 0; i < columns.length; i++) { - int idx = i+1; - - if (idx >= cols.length) { - log.warn("Insufficient column numbers: " + line); - continue; - } - - String value = cols[idx]; - - try { - columns[i].addColumnValue( - new BigDecimal(station), - new BigDecimal(nf.parse(value).doubleValue())); - } - catch (ParseException pe) { - log.warn("Could not parse value: '" + value + "'"); - } - } - } - catch (ParseException pe) { - log.warn("Could not parse station: '" + line + "'"); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/WaterlevelParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,191 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import de.intevation.flys.importer.ImportUnit; - -import de.intevation.flys.importer.ImportRange; -import de.intevation.flys.importer.ImportWst; -import de.intevation.flys.importer.ImportWstColumn; -import de.intevation.flys.importer.ImportWstColumnValue; -import de.intevation.flys.importer.ImportWstQRange; - - -/** - * Parse CSV Waterlevel files. - * As these waterlevels are probably used in fixation analysis - * only, functionality to export them to "fixation"-wsts - * has been added (the ImportWaterlevel*- stuff is actually - * not needed to do so.) - */ -public class WaterlevelParser extends LineParser { - - private static final Logger log = Logger.getLogger(WaterlevelParser.class); - - private static final NumberFormat nf = - NumberFormat.getInstance(DEFAULT_LOCALE); - - private static final Pattern META_Q_RANGE = - Pattern.compile("Abfluss\\s\\[(.*)\\];(.*)"); - - public static final Pattern META_UNIT = - Pattern.compile("^Einheit: \\[(.*)\\].*"); - - private List<ImportWst> waterlevels; - - private ImportWst current; - - /** The Waterlevel-Wst s will always have but one column. */ - private ImportWstColumn column; - - /** The current (incomplete) Q Range. */ - private ImportWstQRange currentQRange; - - /** The current (incomplete) km range for Q Range. */ - private ImportRange currentRange; - - private String currentDescription; - - - public WaterlevelParser() { - waterlevels = new ArrayList<ImportWst>(); - } - - - public List<ImportWst> getWaterlevels() { - return waterlevels; - } - - - @Override - public void parse(File file) throws IOException { - currentDescription = file.getName(); - - super.parse(file); - } - - - @Override - protected void reset() { - currentQRange = null; - current = new ImportWst(currentDescription); - current.setNumberColumns(1); - column = current.getColumn(0); - column.setName(currentDescription); - column.setDescription(currentDescription); - current.setKind(6); - } - - - @Override - protected void finish() { - if (current != null) { - if (currentQRange != null) { - List<ImportWstColumnValue> cValues = column.getColumnValues(); - // Set end of range to last station. - currentRange.setB(cValues.get(cValues.size() -1).getPosition()); - currentQRange.setRange(currentRange); - column.addColumnQRange(currentQRange); - } - - waterlevels.add(current); - } - } - - @Override - protected void handleLine(int lineNum, String line) { - if (line.startsWith(START_META_CHAR)) { - handleMetaLine(stripMetaLine(line)); - return; - } - else if (handleQRange(line)) { - return; - } - else { - handleDataLine(line); - return; - } - } - - - private void handleMetaLine(String meta) { - Matcher m = META_UNIT.matcher(meta); - - if (m.matches()) { - String unit = m.group(1); - log.debug("Found unit: '" + unit + "'"); - - current.setUnit(new ImportUnit(unit)); - } - } - - - private boolean handleQRange(String line) { - Matcher m = META_Q_RANGE.matcher(line); - - if (m.matches()) { - String unitStr = m.group(1); - String valueStr = m.group(2); - try { - if (currentQRange != null) { - // Finish off the last one. - List<ImportWstColumnValue> cValues = column.getColumnValues(); - // Set end of range to last station. - currentRange.setB(cValues.get(cValues.size() -1).getPosition()); - currentQRange.setRange(currentRange); - column.addColumnQRange(currentQRange); - } - currentQRange = new ImportWstQRange(null, - new BigDecimal(nf.parse(valueStr).doubleValue())); - currentRange = new ImportRange(); - - log.debug("Found new Q range: Q=" + valueStr); - - return true; - } - catch (ParseException pe) { - log.warn("Unparseable Q range: '" + line + "'"); - } - } - - return false; - } - - - private void handleDataLine(String line) { - String[] cols = line.split(SEPERATOR_CHAR); - - if (cols == null || cols.length < 2) { - log.warn("skip invalid waterlevel line: '" + line + "'"); - return; - } - - try { - // Store the value and remember the position for QRange, if needed. - Double station = nf.parse(cols[0]).doubleValue(); - Double value = nf.parse(cols[1]).doubleValue(); - - BigDecimal stationBD = new BigDecimal(station); - - column.addColumnValue(stationBD, new BigDecimal(value)); - - if (currentRange.getA() == null) { - currentRange.setA(stationBD); - } - } - catch (ParseException pe) { - log.warn("Unparseable number in data row: " + line); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/WstParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,464 +0,0 @@ -package de.intevation.flys.importer.parsers; - -import java.util.ArrayList; -import java.util.HashSet; - -import java.io.File; -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.InputStreamReader; -import java.io.FileInputStream; - -import java.text.NumberFormat; - -import org.apache.log4j.Logger; - -import de.intevation.flys.utils.StringUtil; -import de.intevation.flys.utils.DateGuesser; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.math.BigDecimal; - -import de.intevation.flys.importer.ImportWstQRange; -import de.intevation.flys.importer.ImportWstColumn; -import de.intevation.flys.importer.ImportTimeInterval; -import de.intevation.flys.importer.ImportRange; -import de.intevation.flys.importer.ImportUnit; -import de.intevation.flys.importer.ImportWst; - -public class WstParser -{ - private static Logger log = Logger.getLogger(WstParser.class); - - public static final String COLUMN_BEZ_TEXT = "column-bez-text"; - public static final String COLUMN_BEZ_BREITE = "column-bez-breite"; - public static final String COLUMN_QUELLE = "column-quelle"; - public static final String COLUMN_DATUM = "column-datum"; - - public static final BigDecimal UNDEFINED_ZERO = - new BigDecimal(0.0); - public static final BigDecimal MIN_RANGE = - new BigDecimal(-Double.MAX_VALUE); - public static final BigDecimal MAX_RANGE = - new BigDecimal(Double.MAX_VALUE); - - public static final String ENCODING = "ISO-8859-1"; - - public static final Pattern UNIT_COMMENT = - Pattern.compile("\\*\\s*[kK][mM]\\s+(.+)"); - - public static final Pattern UNIT = - Pattern.compile("[^\\[]*\\[([^]]+)\\].*"); - - public static final double INTERVAL_GAP = 0.00001d; - - protected ImportWst wst; - - protected ImportRange lastRange; - - public WstParser() { - } - - public ImportWst getWst() { - return wst; - } - - public void setWst(ImportWst wst) { - this.wst = wst; - } - - public ImportTimeInterval guessDate(String string) { - try { - return new ImportTimeInterval( - DateGuesser.guessDate(string)); - } - catch (IllegalArgumentException iae) { - } - return null; - } - - public void parse(File file) throws IOException { - - log.info("Parsing WST file '" + file + "'"); - - wst = new ImportWst(file.getName()); - - LineNumberReader in = null; - try { - in = - new LineNumberReader( - new InputStreamReader( - new FileInputStream(file), ENCODING)); - - String input; - boolean first = true; - int columnCount = 0; - - String [] lsBezeichner = null; - String [] langBezeichner = null; - int [] colNaWidths = null; - String [] quellen = null; - String [] daten = null; - - BigDecimal [] aktAbfluesse = null; - BigDecimal [] firstAbfluesse = null; - - BigDecimal minKm = MAX_RANGE; - BigDecimal maxKm = MIN_RANGE; - BigDecimal kmHist1 = null; - BigDecimal kmHist2 = null; - - boolean columnHeaderChecked = false; - - String einheit = "Wasserstand [NN + m]"; - - HashSet<BigDecimal> kms = new HashSet<BigDecimal>(); - - while ((input = in.readLine()) != null) { - String line = input; - if (first) { // fetch number of columns - if ((line = line.trim()).length() == 0) { - continue; - } - try { - columnCount = Integer.parseInt(line); - if (columnCount <= 0) { - throw new NumberFormatException( - "number columns <= 0"); - } - log.debug("Number of columns: " + columnCount); - wst.setNumberColumns(columnCount); - lsBezeichner = new String[columnCount]; - } - catch (NumberFormatException nfe) { - log.warn("WST: invalid number.", nfe); - continue; - } - first = false; - continue; - } - - line = line.replace(',', '.'); - - if (line.startsWith("*\u001f")) { - BigDecimal [] data = - parseLineAsDouble(line, columnCount, false, true); - - if (aktAbfluesse != null) { - if (kmHist1 != null && kmHist2 != null - && kmHist1.compareTo(kmHist2) < 0) { - BigDecimal t = minKm; minKm = maxKm; maxKm = t; - } - addInterval(minKm, maxKm, aktAbfluesse); - minKm = MAX_RANGE; - maxKm = MIN_RANGE; - } - - aktAbfluesse = new BigDecimal[columnCount]; - log.debug("new q range: " + columnCount); - for (int i = 0; i < Math.min(columnCount, data.length); ++i) { - if (data[i] != null) { - log.debug(" column: " + data[i]); - aktAbfluesse[i] = data[i]; - } - } - - if (firstAbfluesse == null) { - firstAbfluesse = (BigDecimal [])aktAbfluesse.clone(); - } - continue; - } - - if (line.startsWith("*!")) { - String spezial = line.substring(2).trim(); - - if (spezial.length() == 0) { - continue; - } - - if (spezial.startsWith(COLUMN_BEZ_TEXT)) { - spezial = spezial.substring(COLUMN_BEZ_TEXT.length()).trim(); - if (spezial.length() == 0) { - continue; - } - langBezeichner = StringUtil.splitQuoted(spezial, '"'); - } - else if (spezial.startsWith(COLUMN_BEZ_BREITE)) { - spezial = spezial.substring(COLUMN_BEZ_BREITE.length()).trim(); - - if (spezial.length() == 0) { - continue; - } - - String[] split = spezial.split("\\s+"); - - colNaWidths = new int[split.length]; - for (int i=0; i < split.length; i++) { - colNaWidths[i] = Integer.parseInt(split[i]); - } - } - else if (spezial.startsWith(COLUMN_QUELLE)) { - if (spezial.length() == 0) { - continue; - } - quellen = StringUtil.splitQuoted(spezial, '"'); - } - else if (spezial.startsWith(COLUMN_DATUM)) { - spezial = spezial.substring(COLUMN_DATUM.length()).trim(); - if (spezial.length() == 0) { - continue; - } - daten = StringUtil.splitQuoted(spezial, '"'); - } - continue; - } - - if (line.length() < 11) { - continue; - } - - if (line.startsWith("*")) { - Matcher m = UNIT_COMMENT.matcher(line); - if (m.matches()) { - log.debug("unit comment found"); - // XXX: This hack is needed because desktop - // FLYS is broken figuring out the unit - String [] units = m.group(1).split("\\s{2,}"); - m = UNIT.matcher(units[0]); - einheit = m.matches() ? m.group(1) : units[0]; - log.debug("unit: " + einheit); - } - continue; - } - - if (firstAbfluesse != null) { - if (!columnHeaderChecked) { - int unknownCount = 0; - HashSet<String> uniqueColumnNames = - new HashSet<String>(); - for (int i = 0; i < lsBezeichner.length; ++i) { - if (lsBezeichner[i] == null - || lsBezeichner[i].length() == 0) { - double q = firstAbfluesse[i].doubleValue(); - if (q < 0.001) { - lsBezeichner[i] = - "<unbekannt #" + unknownCount + ">"; - ++unknownCount; - } - else { - lsBezeichner[i] = "Q="+format(q); - } - } - String candidate = lsBezeichner[i]; - int collision = 1; - while (!uniqueColumnNames.add(candidate)) { - candidate = lsBezeichner[i] + - " (" + collision + ")"; - ++collision; - } - ImportWstColumn iwc = wst.getColumn(i); - iwc.setName(candidate); - String potentialDate = daten != null && i < daten.length - ? daten[i] - : candidate; - iwc.setTimeInterval(guessDate(potentialDate)); - } - columnHeaderChecked = true; - } - - BigDecimal [] data = - parseLineAsDouble(line, columnCount, true, false); - - BigDecimal kaem = data[0]; - - if (!kms.add(kaem)) { - log.warn( - "WST: km " + kaem + - " (line " + in.getLineNumber() + - ") found more than once. -> ignored"); - continue; - } - - kmHist2 = kmHist1; - kmHist1 = kaem; - - if (kaem.compareTo(minKm) < 0) { - minKm = kaem; - } - if (kaem.compareTo(maxKm) > 0) { - maxKm = kaem; - } - - // extract values - for (int i = 0; i < columnCount; ++i) { - addValue(kaem, data[i+1], i); - } - - } - else { // firstAbfluesse == null - if (langBezeichner != null) { - lsBezeichner = StringUtil.fitArray( - langBezeichner, lsBezeichner); - } - else if (colNaWidths != null) { - for (int j = 0, i = 0, N = input.length(); - j < colNaWidths.length && i < N; - i += colNaWidths[j++] - ) { - lsBezeichner[j] = input.substring( - i, i+colNaWidths[j]).trim(); - } - } - else { - // first column begins at position 8 in line - for (int i = 8, col = 0; i < input.length(); i += 9) { - if ((i + 9) > input.length()) { - i = input.length() - 10; - } - // one column header is 9 chars wide - lsBezeichner[col++] = - input.substring(i, i + 9).trim(); - - if (col == lsBezeichner.length) { - break; - } - } - } - } - - } // for all lines in WST file - - wst.setUnit(new ImportUnit(einheit)); - - if (kmHist1 != null && kmHist2 != null - && kmHist1.compareTo(kmHist2) < 0) { - BigDecimal t = minKm; minKm = maxKm; maxKm = t; - } - addInterval(minKm, maxKm, aktAbfluesse); - - fixRangesOrder(); - } - finally { - if (in != null) { - in.close(); - } - } - } - - protected void fixRangesOrder() { - wst.fixRangesOrder(); - } - - protected void addValue(BigDecimal km, BigDecimal w, int index) { - if (w != null) { - ImportWstColumn column = wst.getColumn(index); - column.addColumnValue(km, w); - } - } - - private static final NumberFormat NF = getNumberFormat(); - - private static final NumberFormat getNumberFormat() { - NumberFormat nf = NumberFormat.getInstance(); - nf.setMinimumFractionDigits(2); - nf.setMaximumFractionDigits(2); - return nf; - } - - protected static String format(double value) { - return NF.format(value); - } - - protected void addInterval( - BigDecimal from, - BigDecimal to, - BigDecimal [] values - ) { - log.debug("addInterval: " + from + " " + to); - - if (values == null || from == MAX_RANGE || from == MIN_RANGE) { - return; - } - - ImportRange range = new ImportRange(from, to); - - // little workaround to make the q ranges tightly fit. - // Leave a very small gap to ensure that the range queries - // still work. - - if (lastRange != null) { - double a1 = lastRange.getA().doubleValue(); - double b1 = lastRange.getB().doubleValue(); - double a2 = range.getA().doubleValue(); - - if (a1 < b1) { - lastRange.setB(new BigDecimal(a2 - INTERVAL_GAP)); - } - else { // a1 >= b1 - lastRange.setB(new BigDecimal(a2 + INTERVAL_GAP)); - } - } - - for (int i = 0; i < values.length; ++i) { - ImportWstColumn column = wst.getColumn(i); - ImportWstQRange wstQRange = new ImportWstQRange(range, values[i]); - column.addColumnQRange(wstQRange); - } - - lastRange = range; - } - - private static final BigDecimal [] parseLineAsDouble( - String line, - int count, - boolean bStation, - boolean bParseEmptyAsZero - ) { - String [] tokens = parseLine(line, count, bStation); - - BigDecimal [] doubles = new BigDecimal[tokens.length]; - - for (int i = 0; i < doubles.length; ++i) { - String token = tokens[i].trim(); - if (token.length() != 0) { - doubles[i] = new BigDecimal(token); - } - else if (bParseEmptyAsZero) { - doubles[i] = UNDEFINED_ZERO; - } - } - - return doubles; - } - - private static String [] parseLine( - String line, - int tokenCount, - boolean bParseStation - ) { - ArrayList<String> strings = new ArrayList<String>(); - - if (bParseStation) { - if (line.length() < 8) { - throw new IllegalArgumentException("station too short"); - } - strings.add(line.substring(0, 8)); - } - - int pos = 9; - for (int i = 0; i < tokenCount; ++i) { - if (line.length() >= pos + 8) { - strings.add(line.substring(pos, pos + 8)); - } - else { - strings.add(""); - } - pos += 9; - } - - return strings.toArray(new String[strings.size()]); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/tim/Coordinate.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.importer.parsers.tim; - -/** X,Y,Z- triple. */ -public class Coordinate -{ - public double x; - public double y; - public double z; - - public Coordinate() { - } - - public Coordinate(Coordinate c) { - this(c.x, c.y, c.z); - } - - public Coordinate(double x, double y) { - this(x, y, 0d); - } - - public Coordinate(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - public double getX() { - return this.x; - } - - public double getY() { - return this.y; - } - - public final double distanceSqr(double ox, double oy) { - double dx = x - ox; - double dy = y - oy; - return dx*dx + dy*dy; - } - - public final double distance(double xo, double yo) { - return Math.sqrt(distanceSqr(xo, yo)); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/tim/LexiComparator.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,18 +0,0 @@ -package de.intevation.flys.importer.parsers.tim; - -import java.util.Comparator; - -public class LexiComparator implements Comparator<Coordinate> { - - public static final LexiComparator CMP = new LexiComparator(); - - @Override - public int compare(Coordinate a, Coordinate b) { - if (a.x < b.x) return -1; - if (a.x > b.x) return +1; - if (a.y < b.y) return -1; - if (a.y > b.y) return +1; - return 0; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/tim/Line.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,34 +0,0 @@ -package de.intevation.flys.importer.parsers.tim; - -/** Two coordinates and a helper. */ -public class Line { - - public Coordinate a; - public Coordinate b; - - public Line() { - } - - public Line(Coordinate a, Coordinate b) { - this.a = a; - this.b = b; - } - - /** Project coordinate to line. */ - public double distanceToFirst(Coordinate c) { - - double nx = b.x - a.x; - double ny = b.y - a.y; - - double len = Math.sqrt(nx*nx + ny*ny); - - nx /= len; - ny /= len; - - double px = c.x - a.x; - double py = c.y - a.y; - - return nx*px + ny*py; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/importer/parsers/tim/TIMParser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -package de.intevation.flys.importer.parsers.tim; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.log4j.Logger; - -import de.intevation.flys.utils.EpsilonComparator; - -/** Parser for single .tim files. */ -public class TIMParser -{ - /** Private logger. */ - private static Logger logger = Logger.getLogger(TIMParser.class); - - /** Proper encoding. */ - public static final String ENCODING = - System.getProperty("tim.encoding", "ISO-8859-1"); - - /** Map of stations (km) to points (xyz). */ - protected Map<Double, List<Coordinate>> lines; - - public TIMParser() { - lines = new TreeMap<Double, List<Coordinate>>(EpsilonComparator.CMP); - } - - /** Access map of stations (km) to coordinates (xyz). */ - public Map<Double, List<Coordinate>> getLines() { - return lines; - } - - /** Get number of lines (data). */ - public int numLines() { - return lines.size(); - } - - /** Parse single .tim file. */ - public void load(String filename) throws IOException { - BufferedReader reader = - new BufferedReader( - new InputStreamReader( - new FileInputStream(filename), ENCODING)); - try { - String row; - while ((row = reader.readLine()) != null) { - if (row.length() < 54) { - logger.warn("row too short"); - continue; - } - double station, x, y, z; - try { - station = Double.parseDouble(row.substring( 9, 16))/1000d; - x = Double.parseDouble(row.substring(20, 30))/1000d; - y = Double.parseDouble(row.substring(30, 40))/1000d; - z = Double.parseDouble(row.substring(47, 54))/10000d; - } catch (NumberFormatException nfe) { - logger.warn("Invalid row"); - continue; - } - - Double km = station; - - List<Coordinate> line = lines.get(km); - if (line == null) { - line = new ArrayList<Coordinate>(); - lines.put(km, line); - } - - line.add(new Coordinate(x, y, z)); - } - // Bring coords in lexicographical order. - sortCoordinates(); - } finally { - reader.close(); - } - } - - /** Sort coordinates of lines lexicographically. */ - protected void sortCoordinates() { - for (List<Coordinate> line: lines.values()) { - Collections.sort(line, LexiComparator.CMP); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Annotation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,111 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "annotations") -public class Annotation -implements Serializable -{ - private Integer id; - private Range range; - private Attribute attribute; - private Position position; - private Edge edge; - private AnnotationType type; - - public Annotation() { - } - - public Annotation( - Range range, - Attribute attribute, - Position position, - Edge edge, - AnnotationType type - ) { - this.range = range; - this.attribute = attribute; - this.position = position; - this.edge = edge; - this.type = type; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_ANNOTATIONS_ID_SEQ", - sequenceName = "ANNOTATIONS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_ANNOTATIONS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "range_id") - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @OneToOne - @JoinColumn(name = "attribute_id") - public Attribute getAttribute() { - return attribute; - } - - public void setAttribute(Attribute attribute) { - this.attribute = attribute; - } - - @OneToOne - @JoinColumn(name = "position_id") - public Position getPosition() { - return position; - } - - public void setPosition(Position position) { - this.position = position; - } - - @OneToOne - @JoinColumn(name = "edge_id") - public Edge getEdge() { - return edge; - } - - public void setEdge(Edge edge) { - this.edge = edge; - } - - @OneToOne - @JoinColumn(name = "type_id") - public AnnotationType getType() { - return type; - } - - public void setType(AnnotationType type) { - this.type = type; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/AnnotationType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "annotation_types") -public class AnnotationType -implements Serializable -{ - private Integer id; - private String name; - - public AnnotationType() { - } - - public AnnotationType(String name) { - this.name = name; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_ANNOTATION_TYPES_ID_SEQ", - sequenceName = "ANNOTATION_TYPES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_ANNOTATION_TYPES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Attribute.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,55 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "attributes") -public class Attribute -implements Serializable -{ - private Integer id; - - private String value; - - public Attribute() { - } - - public Attribute(String value) { - this.value = value; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_ATTRIBUTES_ID_SEQ", - sequenceName = "ATTRIBUTES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_ATTRIBUTES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "value") - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/AxisKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "axis_kinds") -public class AxisKind implements Serializable { - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return The display Name of the kind as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/BedHeightEpoch.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,211 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "bed_height_epoch") -public class BedHeightEpoch implements Serializable { - - private Integer id; - - private River river; - - private TimeInterval timeInterval; - - private ElevationModel curElevationModel; - private ElevationModel oldElevationModel; - - private Range range; - - private String evaluationBy; - private String description; - - private List<BedHeightEpochValue> values; - - - public BedHeightEpoch() { - } - - - public BedHeightEpoch( - River river, - TimeInterval timeInterval, - Range range, - ElevationModel curElevationModel, - ElevationModel oldElevationModel, - String evaluationBy, - String description - ) { - this.river = river; - this.timeInterval = timeInterval; - this.range = range; - this.curElevationModel = curElevationModel; - this.oldElevationModel = oldElevationModel; - this.evaluationBy = evaluationBy; - this.description = description; - this.values = new ArrayList<BedHeightEpochValue>(); - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_BED_HEIGHT_EPOCH_ID_SEQ", - sequenceName = "BED_HEIGHT_EPOCH_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_BED_HEIGHT_EPOCH_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - @OneToOne - @JoinColumn(name = "cur_elevation_model_id") - public ElevationModel getCurElevationModel() { - return curElevationModel; - } - - public void setCurElevationModel(ElevationModel curElevationModel) { - this.curElevationModel = curElevationModel; - } - - @OneToOne - @JoinColumn(name = "old_elevation_model_id") - public ElevationModel getOldElevationModel() { - return oldElevationModel; - } - - public void setOldElevationModel(ElevationModel oldElevationModel) { - this.oldElevationModel = oldElevationModel; - } - - @OneToOne - @JoinColumn(name = "range_id") - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @Column(name = "evaluation_by") - public String getEvaluationBy() { - return evaluationBy; - } - - public void setEvaluationBy(String evaluationBy) { - this.evaluationBy = evaluationBy; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @JoinColumn(name = "bed_height_epoch_id") - public List<BedHeightEpochValue> getValues() { - return values; - } - - public void setValues(List<BedHeightEpochValue> values) { - this.values = values; - } - - - public static List<BedHeightEpoch> getBedHeightEpochs( - River river, - double kmLo, - double kmHi - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightEpoch where river=:river"); - - query.setParameter("river", river); - - // TODO Do km range filtering in SQL statement - - List<BedHeightEpoch> epochs = query.list(); - List<BedHeightEpoch> good = new ArrayList<BedHeightEpoch>(); - - OUTER: for (BedHeightEpoch e: epochs) { - for (BedHeightEpochValue value: e.getValues()) { - double station = value.getStation().doubleValue(); - - if (station >= kmLo && station <= kmHi) { - good.add(e); - continue OUTER; - } - } - } - - return good; - } - - - public static BedHeightEpoch getBedHeightEpochById(int id) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightEpoch where id=:id"); - - query.setParameter("id", id); - - List<BedHeightEpoch> singles = query.list(); - - return singles != null ? singles.get(0) : null; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/BedHeightEpochValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,119 +0,0 @@ -package de.intevation.flys.model; - -import java.util.List; - -import java.io.Serializable; -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "bed_height_epoch_values") -public class BedHeightEpochValue -implements Serializable -{ - private static Logger logger = - Logger.getLogger(BedHeightEpochValue.class); - - private Integer id; - - private BedHeightEpoch bedHeight; - - private BigDecimal station; - private BigDecimal height; - - - public BedHeightEpochValue() { - } - - public BedHeightEpochValue( - BedHeightEpoch bedHeight, - BigDecimal station, - BigDecimal height - ) { - this.bedHeight = bedHeight; - this.station = station; - this.height = height; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_BED_EPOCH_VALUE_ID_SEQ", - sequenceName = "BED_EPOCH_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_BED_EPOCH_VALUE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "bed_height_epoch_id" ) - public BedHeightEpoch getBedHeight() { - return bedHeight; - } - - public void setBedHeight(BedHeightEpoch bedHeight) { - this.bedHeight = bedHeight; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "height") - public BigDecimal getHeight() { - return height; - } - - public void setHeight(BigDecimal height) { - this.height = height; - } - - - public static List<BedHeightEpochValue> getBedHeightEpochValues( - BedHeightEpoch epoch, - double kmLo, - double kmHi - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightEpochValue where bedHeight=:epoch " + - " and station >= :kmLo and station <= :kmHi"); - - query.setParameter("epoch", epoch); - query.setParameter("kmLo", new BigDecimal(kmLo)); - query.setParameter("kmHi", new BigDecimal(kmHi)); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/BedHeightSingle.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,272 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "bed_height_single") -public class BedHeightSingle implements Serializable { - - private Integer id; - private Integer year; - private Integer soundingWidth; - - private String evaluationBy; - private String description; - - private River river; - - private BedHeightType type; - - private LocationSystem locationSystem; - - private ElevationModel curElevationModel; - - private ElevationModel oldElevationModel; - - private Range range; - - private List<BedHeightSingleValue> values; - - - public BedHeightSingle() { - } - - - public BedHeightSingle( - River river, - Integer year, - Integer soundingWidth, - BedHeightType type, - LocationSystem locationSystem, - ElevationModel curElevationModel, - Range range - ) { - this( - river, - year, - soundingWidth, - type, - locationSystem, - curElevationModel, - null, - range, - null, - null); - } - - - public BedHeightSingle( - River river, - Integer year, - Integer soundingWidth, - BedHeightType type, - LocationSystem locationSystem, - ElevationModel curElevationModel, - ElevationModel oldElevationModel, - Range range, - String evaluationBy, - String description - ) { - this.river = river; - this.year = year; - this.soundingWidth = soundingWidth; - this.type = type; - this.locationSystem = locationSystem; - this.curElevationModel = curElevationModel; - this.oldElevationModel = oldElevationModel; - this.range = range; - this.evaluationBy = evaluationBy; - this.description = description; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_BED_HEIGHT_SINGLE_ID_SEQ", - sequenceName = "BED_HEIGHT_SINGLE_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_BED_HEIGHT_SINGLE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "year") - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - @Column(name = "sounding_width") - public Integer getSoundingWidth() { - return soundingWidth; - } - - public void setSoundingWidth(Integer soundingWidth) { - this.soundingWidth = soundingWidth; - } - - @OneToOne - @JoinColumn(name = "type_id") - public BedHeightType getType() { - return type; - } - - public void setType(BedHeightType type) { - this.type = type; - } - - @OneToOne - @JoinColumn(name = "location_system_id") - public LocationSystem getLocationSystem() { - return locationSystem; - } - - public void setLocationSystem(LocationSystem locationSystem) { - this.locationSystem = locationSystem; - } - - @OneToOne - @JoinColumn(name = "cur_elevation_model_id") - public ElevationModel getCurElevationModel() { - return curElevationModel; - } - - public void setCurElevationModel(ElevationModel curElevationModel) { - this.curElevationModel = curElevationModel; - } - - @OneToOne - @JoinColumn(name = "old_elevation_model_id") - public ElevationModel getOldElevationModel() { - return oldElevationModel; - } - - public void setOldElevationModel(ElevationModel oldElevationModel) { - this.oldElevationModel = oldElevationModel; - } - - @OneToOne - @JoinColumn(name = "range_id") - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @Column(name = "evaluation_by") - public String getEvaluationBy() { - return evaluationBy; - } - - public void setEvaluationBy(String evaluationBy) { - this.evaluationBy = evaluationBy; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @JoinColumn(name = "bed_height_single_id") - public List<BedHeightSingleValue> getValues() { - return values; - } - - public void setValues(List<BedHeightSingleValue> values) { - this.values = values; - } - - - public static List<BedHeightSingle> getBedHeightSingles( - River river, - double kmLo, - double kmHi - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightSingle where river=:river"); - - query.setParameter("river", river); - - // TODO Do km range filtering in SQL statement - - List<BedHeightSingle> singles = query.list(); - List<BedHeightSingle> good = new ArrayList<BedHeightSingle>(); - - for (BedHeightSingle s: singles) { - for (BedHeightSingleValue value: s.getValues()) { - double station = value.getStation().doubleValue(); - - if (station >= kmLo && station <= kmHi) { - good.add(s); - break; - } - } - } - - return good; - } - - - public static BedHeightSingle getBedHeightSingleById(int id) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightSingle where id=:id"); - - query.setParameter("id", id); - - List<BedHeightSingle> singles = query.list(); - - return singles != null ? singles.get(0) : null; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/BedHeightSingleValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,167 +0,0 @@ -package de.intevation.flys.model; - -import java.util.List; - -import java.io.Serializable; -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "bed_height_single_values") -public class BedHeightSingleValue -implements Serializable -{ - private static Logger logger = - Logger.getLogger(BedHeightSingleValue.class); - - private Integer id; - - private BedHeightSingle bedHeight; - - private BigDecimal station; - private BigDecimal height; - private BigDecimal uncertainty; - private BigDecimal dataGap; - private BigDecimal soundingWidth; - private BigDecimal width; - - - public BedHeightSingleValue() { - } - - public BedHeightSingleValue( - BedHeightSingle bedHeight, - BigDecimal station, - BigDecimal height, - BigDecimal uncertainty, - BigDecimal dataGap, - BigDecimal soundingWidth, - BigDecimal width - ) { - this.bedHeight = bedHeight; - this.station = station; - this.height = height; - this.uncertainty = uncertainty; - this.dataGap = dataGap; - this.soundingWidth = soundingWidth; - this.width = width; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_BED_SINGLE_VALUE_ID_SEQ", - sequenceName = "BED_SINGLE_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_BED_SINGLE_VALUE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "bed_height_single_id" ) - public BedHeightSingle getBedHeight() { - return bedHeight; - } - - public void setBedHeight(BedHeightSingle bedHeight) { - this.bedHeight = bedHeight; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "height") - public BigDecimal getHeight() { - return height; - } - - public void setHeight(BigDecimal height) { - this.height = height; - } - - @Column(name="uncertainty") - public BigDecimal getUncertainty() { - return uncertainty; - } - - public void setUncertainty(BigDecimal uncertainty) { - this.uncertainty = uncertainty; - } - - @Column(name="data_gap") - public BigDecimal getDataGap() { - return dataGap; - } - - public void setDataGap(BigDecimal dataGap) { - this.dataGap = dataGap; - } - - @Column(name="sounding_width") - public BigDecimal getSoundingWidth() { - return soundingWidth; - } - - public void setSoundingWidth(BigDecimal soundingWidth) { - this.soundingWidth = soundingWidth; - } - - @Column(name="width") - public BigDecimal getWidth() { - return width; - } - - public void setWidth(BigDecimal width) { - this.width = width; - } - - - public static List<BedHeightSingleValue> getBedHeightSingleValues( - BedHeightSingle single, - double kmLo, - double kmHi - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from BedHeightSingleValue where bedHeight=:single " + - " and station >= :kmLo and station <= :kmHi"); - - query.setParameter("single", single); - query.setParameter("kmLo", new BigDecimal(kmLo)); - query.setParameter("kmHi", new BigDecimal(kmHi)); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/BedHeightType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,86 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; - -import de.intevation.flys.backend.SessionHolder; - -@Entity -@Table(name = "bed_height_type") -public class BedHeightType -implements Serializable -{ - private static Logger log = Logger.getLogger(BedHeightType.class); - - private Integer id; - private String name; - - - public BedHeightType() { - } - - public BedHeightType(String name) { - this.name = name; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_BED_HEIGHT_TYPE_ID_SEQ", - sequenceName = "BED_HEIGHT_TYPE_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_BED_HEIGHT_TYPE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public static BedHeightType fetchBedHeightTypeForType(String type) { - return fetchBedHeightTypeForType(type, null); - } - - public static BedHeightType fetchBedHeightTypeForType(String name, Session session) { - - if (session == null) { - session = SessionHolder.HOLDER.get(); - } - - Query query = session.createQuery( - "from BedHeightType where name=:name"); - - query.setParameter("name", name); - - List<Object> results = query.list(); - - return results.isEmpty() ? null : (BedHeightType)results.get(0); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/BoundaryKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "boundary_kinds") -public class BoundaryKind implements Serializable { - - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return name of the kind of boundary as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/Building.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,104 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.LineString; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "buildings") -public class Building -implements Serializable -{ - private Integer id; - private River river; - private String name; - private LineString geom; - - public Building() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public LineString getGeom() { - return geom; - } - - - public void setGeom(LineString geom) { - this.geom = geom; - } - - public static List<Building> getBuildings(int riverId, int kindId) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Building where river.id =:river_id and kind_id=:kind_id"); - query.setParameter("kind_id", kindId); - query.setParameter("river_id", riverId); - - return query.list(); - } - - public static List<Building> getBuildings(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Building where river.id =:river_id and name=:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/CrossSection.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,198 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.List; -import java.util.ArrayList; - -import java.awt.geom.Point2D; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.JoinColumn; - -import java.math.MathContext; -import java.math.BigDecimal; - -import org.hibernate.Session; -import org.hibernate.SQLQuery; -import org.hibernate.Query; - -import org.hibernate.type.StandardBasicTypes; - -import de.intevation.flys.backend.SessionHolder; - -@Entity -@Table(name = "cross_sections") -public class CrossSection -implements Serializable -{ - public static final MathContext PRECISION = new MathContext(6); - - public static final String SQL_FAST_CROSS_SECTION_LINES = - "SELECT km, x, y, csl.id AS csl_id " + - "FROM cross_section_lines csl JOIN cross_section_points csp " + - "ON csp.cross_section_line_id = csl.id " + - "WHERE csl.cross_section_id = :cs_id AND " + - "km between :from_km AND :to_km " + - "ORDER BY csl.id, csp.col_pos"; - - private Integer id; - private River river; - private TimeInterval timeInterval; - private String description; - private List<CrossSectionLine> lines; - - public CrossSection() { - } - - public CrossSection( - River river, - TimeInterval timeInterval, - String description - ) { - this.river = river; - this.timeInterval = timeInterval; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_CROSS_SECTIONS_ID_SEQ", - sequenceName = "CROSS_SECTIONS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_CROSS_SECTIONS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @OrderBy("km") - @JoinColumn(name="cross_section_id") - public List<CrossSectionLine> getLines() { - return lines; - } - - public void setLines(List<CrossSectionLine> lines) { - this.lines = lines; - } - - public List<CrossSectionLine> getLines(double startKm, double endKm) { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from CrossSectionLine where crossSection=:crossSection " + - "and km between :startKm and :endKm order by km"); - query.setParameter("crossSection", this); - query.setParameter("startKm", new BigDecimal(startKm, PRECISION)); - query.setParameter("endKm", new BigDecimal(endKm, PRECISION)); - - return query.list(); - } - - public List<FastCrossSectionLine> getFastLines( - double startKm, - double endKm - ) { - Session session = SessionHolder.HOLDER.get(); - - SQLQuery sqlQuery = session.createSQLQuery(SQL_FAST_CROSS_SECTION_LINES) - .addScalar("km", StandardBasicTypes.DOUBLE) - .addScalar("x", StandardBasicTypes.DOUBLE) - .addScalar("y", StandardBasicTypes.DOUBLE) - .addScalar("csl_id", StandardBasicTypes.INTEGER); - - sqlQuery - .setInteger("cs_id", getId()) - .setDouble("from_km", startKm) - .setDouble("to_km", endKm); - - List<Object []> results = sqlQuery.list(); - - ArrayList<Point2D> points = new ArrayList<Point2D>(500); - ArrayList<FastCrossSectionLine> lines = - new ArrayList<FastCrossSectionLine>(); - - Integer lastId = null; - Double lastKm = null; - - for (Object [] result: results) { - Double km = (Double)result[0]; - Double x = (Double)result[1]; - Double y = (Double)result[2]; - Integer id = (Integer)result[3]; - - if (lastId != null && !lastId.equals(id)) { - points.trimToSize(); - FastCrossSectionLine line = - new FastCrossSectionLine(lastKm, points); - lines.add(line); - points = new ArrayList<Point2D>(500); - } - - Point2D p = new Point2D.Double(x, y); - - if (CrossSectionLine.isValid(p)) { - points.add(p); - } - - lastKm = km; - lastId = id; - } - - if (lastId != null) { - points.trimToSize(); - FastCrossSectionLine line = - new FastCrossSectionLine(lastKm, points); - lines.add(line); - } - - lines.trimToSize(); - - return lines; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/CrossSectionLine.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,174 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.ArrayList; -import java.util.List; -import java.util.Collections; -import java.util.Comparator; - -import java.awt.geom.Point2D; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; -import javax.persistence.JoinColumn; - -import org.apache.log4j.Logger; - -@Entity -@Table(name = "cross_section_lines") -public class CrossSectionLine -implements Serializable -{ - private static Logger logger = Logger.getLogger(CrossSectionLine.class); - - public static final double EPSILON = 1e-4; - - public static final double TOO_SMALL = 0.2; - public static final double TOO_BIG = 2500; - - private Integer id; - private Double km; - private CrossSection crossSection; - - private List<CrossSectionPoint> points; - - public static final Comparator<CrossSectionPoint> COL_POS_CMP = - new Comparator<CrossSectionPoint>() { - @Override - public int compare(CrossSectionPoint a, CrossSectionPoint b) { - double xa = a.getX().doubleValue(); - double xb = b.getX().doubleValue(); - double d = xa - xb; - if (d < -EPSILON) return -1; - if (d > +EPSILON) return +1; - int diff = a.getColPos() - b.getColPos(); - return diff < 0 ? -1 : diff > 0 ? +1 : 0; - } - }; - - - public static final boolean isValid(double x) { - x = Math.abs(x); - return x > TOO_SMALL && x < TOO_BIG; - } - - public static final boolean isValid(Point2D p) { - return isValid(p.getX()) && isValid(p.getY()); - } - - - public CrossSectionLine() { - } - - public CrossSectionLine(CrossSection crossSection, Double km) { - this.crossSection = crossSection; - this.km = km; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_CROSS_SECTION_LINES_ID_SEQ", - sequenceName = "CROSS_SECTION_LINES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_CROSS_SECTION_LINES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "km") - public Double getKm() { - return km; - } - - public void setKm(Double km) { - this.km = km; - } - - @OneToOne - @JoinColumn(name = "cross_section_id") - public CrossSection getCrossSection() { - return crossSection; - } - - public void setCrossSection(CrossSection CrossSection) { - this.crossSection = crossSection; - } - - @OneToMany - @JoinColumn(name="cross_section_line_id") - public List<CrossSectionPoint> getPoints() { - return points; - } - - public void setPoints(List<CrossSectionPoint> points) { - this.points = points; - } - - - public List<Point2D> fetchCrossSectionLinesPoints() { - - List<CrossSectionPoint> linePoints = - new ArrayList<CrossSectionPoint>(getPoints()); - - Collections.sort(linePoints, COL_POS_CMP); - - List<Point2D> points = new ArrayList<Point2D>(linePoints.size()); - for (CrossSectionPoint p: linePoints) { - double x = p.getX().doubleValue(); - double y = p.getY().doubleValue(); - if (isValid(x) && isValid(y)) { - points.add(new Point2D.Double(x, y)); - } - } - - return points; - } - - public double [][] fetchCrossSectionProfile() { - return fetchCrossSectionProfile(fetchCrossSectionLinesPoints()); - } - - public static double [][] fetchCrossSectionProfile(List<Point2D> points) { - - int P = points.size(); - - double [] xs = new double[P]; - double [] ys = new double[P]; - - if (P > 0) { - xs[0] = points.get(0).getX(); - ys[0] = points.get(0).getY(); - - for (int i = 1; i < P; i++) { - Point2D p = points.get(i); - double x = p.getX(); - double y = p.getY(); - - if (x <= xs[i-1]) { - x = xs[i-1] + EPSILON; - } - - xs[i] = x; - ys[i] = y; - } - } - - return new double [][] { xs, ys }; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/CrossSectionPoint.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,96 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -/** Mapped Point of a cross section line. */ -@Entity -@Table(name = "cross_section_points") -public class CrossSectionPoint -implements Serializable -{ - private Integer id; - private CrossSectionLine crossSectionLine; - private Integer colPos; - private Double x; - private Double y; - - public CrossSectionPoint() { - } - - public CrossSectionPoint( - CrossSectionLine crossSectionLine, - Integer colPos, - Double x, - Double y - ) { - this.crossSectionLine = crossSectionLine; - this.colPos = colPos; - this.x = x; - this.y = y; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_CROSS_SECTION_POINTS_ID_SEQ", - sequenceName = "CROSS_SECTION_POINTS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_CROSS_SECTION_POINTS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "cross_section_line_id") - public CrossSectionLine getCrossSectionLine() { - return crossSectionLine; - } - - public void setCrossSectionLine(CrossSectionLine crossSectionLine) { - this.crossSectionLine = crossSectionLine; - } - - @Column(name = "col_pos") - public Integer getColPos() { - return colPos; - } - - public void setColPos(Integer colPos) { - this.colPos = colPos; - } - - @Column(name = "x") - public Double getX() { - return x; - } - - public void setX(Double x) { - this.x = x; - } - - @Column(name = "y") - public Double getY() { - return y; - } - - public void setY(Double y) { - this.y = y; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/CrossSectionTrack.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,200 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.LineString; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "cross_section_tracks") -public class CrossSectionTrack -implements Serializable -{ - private Integer id; - private River river; - private String name; - private LineString geom; - private BigDecimal km; - private BigDecimal z; - - public CrossSectionTrack() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public LineString getGeom() { - return geom; - } - - - public void setGeom(LineString geom) { - this.geom = geom; - } - - - @Column(name = "km") - public BigDecimal getKm() { - return km; - } - - - public void setKm(BigDecimal km) { - this.km = km; - } - - - @Column(name = "z") - public BigDecimal getZ() { - return z; - } - - - public void setZ(BigDecimal z) { - this.z = z; - } - - - public static List<CrossSectionTrack> getCrossSectionTrack( - String river) - { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from CrossSectionTrack where river.name =:river"); - query.setParameter("river", river); - - return query.list(); - } - - - public static List<CrossSectionTrack> getCrossSectionTrack( - String river, - String name - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from CrossSectionTrack as cst " + - " where river.name =:river" + - " and cst.name=:name"); - query.setParameter("river", river); - query.setParameter("name", name); - - return query.list(); - } - - public static List<CrossSectionTrack> getCrossSectionTrack( - String river, - int kind_id - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from CrossSectionTrack as cst " + - " where river.name =:river" + - " and kind_id=:kind_id"); - query.setParameter("river", river); - query.setParameter("kind_id", kind_id); - - return query.list(); - } - - public static List<CrossSectionTrack> getCrossSectionTrack( - String river, - String name, - int kind_id - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from CrossSectionTrack as cst " + - " where river.name =:river" + - " and cst.name=:name" + - " and kind_id=:kind_id"); - query.setParameter("river", river); - query.setParameter("name", name); - query.setParameter("kind_id", kind_id); - - return query.list(); - } - - - /** - * Returns the nearest CrossSectionTrack of <i>river</i> to a given - * <i>km</i>. - * - * @param river The name of a river. - * @param km The kilometer value. - * - * @return the nearest CrossSectionTrack to <i>km</i> of river <i>river</i>. - */ - public static CrossSectionTrack getCrossSectionTrack( - String river, - double km - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from CrossSectionTrack where river.name =:river " + - "and kind_id = 1 " + - "order by abs( km - :mykm)"); - query.setParameter("river", river); - query.setParameter("mykm", new BigDecimal(km)); - - List<CrossSectionTrack> cst = query.list(); - - return cst != null && !cst.isEmpty() ? cst.get(0) : null; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/CrossSectionTrackKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "cross_section_track_kinds") -public class CrossSectionTrackKind implements Serializable { - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return The name of the Cross section kind as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -} -
--- a/flys-backend/src/main/java/de/intevation/flys/model/DGM.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,138 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; -import java.math.BigDecimal; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.SequenceGenerator; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "dem") -public class DGM implements Serializable { - - private Integer id; - private Integer srid; - - private River river; - - private Range range; - private TimeInterval time_interval; - - private String path; - - - public DGM() { - } - - - public void setId(Integer id) { - this.id = id; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_DEM_ID_SEQ", - sequenceName = "DEM_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_DEM_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setPath(String path) { - this.path = path; - } - - @Column(name = "path") - public String getPath() { - return path; - } - - public void setSrid(int srid) { - this.srid = srid; - } - - @Column(name = "srid") - public int getSrid() { - return srid; - } - - public static DGM getDGM(int id) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from DGM where Id =:id"); - query.setParameter("id", id); - - List<DGM> result = query.list(); - - return result.isEmpty() ? null : result.get(0); - } - - - public static DGM getDGM(String river, double lower, double upper) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from DGM where river.name =:river and " + - "range.a <=:lower and range.b >=:lower and " + - "range.a <=:upper and range.b >=:upper"); - query.setParameter("river", river); - query.setParameter("lower", new BigDecimal(lower)); - query.setParameter("upper", new BigDecimal(upper)); - - List<DGM> result = query.list(); - - return result.isEmpty() ? null : result.get(0); - } - - @OneToOne - @JoinColumn(name = "range_id") - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return time_interval; - } - - public void setTimeInterval(TimeInterval time_interval) { - this.time_interval = time_interval; - } - - -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Depth.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,70 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - - -@Entity -@Table(name = "depths") -public class Depth implements Serializable { - - private Integer id; - - private BigDecimal lower; - private BigDecimal upper; - - - public Depth() { - } - - - public Depth(BigDecimal lower, BigDecimal upper) { - this.lower = lower; - this.upper = upper; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_DEPTHS_ID_SEQ", - sequenceName = "DEPTHS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_DEPTHS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "lower") - public BigDecimal getLower() { - return lower; - } - - public void setLower(BigDecimal lower) { - this.lower = lower; - } - - @Column(name = "upper") - public BigDecimal getUpper() { - return upper; - } - - public void setUpper(BigDecimal upper) { - this.upper = upper; - } - -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/DischargeTable.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,193 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.Date; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - -@Entity -@Table(name = "discharge_tables") -public class DischargeTable -implements Serializable, Comparable<DischargeTable> -{ - private Integer id; - private Gauge gauge; - private String description; - private String bfgId; - private Integer kind; - private TimeInterval timeInterval; - - private List<DischargeTableValue> dischargeTableValues; - - public DischargeTable() { - kind = 0; - } - - public DischargeTable(Gauge gauge) { - this(gauge, null, null, 0, null); - } - - public DischargeTable( - Gauge gauge, - String description, - String bfgId, - Integer kind, - TimeInterval timeInterval - ) { - this.gauge = gauge; - this.description = description; - this.bfgId = bfgId; - this.kind = kind; - this.timeInterval = timeInterval; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_DISCHARGE_TABLES_ID_SEQ", - sequenceName = "DISCHARGE_TABLES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_DISCHARGE_TABLES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "gauge_id" ) - public Gauge getGauge() { - return gauge; - } - - public void setGauge(Gauge gauge) { - this.gauge = gauge; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Column(name = "bfg_id") - public String getBfgId() { - return bfgId; - } - - public void setBfgId(String bfgId) { - this.bfgId = bfgId; - } - - @Column(name = "kind") - public Integer getKind() { - return kind; - } - - public void setKind(Integer kind) { - this.kind = kind; - } - - @OneToOne - @JoinColumn(name = "time_interval_id" ) - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - @OneToMany - @JoinColumn(name = "table_id") - @OrderBy("q") - public List<DischargeTableValue> getDischargeTableValues() { - return dischargeTableValues; - } - - public void setDischargeTableValues( - List<DischargeTableValue> dischargeTableValues - ) { - this.dischargeTableValues = dischargeTableValues; - } - - @Override - public int compareTo(DischargeTable o) { - if (getKind() == 0 && o.getKind() != 0) { - return 1; - } - - TimeInterval other = o.getTimeInterval(); - if (other == null && timeInterval == null) { - return 1; - } - else if (other == null) { - return -1; - } - else if (timeInterval == null) { - return 1; - } - - Date otherStartTime = other.getStartTime(); - Date thisStartTime = timeInterval.getStartTime(); - - if (otherStartTime == null) { - return -1; - } - else if (thisStartTime == null) { - return 1; - } - - long otherStart = otherStartTime.getTime(); - long thisStart = thisStartTime.getTime(); - - if (otherStart < thisStart) { - return 1; - } - else if (otherStart > thisStart) { - return -1; - } - - Date otherStopTime = other.getStopTime(); - Date thisStopTime = timeInterval.getStopTime(); - - if (otherStopTime == null) { - return -1; - } - else if (thisStopTime == null) { - return 1; - } - - long otherEnd = otherStopTime.getTime(); - long thisEnd = thisStopTime.getTime(); - - if (otherEnd < thisEnd) { - return 1; - } - else if (otherEnd > thisEnd) { - return -1; - } - else { - return 0; - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/DischargeTableValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,84 +0,0 @@ -package de.intevation.flys.model; - -import java.math.BigDecimal; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "discharge_table_values") -public class DischargeTableValue -implements Serializable -{ - private Integer id; - private DischargeTable dischargeTable; - private BigDecimal q; - private BigDecimal w; - - public DischargeTableValue() { - } - - public DischargeTableValue( - DischargeTable dischargeTable, BigDecimal q, BigDecimal w) - { - this.dischargeTable = dischargeTable; - this.q = q; - this.w = w; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_DISCHARGE_TABLE_VALUES_ID_SEQ", - sequenceName = "DISCHARGE_TABLE_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_DISCHARGE_TABLE_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "table_id" ) - public DischargeTable getDischargeTable() { - return dischargeTable; - } - - public void setDischargeTable(DischargeTable dischargeTable) { - this.dischargeTable = dischargeTable; - } - - - @Column(name = "q") - public BigDecimal getQ() { - return q; - } - - public void setQ(BigDecimal q) { - this.q = q; - } - - @Column(name = "w") - public BigDecimal getW() { - return w; - } - - public void setW(BigDecimal w) { - this.w = w; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/DischargeZone.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,159 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.hibernate.Session; -import org.hibernate.Query; - -import org.apache.log4j.Logger; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "discharge_zone") -public class DischargeZone -implements Serializable -{ - private static Logger logger = Logger.getLogger(DischargeZone.class); - - private Integer id; - - private River river; - - private String gaugeName; - - private BigDecimal value; - - private String lowerDischarge; - private String upperDischarge; - - private String type; - - public DischargeZone() { - } - - - public DischargeZone( - River river, - String gaugeName, - BigDecimal value, - String lowerDischarge, - String upperDischarge - ) { - this.river = river; - this.gaugeName = gaugeName; - this.value = value; - this.lowerDischarge = lowerDischarge; - this.upperDischarge = upperDischarge; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_DISCHARGE_ZONE_ID_SEQ", - sequenceName = "DISCHARGE_ZONE_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_DISCHARGE_ZONE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "value") - public BigDecimal getValue() { - return value; - } - - public void setValue(BigDecimal value) { - this.value = value; - } - - @Column(name = "gauge_name") - public String getGaugeName() { - return gaugeName; - } - - public void setGaugeName(String gaugeName) { - this.gaugeName = gaugeName; - } - - @Column(name = "lower_discharge") - public String getLowerDischarge() { - return lowerDischarge; - } - - public void setLowerDischarge(String lowerDischarge) { - this.lowerDischarge = lowerDischarge; - } - - @Column(name = "upper_discharge") - public String getUpperDischarge() { - return upperDischarge; - } - - public void setUpperDischarge(String upperDischarge) { - this.upperDischarge = upperDischarge; - } - - public void putType(String type) { - this.type = type; - } - - public String fetchType() { - return this.type; - } - - public static List<DischargeZone> getDischargeZones(River river) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from DischargeZone where river=:river"); - - query.setParameter("river", river); - - return query.list(); - } - - - public static DischargeZone getDischargeZoneById(int id) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from DischargeZone where id=:id"); - - query.setParameter("id", id); - - List<DischargeZone> zones = query.list(); - - return zones.isEmpty() ? null : zones.get(0); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Edge.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "edges") -public class Edge -implements Serializable -{ - private Integer id; - private BigDecimal top; - private BigDecimal bottom; - - public Edge() { - } - - public Edge(BigDecimal top, BigDecimal bottom) { - this.top = top; - this.bottom = bottom; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_EDGES_ID_SEQ", - sequenceName = "EDGES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_EDGES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "top") - public BigDecimal getTop() { - return top; - } - - public void setTop(BigDecimal top) { - this.top = top; - } - - @Column(name = "bottom") - public BigDecimal getBottom() { - return bottom; - } - - public void setBottom(BigDecimal bottom) { - this.bottom = bottom; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/ElevationModel.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,78 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - - -@Entity -@Table(name = "elevation_model") -public class ElevationModel -implements Serializable -{ - private static Logger logger = Logger.getLogger(ElevationModel.class); - - protected Integer id; - - protected String name; - - protected Unit unit; - - - public ElevationModel() { - } - - - public ElevationModel(String name, Unit unit) { - this.name = name; - this.unit = unit; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_ELEVATION_MODE_ID_SEQ", - sequenceName = "ELEVATION_MODEL_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_ELEVATION_MODE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @OneToOne - @JoinColumn(name = "unit_id") - public Unit getUnit() { - return unit; - } - - public void setUnit(Unit unit) { - this.unit = unit; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FastAnnotations.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,335 +0,0 @@ -package de.intevation.flys.model; - -import java.util.Comparator; -import java.util.ArrayList; -import java.util.List; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import java.io.Serializable; - -import org.hibernate.Session; -import org.hibernate.SQLQuery; - -import org.hibernate.type.StandardBasicTypes; - -import de.intevation.flys.backend.SessionHolder; - -public class FastAnnotations -implements Serializable -{ - public static final String SQL_BY_RIVER_NAME = - "SELECT r.a AS a, r.b AS b, p.value AS position, " + - "at.value AS attribute, ant.name AS name, " + - "e.top AS top, e.bottom AS bottom " + - "FROM annotations an " + - "JOIN ranges r " + - "ON an.range_id = r.id " + - "JOIN attributes at " + - "ON an.attribute_id = at.id " + - "JOIN positions p " + - "ON an.position_id = p.id " + - "JOIN rivers riv " + - "ON r.river_id = riv.id " + - "LEFT JOIN annotation_types ant " + - "ON an.type_id = ant.id " + - "LEFT JOIN edges e " + - "ON an.edge_id = e.id " + - "WHERE riv.name = :river_name " + - "ORDER BY r.a"; - - public static final String SQL_BY_RIVER_ID = - "SELECT r.a AS a, r.b AS b, p.value AS position, " + - "at.value AS attribute, ant.name AS name, " + - "e.top AS top, e.bottom AS bottom " + - "FROM annotations an " + - "JOIN ranges r " + - "ON an.range_id = r.id " + - "JOIN attributes at " + - "ON an.attribute_id = at.id " + - "JOIN positions p " + - "ON an.position_id = p.id " + - "LEFT JOIN annotation_types ant " + - "ON an.type_id = ant.id " + - "LEFT JOIN edges e " + - "ON an.edge_id = e.id " + - "WHERE r.id = :river_id " + - "ORDER BY r.a"; - - public static final double EPSILON = 1e-5; - - public static final Comparator<Annotation> KM_CMP = - new Comparator<Annotation>() { - @Override - public int compare(Annotation a, Annotation b) { - double diff = a.a - b.a; - if (diff < -EPSILON) return -1; - if (diff > +EPSILON) return +1; - return 0; - } - }; - - public static final class Annotation - implements Serializable - { - private double a; - private double b; - private String position; - private String attribute; - private String name; - private double top; - private double bottom; - - public Annotation() { - } - - public Annotation(double a) { - this.a = a; - } - - public Annotation( - double a, - double b, - String position, - String attribute, - String name, - double top, - double bottom - ) { - this.a = a; - this.b = b; - this.position = position; - this.attribute = attribute; - this.name = name; - this.top = top; - this.bottom = bottom; - } - - public double getA() { - return a; - } - - public double getB() { - return b; - } - - public String getPosition() { - return position; - } - - public String getAttribute() { - return attribute; - } - - public String getName() { - return name; - } - - public double getTop() { - return top; - } - - public double getBottom() { - return bottom; - } - - @Override - public String toString() { - return "[a=" + a + ";b=" + b + - ";pos=" + position + ";attr=" + attribute + - ";name=" + name + ";top=" + top + - ";bot=" + bottom + "]"; - } - } // class Annotation - - public interface Filter { - - boolean accept(Annotation annotation); - - } // interface Filter - - public static class NameFilter implements Filter { - - private String name; - - public NameFilter(String name) { - this.name = name; - } - - @Override - public boolean accept(Annotation annotation) { - return annotation.getName().contains(name); - } - } // class NameFilter - - public static final Filter ALL = new Filter() { - @Override - public boolean accept(Annotation annotation) { - return true; - } - }; - - public static final Filter IS_POINT = new Filter() { - @Override - public boolean accept(Annotation annotation) { - return Double.isNaN(annotation.getB()); - } - }; - - public static final Filter IS_RANGE = new Filter() { - @Override - public boolean accept(Annotation annotation) { - return !Double.isNaN(annotation.getB()); - } - }; - - private Annotation [] annotations; - - public FastAnnotations() { - } - - public FastAnnotations(Annotation [] annotations) { - this.annotations = annotations; - } - - public FastAnnotations(String riverName) { - this(loadByRiverName(riverName)); - } - - public FastAnnotations(int riverId) { - this(loadByRiverId(riverId)); - } - - public FastAnnotations(Iterator<Annotation> iter) { - this(toArray(iter)); - } - - public int size() { - return annotations.length; - } - - public Iterator<Annotation> filter(final Filter filter) { - return new Iterator<Annotation>() { - - private int idx; - private Annotation current = findNext(); - - @Override - public boolean hasNext() { - return current != null; - } - - @Override - public Annotation next() { - if (current == null) { - throw new NoSuchElementException(); - } - Annotation result = current; - current = findNext(); - return result; - } - - private Annotation findNext() { - - while (idx < annotations.length) { - Annotation annotation = annotations[idx++]; - if (filter.accept(annotation)) { - return annotation; - } - } - - return null; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - public static Annotation [] toArray(Iterator<Annotation> iter) { - - ArrayList<Annotation> list = new ArrayList<Annotation>(); - - while (iter.hasNext()) { - list.add(iter.next()); - } - - return list.toArray(new Annotation[list.size()]); - } - - public Annotation findByKm(double km) { - Annotation key = new Annotation(km); - int idx = Arrays.binarySearch(annotations, key, KM_CMP); - return idx < 0 ? null : annotations[idx]; - } - - private static SQLQuery createQuery(String query) { - Session session = SessionHolder.HOLDER.get(); - - return session.createSQLQuery(query) - .addScalar("a", StandardBasicTypes.DOUBLE) - .addScalar("b", StandardBasicTypes.DOUBLE) - .addScalar("position", StandardBasicTypes.STRING) - .addScalar("attribute", StandardBasicTypes.STRING) - .addScalar("name", StandardBasicTypes.STRING) - .addScalar("top", StandardBasicTypes.DOUBLE) - .addScalar("bottom", StandardBasicTypes.DOUBLE); - } - - private static Annotation [] buildAnnotations(List<Object []> list) { - Annotation [] anns = new Annotation[list.size()]; - - // Names are likely the same because they are a type - // like 'Pegel' or 'Hafen'. - HashMap<String, String> names = new HashMap<String, String>(); - - for (int i = 0; i < anns.length; ++i) { - Object [] data = list.get(i); - double a = ((Double)data[0]); - double b = data[1] != null ? (Double)data[1] : Double.NaN; - String position = (String)data[2]; - String attribute = (String)data[3]; - String name = (String)data[4]; - double top = data[5] != null ? (Double)data[5] : Double.NaN; - double bottom = data[6] != null ? (Double)data[6] : Double.NaN; - - if (name != null) { - String old = names.get(name); - if (old != null) { - name = old; - } - else { - names.put(name, name); - } - } - - anns[i] = new Annotation( - a, b, position, attribute, name, top, bottom); - } - - return anns; - } - - public static Annotation [] loadByRiverName(String riverName) { - - SQLQuery query = createQuery(SQL_BY_RIVER_NAME); - - query.setString("river_name", riverName); - - return buildAnnotations(query.list()); - } - - public static Annotation [] loadByRiverId(int riverId) { - - SQLQuery query = createQuery(SQL_BY_RIVER_ID); - - query.setInteger("river_id", riverId); - - return buildAnnotations(query.list()); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FastCrossSectionLine.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -package de.intevation.flys.model; - -import java.util.List; -import java.util.Comparator; - -import java.io.Serializable; - -import java.awt.geom.Point2D; - -public class FastCrossSectionLine -implements Serializable -{ - public static final double EPSILON = 1e-5; - - public static final Comparator<FastCrossSectionLine> KM_CMP = - new Comparator<FastCrossSectionLine>() { - public int compare( - FastCrossSectionLine a, - FastCrossSectionLine b - ) { - double diff = a.km - b.km; - if (diff < -EPSILON) return -1; - return diff > +EPSILON ? +1 : 0; - } - }; - - protected double km; - protected List<Point2D> points; - - public FastCrossSectionLine() { - } - - public FastCrossSectionLine(double km) { - this.km = km; - } - - public FastCrossSectionLine(double km, List<Point2D> points) { - this(km); - this.points = points; - } - - public FastCrossSectionLine(CrossSectionLine csl) { - Double kmBD = csl.getKm(); - km = kmBD != null ? kmBD.doubleValue() : 0d; - points = csl.fetchCrossSectionLinesPoints(); - } - - public double getKm() { - return km; - } - - public void setKm(double km) { - this.km = km; - } - - public List<Point2D> getPoints() { - return points; - } - - public void setPoints(List<Point2D> points) { - this.points = points; - } - - public double [][] fetchCrossSectionProfile() { - return CrossSectionLine.fetchCrossSectionProfile(points); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FedState.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "fed_states") -public class FedState implements Serializable { - - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return name of the Federal State as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/Fixpoint.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,130 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.Point; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "fixpoints") -public class Fixpoint -implements Serializable -{ - private Integer id; - private River river; - private Integer x; - private Integer y; - private BigDecimal km; - private String hpgp; - private Point geom; - - public Fixpoint() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "x") - public Integer getX() { - return x; - } - - - public void setX(Integer x) { - this.x = x; - } - - - @Column(name = "y") - public Integer getY() { - return y; - } - - - public void setY(Integer y) { - this.y = y; - } - - - @Column(name = "km") - public BigDecimal getKm() { - return km; - } - - - public void setKm(BigDecimal km) { - this.km = km; - } - - - @Column(name = "hpgp") - public String getHpgp() { - return hpgp; - } - - - public void setHpgp(String hpgp) { - this.hpgp = hpgp; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Point getGeom() { - return geom; - } - - - public void setGeom(Point geom) { - this.geom = geom; - } - - - public static List<Fixpoint> getFixpoints(int riverId) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Fixpoint where river.id =:river_id"); - query.setParameter("river_id", riverId); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Floodmaps.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,155 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.Geometry; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "floodmaps") -public class Floodmaps -implements Serializable -{ - private Integer id; - private River river; - private String name; - private Integer kind; - private Integer count; - private BigDecimal diff; - private BigDecimal area; - private BigDecimal perimeter; - private Geometry geom; - - public Floodmaps() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "kind") - public Integer getKind() { - return kind; - } - - - public void setKind(Integer kind) { - this.kind = kind; - } - - - @Column(name = "count") - public Integer getCount() { - return count; - } - - - public void setCount(Integer count) { - this.count = count; - } - - - @Column(name = "diff") - public BigDecimal getDiff() { - return diff; - } - - - public void setDiff(BigDecimal diff) { - this.diff = diff; - } - - - @Column(name = "area") - public BigDecimal getArea() { - return area; - } - - - public void setArea(BigDecimal area) { - this.area = area; - } - - - @Column(name = "perimeter") - public BigDecimal getPerimeter() { - return perimeter; - } - - - public void setPerimeter(BigDecimal perimeter) { - this.perimeter = perimeter; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Geometry getGeom() { - return geom; - } - - - public void setGeom(Geometry geom) { - this.geom = geom; - } - - - public static List<Floodmaps> getFloodmaps(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Floodmaps where river.id =:river_id AND name =:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Floodmark.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,129 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.Point; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "flood_marks") -public class Floodmark -implements Serializable -{ - private Integer id; - private River river; - private Integer z; - private Integer year; - private BigDecimal km; - private Point geom; - - public Floodmark() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "z") - public Integer getZ() { - return z; - } - - - public void setZ(Integer z) { - this.z = z; - } - - - @Column(name = "year") - public Integer getYear() { - return year; - } - - - public void setYear(Integer year) { - this.year = year; - } - - - @Column(name = "km") - public BigDecimal getKm() { - return km; - } - - - public void setKm(BigDecimal km) { - this.km = km; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Point getGeom() { - return geom; - } - - - public void setGeom(Point geom) { - this.geom = geom; - } - - public static List<Floodmark> getFloodmarks(int riverId) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Floodmark where river.id =:river_id"); - query.setParameter("river_id", riverId); - - return query.list(); - } - - public static List<Floodmark> getFloodmarks(int riverId, int year) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Floodmark where river.id =:river_id and year = :year"); - query.setParameter("river_id", riverId); - query.setParameter("year", year); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : -
--- a/flys-backend/src/main/java/de/intevation/flys/model/Floodplain.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,134 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.annotations.Type; -import org.hibernate.HibernateException; - -import com.vividsolutions.jts.geom.Polygon; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "floodplain") -public class Floodplain -implements Serializable -{ - private Integer id; - - private FloodplainKind kind; - - private River river; - - private Polygon geom; - - private String name; - - - public Floodplain() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "kind_id") - public FloodplainKind getKind() { - return kind; - } - - public void setKind(FloodplainKind kind) { - this.kind = kind; - } - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Polygon getGeom() { - return geom; - } - - public void setGeom(Polygon geom) { - this.geom = geom; - } - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - public static List<Floodplain> getFloodplains(String river, String name, int kind) - throws HibernateException { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from Floodplain as fp where river.name =:river" + - " and kind.id =:kind" + - " and fp.name=:name"); - query.setParameter("river", river); - query.setParameter("kind", kind); - query.setParameter("name", name); - - List<Floodplain> list = query.list(); - return list.isEmpty() ? null : list; - } - - public static List<Floodplain> getFloodplains(String river, int kind) - throws HibernateException { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from Floodplain where river.name =:river AND kind.id =:kind"); - query.setParameter("river", river); - query.setParameter("kind", kind); - - List<Floodplain> list = query.list(); - return list.isEmpty() ? null : list; - } - - public static Floodplain getFloodplain(String river) { - Session session = SessionHolder.HOLDER.get(); - - // kind_id 0 -> Offical - // kind_id 1 -> Misc. - Query query = session.createQuery( - "from Floodplain where river.name =:river and kind_id=1"); - query.setParameter("river", river); - - List<Floodplain> result = query.list(); - - return result.isEmpty() ? null : result.get(0); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FloodplainKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "floodplain_kinds") -public class FloodplainKind implements Serializable { - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return The name of the Floodplain Kind as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -} -
--- a/flys-backend/src/main/java/de/intevation/flys/model/FlowVelocityMeasurement.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,96 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -import org.apache.log4j.Logger; - - -@Entity -@Table(name = "flow_velocity_measurements") -public class FlowVelocityMeasurement -implements Serializable -{ - private static Logger logger = - Logger.getLogger(FlowVelocityMeasurement.class); - - private Integer id; - - private River river; - - private String description; - - private List<FlowVelocityMeasurementValue> values; - - - public FlowVelocityMeasurement() { - } - - - public FlowVelocityMeasurement(River river, String description) { - this.river = river; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_FV_MEASURE_ID_SEQ", - sequenceName = "FV_MEASURE_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_FV_MEASURE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @JoinColumn(name = "measurements_id") - public List<FlowVelocityMeasurementValue> getValues() { - return values; - } - - public void setValues(List<FlowVelocityMeasurementValue> values) { - this.values = values; - } - - public void addValue(FlowVelocityMeasurementValue value) { - this.values.add(value); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FlowVelocityMeasurementValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,196 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - - -/** Measured Flow Velocities. */ -@Entity -@Table(name = "flow_velocity_measure_values") -public class FlowVelocityMeasurementValue -implements Serializable -{ - private static Logger logger = - Logger.getLogger(FlowVelocityMeasurementValue.class); - - private Integer id; - - private FlowVelocityMeasurement measurement; - - private BigDecimal station; - private BigDecimal w; - private BigDecimal q; - private BigDecimal v; - - private Date datetime; - - private String description; - - /** Non-mapped class holding same values. */ - public static class FastFlowVelocityMeasurementValue { - protected double station; - protected double w; - protected double q; - protected double v; - protected Date datetime; - protected String description; - - public FastFlowVelocityMeasurementValue(double station, - double w, double q, double v, Date datetime, String description) { - this.station = station; - this.w = w; - this.q = q; - this.v = v; - this.datetime = datetime; - this.description = description; - } - - public double getStation() { - return station; - } - - public double getW() { - return w; - } - - public double getQ() { - return q; - } - - public double getV() { - return v; - } - - public Date getDatetime() { - return datetime; - } - - public String getDescription() { - return description; - } - } - - - public FlowVelocityMeasurementValue() { - } - - - public FlowVelocityMeasurementValue( - FlowVelocityMeasurement measurement, - Date datetime, - BigDecimal station, - BigDecimal w, - BigDecimal q, - BigDecimal v, - String description - ) { - this.measurement = measurement; - this.datetime = datetime; - this.station = station; - this.w = w; - this.q = q; - this.v = v; - this.description = description; - } - - public static FastFlowVelocityMeasurementValue getUnmapped( - double station, double w, double q, double v, Date datetime, String description) { - return new FastFlowVelocityMeasurementValue( - station, w, q, v, datetime, description); - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_FV_MEASURE_VALUES_ID_SEQ", - sequenceName = "FV_MEASURE_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_FV_MEASURE_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "measurements_id") - public FlowVelocityMeasurement getMeasurement() { - return measurement; - } - - public void setMeasurement(FlowVelocityMeasurement measurement) { - this.measurement = measurement; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "datetime") - public Date getDatetime() { - return datetime; - } - - public void setDatetime(Date datetime) { - this.datetime = datetime; - } - - @Column(name = "w") - public BigDecimal getW() { - return w; - } - - public void setW(BigDecimal w) { - this.w = w; - } - - @Column(name = "q") - public BigDecimal getQ() { - return q; - } - - public void setQ(BigDecimal q) { - this.q = q; - } - - @Column(name = "v") - public BigDecimal getV() { - return v; - } - - public void setV(BigDecimal v) { - this.v = v; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FlowVelocityModel.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,106 +0,0 @@ -package de.intevation.flys.model; - -import de.intevation.flys.backend.SessionHolder; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - -import org.apache.log4j.Logger; - -import org.hibernate.Query; -import org.hibernate.Session; - - -@Entity -@Table(name = "flow_velocity_model") -public class FlowVelocityModel -implements Serializable -{ - private static Logger logger = Logger.getLogger(FlowVelocityModel.class); - - - private Integer id; - - private DischargeZone dischargeZone; - - private String description; - - - public FlowVelocityModel() { - } - - - public FlowVelocityModel(DischargeZone dischargeZone) { - this(dischargeZone, null); - } - - - public FlowVelocityModel( - DischargeZone dischargeZone, - String description - ) { - this.dischargeZone = dischargeZone; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_FLOW_VELOCITY_MODEL_ID_SEQ", - sequenceName = "FLOW_VELOCITY_MODEL_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_FLOW_VELOCITY_MODEL_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "discharge_zone_id") - public DischargeZone getDischargeZone() { - return dischargeZone; - } - - public void setDischargeZone(DischargeZone dischargeZone) { - this.dischargeZone = dischargeZone; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - public static List<FlowVelocityModel> getModels(DischargeZone zone) { - - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from FlowVelocityModel where dischargeZone=:zone"); - - query.setParameter("zone", zone); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/FlowVelocityModelValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.hibernate.Session; -import org.hibernate.Query; - -import org.apache.log4j.Logger; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "flow_velocity_model_values") -public class FlowVelocityModelValue -implements Serializable -{ - private static Logger logger = - Logger.getLogger(FlowVelocityModelValue.class); - - - private Integer id; - - private FlowVelocityModel flowVelocity; - - private BigDecimal station; - private BigDecimal q; - private BigDecimal totalChannel; - private BigDecimal mainChannel; - private BigDecimal shearStress; - - - public FlowVelocityModelValue() { - } - - - public FlowVelocityModelValue( - FlowVelocityModel flowVelocity, - BigDecimal station, - BigDecimal q, - BigDecimal totalChannel, - BigDecimal mainChannel, - BigDecimal shearStress - ) { - this.flowVelocity = flowVelocity; - this.station = station; - this.q = q; - this.totalChannel = totalChannel; - this.mainChannel = mainChannel; - this.shearStress = shearStress; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_FLOW_VELOCITY_M_VALUES_ID_SEQ", - sequenceName = "FLOW_VELOCITY_M_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_FLOW_VELOCITY_M_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "flow_velocity_model_id") - public FlowVelocityModel getFlowVelocity() { - return flowVelocity; - } - - public void setFlowVelocity(FlowVelocityModel flowVelocity) { - this.flowVelocity = flowVelocity; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "q") - public BigDecimal getQ() { - return q; - } - - public void setQ(BigDecimal q) { - this.q = q; - } - - @Column(name = "total_channel") - public BigDecimal getTotalChannel() { - return totalChannel; - } - - public void setTotalChannel(BigDecimal totalChannel) { - this.totalChannel = totalChannel; - } - - @Column(name = "main_channel") - public BigDecimal getMainChannel() { - return mainChannel; - } - - public void setMainChannel(BigDecimal mainChannel) { - this.mainChannel = mainChannel; - } - - @Column(name = "shear_stress") - public BigDecimal getShearStress() { - return shearStress; - } - - public void setShearStress(BigDecimal shearStress) { - this.shearStress = shearStress; - } - - - public static List<FlowVelocityModelValue> getValues( - FlowVelocityModel model, - double kmLo, - double kmHi - ) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from FlowVelocityModelValue where " + - " flowVelocity=:model and" + - " station >= :kmLo and " + - " station <= :kmHi"); - - query.setParameter("model", model); - query.setParameter("kmLo", new BigDecimal(kmLo)); - query.setParameter("kmHi", new BigDecimal(kmHi)); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Gauge.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,334 +0,0 @@ -package de.intevation.flys.model; - -import java.math.BigDecimal; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - -/** Database-mapped Gauge with all info about it. */ -@Entity -@Table(name = "gauges") -public class Gauge -implements Serializable, Comparable<Gauge> -{ - public static final int DEFAULT_SCALE = 100; - - public static final int MASTER_DISCHARGE_TABLE = 0; - - private Integer id; - private String name; - private River river; - private BigDecimal station; - private BigDecimal aeo; - private BigDecimal datum; - private Long officialNumber; - private Range range; - - private List<DischargeTable> dischargeTables; - - /** MainValues at this Gauge. */ - protected List<MainValue> mainValues; - - public Gauge() { - } - - public Gauge( - String name, - River river, - BigDecimal station, - BigDecimal aeo, - BigDecimal datum, - Long officialNumber, - Range range - ) { - this.name = name; - this.river = river; - this.station = station; - this.aeo = aeo; - this.datum = datum; - this.officialNumber = officialNumber; - this.range = range; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_GAUGES_ID_SEQ", - sequenceName = "GAUGES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_GAUGES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "station") // FIXME: type mapping needed - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "aeo") // FIXME: type mapping needed - public BigDecimal getAeo() { - return aeo; - } - - public void setAeo(BigDecimal aeo) { - this.aeo = aeo; - } - - @Column(name = "datum") // FIXME: type mapping needed - public BigDecimal getDatum() { - return datum; - } - - public void setDatum(BigDecimal datum) { - this.datum = datum; - } - - @Column(name = "official_number") - public Long getOfficialNumber() { - return officialNumber; - } - - public void setOfficialNumber(Long officialNumber) { - this.officialNumber = officialNumber; - } - - @OneToOne - @JoinColumn(name = "range_id" ) - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @OneToMany - @JoinColumn(name = "gauge_id") - public List<DischargeTable> getDischargeTables() { - return dischargeTables; - } - - public void setDischargeTables(List<DischargeTable> dischargeTables) { - this.dischargeTables = dischargeTables; - } - - - /** - * Returns min and max W values of this gauge based with a DEFAULT_SCALE. - * - * @return min and max W value of this gauge [min,max]. - */ - public double[] determineMinMaxW() { - return determineMinMaxW(DEFAULT_SCALE); - } - - - /** - * Returns min and max W values of this gauge. - * - * @return the min and max W value of this gauge [min,max]. - */ - public double[] determineMinMaxW(int scale) { - Session session = SessionHolder.HOLDER.get(); - - List<DischargeTable> tables = getDischargeTables(); - DischargeTable dischargeTable = null; - - for (DischargeTable tmp: tables) { - if (tmp.getKind() == 0) { - dischargeTable = tmp; - break; - } - } - - if (dischargeTable == null) { - return null; - } - - Query query = session.createQuery( - "select min(w) as min, max(w) as max from DischargeTableValue " + - "where table_id =:table"); - query.setParameter("table", dischargeTable.getId()); - - List results = query.list(); - Object[] result = (Object[]) results.get(0); - - return result != null - ? new double[] { - ((BigDecimal) result[0]).doubleValue() * scale, - ((BigDecimal) result[1]).doubleValue() * scale} - : null; - } - - @OneToMany - @JoinColumn(name = "gauge_id") - public List<MainValue> getMainValues() { - return mainValues; - } - - public void setMainValues(List<MainValue> mainValues) { - this.mainValues = mainValues; - } - - - public static Gauge getGaugeByOfficialNumber(long number) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Gauge where officialNumber=:number"); - - query.setParameter("number", number); - - List<Gauge> results = query.list(); - - return results.isEmpty() ? null : results.get(0); - } - - - public DischargeTable fetchMasterDischargeTable() { - for (DischargeTable dt: dischargeTables) { - if (dt.getKind() == MASTER_DISCHARGE_TABLE) { - return dt; - } - } - - return null; - } - - /** - * Returns an array of [days, qs] necessary to create duration curves. - * - * @return a 2dim array of [days, qs] where days is an int[] and qs is - * an double[]. - */ - public Object[] fetchDurationCurveData() { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "select cast(nmv.name as integer) as days, mv.value as q " + - "from MainValue as mv " + - "join mv.mainValue as nmv " + - "join nmv.type mvt " + - "where mvt.name = 'D' and mv.gauge.id = :gauge_id " + - "order by days"); - - query.setParameter("gauge_id", getId()); - - List<Object> results = query.list(); - int[] days = new int[results.size()]; - double[] qs = new double[results.size()]; - - int idx = 0; - - for (Object obj: results) { - Object[] arr = (Object[]) obj; - - try { - int day = ((Integer) arr[0]).intValue(); - double q = ((BigDecimal) arr[1]).doubleValue(); - - days[idx] = day; - qs[idx++] = q; - } - catch (NumberFormatException nfe) { - } - } - - return new Object[] { days, qs }; - } - - /** - * Calculates the maximum and minimum W and Q values - * - * @return the MaxMinWQ object representing the calculated values - */ - public MinMaxWQ fetchMaxMinWQ() { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "select max(mv.value) as max, min(mv.value) as min " + - "from MainValue as mv " + - "join mv.mainValue as nmv " + - "join nmv.type mvt " + - "where mvt.name in ('W', 'Q') " + - "and mv.gauge.id = :gauge_id " + - "group by mvt.name order by mvt.name" - ); - - query.setParameter("gauge_id", getId()); - - List<Object> results = query.list(); - if (results.isEmpty()) { - // No values found - return new MinMaxWQ(); - } - - Object[] arr = (Object[]) results.get(0); - BigDecimal maxw = (BigDecimal)arr[0]; - BigDecimal minw = (BigDecimal)arr[1]; - BigDecimal maxq = null; - BigDecimal minq = null; - - - if (results.size() > 1) { - arr = (Object[]) results.get(1); - maxq = (BigDecimal)arr[0]; - minq = (BigDecimal)arr[1]; - } - - return new MinMaxWQ(minw, maxw, minq, maxq); - } - - @Override - public int compareTo(Gauge o) { - return getName().compareTo(o.getName()); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/GaugeLocation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,106 +0,0 @@ -package de.intevation.flys.model; - -import com.vividsolutions.jts.geom.Point; - -import de.intevation.flys.backend.SessionHolder; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Query; -import org.hibernate.Session; - -import org.hibernate.annotations.Type; - - -@Entity -@Table(name = "gauge_location") -public class GaugeLocation -implements Serializable -{ - private Integer id; - private River river; - private String name; - private Point geom; - - - public GaugeLocation() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Point getGeom() { - return geom; - } - - - public void setGeom(Point geom) { - this.geom = geom; - } - - - /** - * Returns a list of RiverAxisKm objects for a given river. - * - * @param riverid The ID of a river in the database. - * - * @return a list of RiverAxisKm objects. - */ - public static List<GaugeLocation> getGaugeLocations(int riverid, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from GaugeLocation where river.id =:riverid and name=:name"); - query.setParameter("riverid", riverid); - query.setParameter("name", name); - - List<GaugeLocation> list = query.list(); - - return list; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/GrainFraction.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -import org.apache.log4j.Logger; - - -@Entity -@Table(name = "grain_fraction") -public class GrainFraction -implements Serializable -{ - public static final String TOTAL = "total"; - public static final String COARSE = "coarse"; - public static final String FINE_MIDDLE = "fine_middle"; - public static final String SAND = "sand"; - public static final String SUSP_SAND = "susp_sand"; - public static final String SUSP_SAND_BED = "susp_sand_bed"; - public static final String SUSPENDED_SEDIMENT = "suspended_sediment"; - - - private static Logger logger = Logger.getLogger(GrainFraction.class); - - private Integer id; - - private String name; - - private Double lower; - private Double upper; - - - public GrainFraction() { - } - - public GrainFraction(String name, Double lower, Double upper) { - this.name = name; - this.lower = lower; - this.upper = upper; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_GRAIN_FRACTION_ID_SEQ", - sequenceName = "GRAIN_FRACTION_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_GRAIN_FRACTION_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name" ) - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "lower") - public Double getLower() { - return lower; - } - - public void setLower(Double lower) { - this.lower = lower; - } - - @Column(name = "upper") - public Double getUpper() { - return upper; - } - - public void setUpper(Double upper) { - this.upper = upper; - } - -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HWSKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "hws_kinds") -public class HWSKind implements Serializable { - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return The name of the Hochwasserschutzanlagenart as String. - */ - @Column(name = "kind") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/HWSLine.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,336 +0,0 @@ -package de.intevation.flys.model; - -import com.vividsolutions.jts.geom.Geometry; - -import de.intevation.flys.model.HWSKind; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.SequenceGenerator; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import de.intevation.flys.backend.SessionHolder; - -@Entity -@Table(name = "hws_lines") -public class HWSLine implements Serializable { - - private Integer id; - - private Integer ogrFid; - private HWSKind kind; - private FedState fedState; - private River river; - private Integer official; - private Integer shoreSide; - private String name; - private String path; - private String agency; - private String range; - private String source; - private String status_date; - private String description; - private Geometry geom; - - @Id - @SequenceGenerator( - name = "SEQUENCE_HWS_LINES_ID_SEQ", - sequenceName = "HWS_LINES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HWS_LINES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Geometry getGeom() { - return geom; - } - - - public void setGeom(Geometry geom) { - this.geom = geom; - } - - /** - * Get ogrFid. - * - * @return ogrFid as Integer. - */ - @Column(name = "ogr_fid") - public Integer getOgrFid() { - return ogrFid; - } - - /** - * Set ogrFid. - * - * @param ogrFid the value to set. - */ - public void setOgrFid(Integer ogrFid) { - this.ogrFid = ogrFid; - } - - - /** - * Get official. - * - * @return official as Integer. - */ - @Column(name = "official") - public Integer getofficial() { - return official; - } - - /** - * Set official. - * - * @param official the value to set. - */ - public void setofficial(Integer official) { - this.official = official; - } - - /** - * Get shoreSide. - * - * @return shoreSide as Integer. - */ - @Column(name = "shore_side") - public Integer getShoreSide() { - return shoreSide; - } - - /** - * Set shoreSide. - * - * @param shoreSide the value to set. - */ - public void setShoreSide(Integer shoreSide) { - this.shoreSide = shoreSide; - } - - /** - * Get name. - * - * @return name as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Get path. - * - * @return path as String. - */ - @Column(name = "path") - public String getPath() { - return path; - } - - /** - * Set path. - * - * @param path the value to set. - */ - public void setPath(String path) { - this.path = path; - } - - /** - * Get agency. - * - * @return agency as String. - */ - @Column(name = "agency") - public String getAgency() { - return agency; - } - - /** - * Set agency. - * - * @param agency the value to set. - */ - public void setAgency(String agency) { - this.agency = agency; - } - - /** - * Get range. - * - * @return range as String. - */ - @Column(name = "range") - public String getRange() { - return range; - } - - /** - * Set range. - * - * @param range the value to set. - */ - public void setRange(String range) { - this.range = range; - } - - /** - * Get source. - * - * @return source as String. - */ - @Column(name = "source") - public String getSource() { - return source; - } - - /** - * Set source. - * - * @param source the value to set. - */ - public void setSource(String source) { - this.source = source; - } - - /** - * Get status_date. - * - * @return status_date as String. - */ - @Column(name = "status_date") - public String getStatusDate() { - return status_date; - } - - /** - * Set status_date. - * - * @param status_date the value to set. - */ - public void setStatusDate(String status_date) { - this.status_date = status_date; - } - - /** - * Get description. - * - * @return description as String. - */ - @Column(name = "description") - public String getDescription() { - return description; - } - - /** - * Set description. - * - * @param description the value to set. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Get kind. - * - * @return kind as HWSKind. - */ - @OneToOne - @JoinColumn(name = "kind_id") - public HWSKind getKind() { - return kind; - } - - /** - * Set kind. - * - * @param kind the value to set. - */ - public void setKind(HWSKind kind) { - this.kind = kind; - } - - /** - * Get fedState. - * - * @return fedState as FedState. - */ - @OneToOne - @JoinColumn(name = "fed_state_id") - public FedState getFedState() { - return fedState; - } - - /** - * Set fedState. - * - * @param fedState the value to set. - */ - public void setFedState(FedState fedState) { - this.fedState = fedState; - } - - /** - * Get river. - * - * @return river as River. - */ - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - /** - * Set river. - * - * @param river the value to set. - */ - public void setRiver(River river) { - this.river = river; - } - - public static List<HWSLine> getLines(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from HWSLine where river.id =:river_id and name=:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/HWSPoint.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,457 +0,0 @@ -package de.intevation.flys.model; - -import com.vividsolutions.jts.geom.Geometry; - -import java.io.Serializable; -import java.util.List; - -import java.math.BigDecimal; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.SequenceGenerator; - -import org.hibernate.annotations.Type; -import org.hibernate.Session; -import org.hibernate.Query; - -import de.intevation.flys.backend.SessionHolder; - -@Entity -@Table(name = "hws_points") -public class HWSPoint implements Serializable { - - private Integer id; - - private Integer ogrFid; - private HWSKind kind; - private FedState fedState; - private River river; - private Integer official; - private Integer shoreSide; - private String name; - private String path; - private String agency; - private String range; - private String source; - private String statusDate; - private String description; - private BigDecimal freeboard; - private BigDecimal dikeKm; - private BigDecimal z; - private BigDecimal zTarget; - private BigDecimal ratedLevel; - private Geometry geom; - - @Id - @SequenceGenerator( - name = "SEQUENCE_HWS_POINTS_ID_SEQ", - sequenceName = "HWS_POINTS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HWS_POINTS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Geometry getGeom() { - return geom; - } - - - public void setGeom(Geometry geom) { - this.geom = geom; - } - - /** - * Get ogrFid. - * - * @return ogrFid as Integer. - */ - @Column(name = "ogr_fid") - public Integer getOgrFid() { - return ogrFid; - } - - /** - * Set ogrFid. - * - * @param ogrFid the value to set. - */ - public void setOgrFid(Integer ogrFid) { - this.ogrFid = ogrFid; - } - - - /** - * Get official. - * - * @return official as Integer. - */ - @Column(name = "official") - public Integer getofficial() { - return official; - } - - /** - * Set official. - * - * @param official the value to set. - */ - public void setofficial(Integer official) { - this.official = official; - } - - /** - * Get shoreSide. - * - * @return shoreSide as Integer. - */ - @Column(name = "shore_side") - public Integer getShoreSide() { - return shoreSide; - } - - /** - * Set shoreSide. - * - * @param shoreSide the value to set. - */ - public void setShoreSide(Integer shoreSide) { - this.shoreSide = shoreSide; - } - - /** - * Get name. - * - * @return name as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Get path. - * - * @return path as String. - */ - @Column(name = "path") - public String getPath() { - return path; - } - - /** - * Set path. - * - * @param path the value to set. - */ - public void setPath(String path) { - this.path = path; - } - - /** - * Get agency. - * - * @return agency as String. - */ - @Column(name = "agency") - public String getAgency() { - return agency; - } - - /** - * Set agency. - * - * @param agency the value to set. - */ - public void setAgency(String agency) { - this.agency = agency; - } - - /** - * Get range. - * - * @return range as String. - */ - @Column(name = "range") - public String getRange() { - return range; - } - - /** - * Set range. - * - * @param range the value to set. - */ - public void setRange(String range) { - this.range = range; - } - - /** - * Get source. - * - * @return source as String. - */ - @Column(name = "source") - public String getSource() { - return source; - } - - /** - * Set source. - * - * @param source the value to set. - */ - public void setSource(String source) { - this.source = source; - } - - /** - * Get statusDate. - * - * @return statusDate as String. - */ - @Column(name = "status_date") - public String getStatusDate() { - return statusDate; - } - - /** - * Set statusDate. - * - * @param statusDate the value to set. - */ - public void setStatusDate(String statusDate) - { - this.statusDate = statusDate; - } - - /** - * Get description. - * - * @return description as String. - */ - @Column(name = "description") - public String getDescription() - { - return description; - } - - /** - * Set description. - * - * @param description the value to set. - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * Get freeboard. - * - * @return freeboard as BigDecimal. - */ - @Column(name = "freeboard") - public BigDecimal getFreeboard() - { - return freeboard; - } - - /** - * Set freeboard. - * - * @param freeboard the value to set. - */ - public void setFreeboard(BigDecimal freeboard) - { - this.freeboard = freeboard; - } - - /** - * Get dikeKm. - * - * @return dikeKm as BigDecimal. - */ - @Column(name = "dike_km") - public BigDecimal getDikeKm() - { - return dikeKm; - } - - /** - * Set dikeKm. - * - * @param dikeKm the value to set. - */ - public void setDikeKm(BigDecimal dikeKm) - { - this.dikeKm = dikeKm; - } - - /** - * Get z. - * - * @return z as BigDecimal. - */ - @Column(name = "z") - public BigDecimal getZ() - { - return z; - } - - /** - * Set z. - * - * @param z the value to set. - */ - public void setZ(BigDecimal z) - { - this.z = z; - } - - /** - * Get zTarget. - * - * @return zTarget as BigDecimal. - */ - @Column(name = "z_target") - public BigDecimal getZTarget() - { - return zTarget; - } - - /** - * Set zTarget. - * - * @param zTarget the value to set. - */ - public void setZTarget(BigDecimal zTarget) - { - this.zTarget = zTarget; - } - - /** - * Get ratedLevel. - * - * @return ratedLevel as BigDecimal. - */ - @Column(name = "rated_level") - public BigDecimal getRatedLevel() - { - return ratedLevel; - } - - /** - * Set ratedLevel. - * - * @param ratedLevel the value to set. - */ - public void setRatedLevel(BigDecimal ratedLevel) - { - this.ratedLevel = ratedLevel; - } - - /** - * Get kind. - * - * @return kind as HWSKind. - */ - @OneToOne - @JoinColumn(name = "kind_id") - public HWSKind getKind() - { - return kind; - } - - /** - * Set kind. - * - * @param kind the value to set. - */ - public void setKind(HWSKind kind) - { - this.kind = kind; - } - - /** - * Get fedState. - * - * @return fedState as FedState. - */ - @OneToOne - @JoinColumn(name = "fed_state_id") - public FedState getFedState() - { - return fedState; - } - - /** - * Set fedState. - * - * @param fedState the value to set. - */ - public void setFedState(FedState fedState) - { - this.fedState = fedState; - } - - /** - * Get river. - * - * @return river as River. - */ - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() - { - return river; - } - - /** - * Set river. - * - * @param river the value to set. - */ - public void setRiver(River river) - { - this.river = river; - } - - public static List<HWSPoint> getPoints(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from HWSPoint where river.id =:river_id and name=:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } -} -
--- a/flys-backend/src/main/java/de/intevation/flys/model/HYK.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,85 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "hyks") -public class HYK -implements Serializable -{ - private Integer id; - private River river; - private String description; - - private List<HYKEntry> entries; - - public HYK() { - } - - public HYK(River river, String description) { - this.river = river; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYKS_ID_SEQ", - sequenceName = "HYKS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYKS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @OrderBy("km") - @JoinColumn(name="hyk_id") - public List<HYKEntry> getEntries() { - return entries; - } - - public void setEntries(List<HYKEntry> entries) { - this.entries = entries; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HYKEntry.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,99 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.math.BigDecimal; - -import java.util.Date; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "hyk_entries") -public class HYKEntry -implements Serializable -{ - private Integer id; - private HYK hyk; - private BigDecimal km; - private Date measure; - - private List<HYKFormation> formations; - - public HYKEntry() { - } - - public HYKEntry(HYK hyk, BigDecimal km, Date measure) { - this.hyk = hyk; - this.km = km; - this.measure = measure; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYK_ENTRIES_ID_SEQ", - sequenceName = "HYK_ENTRIES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYK_ENTRIES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "hyk_id") - public HYK getHYK() { - return hyk; - } - - public void setHYK(HYK hyk) { - this.hyk = hyk; - } - - @Column(name = "km") - public BigDecimal getKm() { - return km; - } - - public void setKm(BigDecimal km) { - this.km = km; - } - - @Column(name = "measure") - public Date getMeasure() { - return measure; - } - - public void setMeasure(Date measure) { - this.measure = measure; - } - - @OneToMany - @OrderBy("formationNum") - @JoinColumn(name="hyk_entry_id") - public List<HYKFormation> getFormations() { - return formations; - } - - public void setFormations(List<HYKFormation> formations) { - this.formations = formations; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HYKFlowZone.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,98 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "hyk_flow_zones") -public class HYKFlowZone -implements Serializable -{ - private Integer id; - private HYKFormation formation; - private HYKFlowZoneType type; - private BigDecimal a; - private BigDecimal b; - - public HYKFlowZone() { - } - - public HYKFlowZone( - HYKFormation formation, - HYKFlowZoneType type, - BigDecimal a, - BigDecimal b - ) { - this.formation = formation; - this.type = type; - this.a = a; - this.b = b; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYK_FLOW_ZONES_ID_SEQ", - sequenceName = "HYK_FLOW_ZONES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYK_FLOW_ZONES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "formation_id") - public HYKFormation getFormation() { - return formation; - } - - public void setFormation(HYKFormation formation) { - this.formation = formation; - } - - @OneToOne - @JoinColumn(name = "type_id") - public HYKFlowZoneType getType() { - return type; - } - - public void setType(HYKFlowZoneType type) { - this.type = type; - } - - @Column(name = "a") - public BigDecimal getA() { - return a; - } - - public void setA(BigDecimal a) { - this.a = a; - } - - @Column(name = "b") - public BigDecimal getB() { - return b; - } - - public void setB(BigDecimal b) { - this.b = b; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HYKFlowZoneType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "hyk_flow_zone_types") -public class HYKFlowZoneType -implements Serializable -{ - private Integer id; - private String name; - private String description; - - public HYKFlowZoneType() { - } - - public HYKFlowZoneType(String name) { - this.name = name; - } - - public HYKFlowZoneType(String name, String description) { - this.name = name; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYK_FLOW_ZONE_TYPES_ID_SEQ", - sequenceName = "HYK_FLOW_ZONE_TYPES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYK_FLOW_ZONE_TYPES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HYKFormation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,151 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.List; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "hyk_formations") -public class HYKFormation -implements Serializable -{ - private Integer id; - private Integer formationNum; - private HYKEntry entry; - private BigDecimal top; - private BigDecimal bottom; - private BigDecimal distanceVL; - private BigDecimal distanceHF; - private BigDecimal distanceVR; - - private List<HYKFlowZone> zones; - - public HYKFormation() { - } - - public HYKFormation( - Integer formationNum, - HYKEntry entry, - BigDecimal top, - BigDecimal bottom, - BigDecimal distanceVL, - BigDecimal distanceHF, - BigDecimal distanceVR - ) { - this.formationNum = formationNum; - this.entry = entry; - this.top = top; - this.bottom = bottom; - this.distanceVL = distanceVL; - this.distanceHF = distanceHF; - this.distanceVR = distanceVR; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYK_FORMATIONS_ID_SEQ", - sequenceName = "HYK_FORMATIONS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYK_FORMATIONS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "formation_num") - public Integer getFormationNum() { - return formationNum; - } - - public void setFormationNum(Integer formationNum) { - this.formationNum = formationNum; - } - - @OneToOne - @JoinColumn(name = "hyk_entry_id") - public HYKEntry getEntry() { - return entry; - } - - public void setEntry(HYKEntry entry) { - this.entry = entry; - } - - @Column(name = "top") - public BigDecimal getTop() { - return top; - } - - public void setTop(BigDecimal top) { - this.top = top; - } - - @Column(name = "bottom") - public BigDecimal getBottom() { - return bottom; - } - - public void setBottom(BigDecimal bottom) { - this.bottom = bottom; - } - - @Column(name = "distance_vl") - public BigDecimal getDistanceVL() { - return distanceVL; - } - - public void setDistanceVL(BigDecimal distanceVL) { - this.distanceVL = distanceVL; - } - - @Column(name = "distance_hf") - public BigDecimal getDistanceHF() { - return distanceHF; - } - - public void setDistanceHF(BigDecimal distanceHF) { - this.distanceHF = distanceHF; - } - - @Column(name = "distance_vr") - public BigDecimal getDistanceVR() { - return distanceVR; - } - - public void setDistanceVR(BigDecimal distanceVR) { - this.distanceVR = distanceVR; - } - - - @OneToMany - @OrderBy("a") - @JoinColumn(name="formation_id") - public List<HYKFlowZone> getZones() { - return zones; - } - - public void setZones(List<HYKFlowZone> zones) { - this.zones = zones; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HydrBoundary.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,184 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.SequenceGenerator; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.MultiLineString; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "hydr_boundaries") -public class HydrBoundary -implements Serializable -{ - private Integer id; - private SectieKind sectie; - private SobekKind sobek; - private String name; - private River river; - private MultiLineString geom; - private BoundaryKind kind; - - public HydrBoundary() { - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYDR_BOUNDARIES_ID_SEQ", - sequenceName = "HYDR_BOUNDARIES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYDR_BOUNDARIES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public MultiLineString getGeom() { - return geom; - } - - - public void setGeom(MultiLineString geom) { - this.geom = geom; - } - - public static List<HydrBoundary> getHydrBoundaries(int riverId, String name, int kindId) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from HydrBoundary where river.id =:river_id and name=:name" + - " and kind.id=:kind_id"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - query.setParameter("kind_id", kindId); - - return query.list(); - } - - public static List<HydrBoundary> getHydrBoundaries(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from HydrBoundary where river.id =:river_id and name=:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } - - /** - * Get sectie. - * - * @return sectie as SectieKind. - */ - @OneToOne - @JoinColumn(name = "sectie") - public SectieKind getSectie() - { - return sectie; - } - - /** - * Set sectie. - * - * @param sectie the value to set. - */ - public void setSectie(SectieKind sectie) - { - this.sectie = sectie; - } - - /** - * Get sobek. - * - * @return sobek as SobekKind. - */ - @OneToOne - @JoinColumn(name = "sobek") - public SobekKind getSobek() - { - return sobek; - } - - /** - * Set sobek. - * - * @param sobek the value to set. - */ - public void setSobek(SobekKind sobek) - { - this.sobek = sobek; - } - - /** - * Get kind. - * - * @return kind as BoundaryKind. - */ - @OneToOne - @JoinColumn(name = "kind") - public BoundaryKind getKind() - { - return kind; - } - - /** - * Set kind. - * - * @param kind the value to set. - */ - public void setKind(BoundaryKind kind) - { - this.kind = kind; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/HydrBoundaryPoly.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,194 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.persistence.SequenceGenerator; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.Geometry; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "hydr_boundaries_poly") -public class HydrBoundaryPoly -implements Serializable -{ - private Integer id; - private String name; - private River river; - private Geometry geom; - private SectieKind sectie; - private SobekKind sobek; - private BoundaryKind kind; - - public HydrBoundaryPoly() { - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_HYDR_BOUNDARIES_POLY_ID_SEQ", - sequenceName = "HYDR_BOUNDARIES_POLY_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_HYDR_BOUNDARIES_POLY_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Geometry getGeom() { - return geom; - } - - - public void setGeom(Geometry geom) { - this.geom = geom; - } - - - public static List<HydrBoundaryPoly> getHydrBoundaries(int riverId, String name) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from HydrBoundaryPoly where river.id =:river_id and name=:name"); - query.setParameter("river_id", riverId); - query.setParameter("name", name); - - return query.list(); - } - - public static List<HydrBoundaryPoly> getHydrBoundaries(int riverId, - int kind, int sectie, int sobek) { - Session session = SessionHolder.HOLDER.get(); - - String filter = " where river.id =:river_id"; - - if (kind != -1) { - filter += " and kind = " + kind; - } - if (sectie != -1) { - filter += " and sectie = " + sectie; - } - if (sobek != -1){ - filter += " and sobek = " + sobek; - } - - Query query = session.createQuery("from HydrBoundaryPoly" + filter); - query.setParameter("river_id", riverId); - return query.list(); - } - - /** - * Get sectie. - * - * @return sectie as SectieKind. - */ - @OneToOne - @JoinColumn(name = "sectie") - public SectieKind getSectie() - { - return sectie; - } - - /** - * Set sectie. - * - * @param sectie the value to set. - */ - public void setSectie(SectieKind sectie) - { - this.sectie = sectie; - } - - /** - * Get sobek. - * - * @return sobek as SobekKind. - */ - @OneToOne - @JoinColumn(name = "sobek") - public SobekKind getSobek() - { - return sobek; - } - - /** - * Set sobek. - * - * @param sobek the value to set. - */ - public void setSobek(SobekKind sobek) - { - this.sobek = sobek; - } - - /** - * Get kind. - * - * @return kind as BoundaryKind. - */ - @OneToOne - @JoinColumn(name = "kind") - public BoundaryKind getKind() - { - return kind; - } - - /** - * Set kind. - * - * @param kind the value to set. - */ - public void setKind(BoundaryKind kind) - { - this.kind = kind; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Jetty.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,79 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import com.vividsolutions.jts.geom.Geometry; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import de.intevation.flys.backend.SessionHolder; - -@Entity -@Table(name = "jetties") -public class Jetty -implements Serializable -{ - private Integer id; - private River river; - private Geometry geom; - - public Jetty() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Geometry getGeom() { - return geom; - } - - - public void setGeom(Geometry geom) { - this.geom = geom; - } - - public static List<Jetty> getJetties(int riverId, int kindId) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Jetty where river.id =:river_id and kind_id=:kind_id"); - query.setParameter("kind_id", kindId); - query.setParameter("river_id", riverId); - - return query.list(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/LocationSystem.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - - -@Entity -@Table(name = "location_system") -public class LocationSystem implements Serializable { - - protected Integer id; - - protected String name; - protected String description; - - - public LocationSystem() { - } - - - public LocationSystem(String name, String description) { - this.name = name; - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_LOCATION_SYSTEM_ID_SEQ", - sequenceName = "LOCATION_SYSTEM_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_LOCATION_SYSTEM_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/MainValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,105 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; -import javax.persistence.GenerationType; - -import java.math.BigDecimal; - - -/** A Main or Extreme value of a rivers gauge. */ -@Entity -@Table(name = "main_values") -public class MainValue -implements Serializable -{ - private Integer id; - - private Gauge gauge; - - private NamedMainValue mainValue; - - private BigDecimal value; - - private TimeInterval timeInterval; - - public MainValue() { - } - - public MainValue( - Gauge gauge, - NamedMainValue mainValue, - BigDecimal value, - TimeInterval timeInterval - ) { - this.gauge = gauge; - this.mainValue = mainValue; - this.value = value; - this.timeInterval = timeInterval; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_MAIN_VALUES_ID_SEQ", - sequenceName = "MAIN_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_MAIN_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "gauge_id") - public Gauge getGauge() { - return gauge; - } - - public void setGauge(Gauge gauge) { - this.gauge = gauge; - } - - @OneToOne - @JoinColumn(name = "named_value_id") - public NamedMainValue getMainValue() { - return mainValue; - } - - public void setMainValue(NamedMainValue mainValue) { - this.mainValue = mainValue; - } - - @Column(name = "value") // FIXME: type mapping needed? - public BigDecimal getValue() { - return value; - } - - public void setValue(BigDecimal value) { - this.value = value; - } - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/MainValueType.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "main_value_types") -public class MainValueType -implements Serializable -{ - private Integer id; - private String name; - - public MainValueType() { - } - - public MainValueType(String name) { - this.name = name; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_MAIN_VALUE_TYPES_ID_SEQ", - sequenceName = "MAIN_VALUE_TYPES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_MAIN_VALUE_TYPES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") // FIXME: Type conversion needed? - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/MeasurementStation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,171 +0,0 @@ -package de.intevation.flys.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - - -@Entity -@Table(name = "measurement_station") -public class MeasurementStation { - - private Integer id; - - private String name; - private String measurementType; - private String riverside; - private String operator; - private String description; - - private Double station; - private Range range; - - private River river; - - private Gauge gauge; - private String gaugeName; - - private TimeInterval observationTimerange; - - public MeasurementStation() { - } - - public MeasurementStation(River river, String name, String measurementType, - String riverside, Double station, Range range, Gauge gauge, - String gaugeName, TimeInterval observationTimerange, String operator, - String description - ) { - this.river = river; - this.name = name; - this.measurementType = measurementType; - this.riverside = riverside; - this.station = station; - this.range = range; - this.gauge = gauge; - this.gaugeName = gaugeName; - this.observationTimerange = observationTimerange; - this.operator = operator; - this.description = description; - } - - @Id - @SequenceGenerator(name = "SEQ_MEASUREMENT_STATION_ID_SEQ", sequenceName = "MEASUREMENT_STATION_ID_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_MEASUREMENT_STATION_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "measurement_type") - public String getMeasurementType() { - return measurementType; - } - - public void setMeasurementType(String measurementType) { - this.measurementType = measurementType; - } - - @Column(name = "riverside") - public String getRiverside() { - return riverside; - } - - public void setRiverside(String riverside) { - this.riverside = riverside; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "reference_gauge_id") - public Gauge getGauge() { - return gauge; - } - - public void setGauge(Gauge gauge) { - this.gauge = gauge; - } - - @Column(name = "reference_gauge_name") - public String getGaugeName() { - return gaugeName; - } - - public void setGaugeName(String gaugeName) { - this.gaugeName = gaugeName; - } - - @Column(name = "station") - public Double getStation() { - return station; - } - - public void setStation(Double station) { - this.station = station; - } - - @OneToOne - @JoinColumn(name = "range_id") - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @OneToOne - @JoinColumn(name = "observation_timerange_id") - public TimeInterval getObservationTimerange() { - return observationTimerange; - } - - public void setObservationTimerange(TimeInterval observationTimerange) { - this.observationTimerange = observationTimerange; - } - - @Column(name = "operator") - public String getOperator() { - return operator; - } - - public void setOperator(String operator) { - this.operator = operator; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/MinMaxWQ.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; - -/** - * Represents minmimum and maximum values for W and Q - */ -public class MinMaxWQ implements Serializable { - - private BigDecimal minw; - private BigDecimal maxw; - private BigDecimal minq; - private BigDecimal maxq; - - /** - * Default constuctor to indecate that no min and max w and q values - * are available - */ - public MinMaxWQ() { - } - - /** - * Constructor for a new MinMaxWQ value - * - * @param minw Mimimim W - * @param maxw Maximum W - * @param minq Mimimim Q - * @param maxq Maximum Q - */ - public MinMaxWQ( - BigDecimal minw, - BigDecimal maxw, - BigDecimal minq, - BigDecimal maxq) - { - this.minw = minw; - this.maxw = maxw; - this.minq = minq; - this.maxq = maxq; - } - - public BigDecimal getMinW() { - return this.minw; - } - - public BigDecimal getMaxW() { - return this.maxw; - } - - public BigDecimal getMinQ() { - return this.minq; - } - - public BigDecimal getMaxQ() { - return this.maxq; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/MorphologicalWidth.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,88 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - - -@Entity -@Table(name = "morphologic_width") -public class MorphologicalWidth implements Serializable { - - private Integer id; - - private River river; - - private Unit unit; - - private List<MorphologicalWidthValue> values; - - - public MorphologicalWidth() { - } - - - public MorphologicalWidth(River river, Unit unit) { - this.river = river; - this.unit = unit; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_MORPHOLOGIC_WIDTH_ID_SEQ", - sequenceName = "MORPHOLOGIC_WIDTH_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_MORPHOLOGIC_WIDTH_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "unit_id") - public Unit getUnit() { - return unit; - } - - public void setUnit(Unit unit) { - this.unit = unit; - } - - @OneToMany - @JoinColumn(name = "morphologic_width_id") - public List<MorphologicalWidthValue> getValues() { - return values; - } - - public void setValues(List<MorphologicalWidthValue> values) { - this.values = values; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/MorphologicalWidthValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,103 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - - -@Entity -@Table(name = "morphologic_width_values") -public class MorphologicalWidthValue implements Serializable { - - private Integer id; - - private MorphologicalWidth morphologicalWidth; - - private BigDecimal station; - private BigDecimal width; - - private String description; - - - public MorphologicalWidthValue() { - } - - - public MorphologicalWidthValue( - MorphologicalWidth morphologicalWidth, - BigDecimal station, - BigDecimal width, - String description - ) { - this.morphologicalWidth = morphologicalWidth; - this.station = station; - this.width = width; - this.description = description; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_MORPH_WIDTH_VALUES_ID_SEQ", - sequenceName = "MORPH_WIDTH_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_MORPH_WIDTH_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "morphologic_width_id") - public MorphologicalWidth getMorphologicalWidth() { - return morphologicalWidth; - } - - public void setMorphologicalWidth(MorphologicalWidth width) { - this.morphologicalWidth = width; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "width") - public BigDecimal getWidth() { - return width; - } - - public void setWidth(BigDecimal width) { - this.width = width; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/NamedMainValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "named_main_values") -public class NamedMainValue -implements Serializable -{ - private Integer id; - private String name; - private MainValueType type; - - public NamedMainValue() { - } - - public NamedMainValue(String name, MainValueType type) { - this.name = name; - this.type = type; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_NAMED_MAIN_VALUES_ID_SEQ", - sequenceName = "NAMED_MAIN_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_NAMED_MAIN_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @OneToOne - @JoinColumn(name = "type_id" ) - public MainValueType getType() { - return type; - } - - public void setType(MainValueType type) { - this.type = type; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Position.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,71 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.OneToMany; -import javax.persistence.JoinColumn; -import javax.persistence.GenerationType; - -import java.util.List; - -@Entity -@Table(name = "positions") -public class Position -implements Serializable -{ - private Integer id; - - private String value; - - private List<Annotation> annotations; - - public Position() { - } - - public Position(String value) { - this.value = value; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_POSITIONS_ID_SEQ", - sequenceName = "POSITIONS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_POSITIONS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "value") - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @OneToMany - @JoinColumn(name="position_id") - public List<Annotation> getAnnotations() { - return annotations; - } - - public void setAnnotations(List<Annotation> annotations) { - this.annotations = annotations; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Range.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,173 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -@Entity -@Table(name = "ranges") -public class Range -implements Serializable -{ - public static final double EPSILON = 1e-5; - private Integer id; - private BigDecimal a; - private BigDecimal b; - - private River river; - - public Range() { - } - - public Range(double a, double b, River river) { - this(new BigDecimal(a), new BigDecimal(b), river); - } - - public Range(BigDecimal a, BigDecimal b, River river) { - this.a = a; - this.b = b; - this.river = river; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_RANGES_ID_SEQ", - sequenceName = "RANGES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_RANGES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "a") // FIXME: type mapping needed? - public BigDecimal getA() { - return a; - } - - public void setA(BigDecimal a) { - this.a = a; - } - - @Column(name = "b") // FIXME: type mapping needed? - public BigDecimal getB() { - return b; - } - - public void setB(BigDecimal b) { - this.b = b; - } - - public boolean containsTolerant(double x) { - return containsTolerant(x, EPSILON); - } - - public boolean containsTolerant(double x, double tolerance) { - BigDecimal b = this.b != null ? this.b : a; - double av = a.doubleValue(); - double bv = b.doubleValue(); - if (av > bv) { - double t = av; - av = bv; - bv = t; - } - return x+tolerance >= av && x-tolerance <= bv; - } - - public boolean contains(double x) { - BigDecimal b = this.b != null ? this.b : a; - double av = a.doubleValue(); - double bv = b.doubleValue(); - if (av > bv) { - double t = av; - av = bv; - bv = t; - } - return x >= av && x <= bv; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - public int code() { - int code = 0; - if (a != null) code = 1; - if (b != null) code |= 2; - return code; - } - - public boolean intersects(BigDecimal c) { - return !(a.compareTo(c) > 0 || b.compareTo(c) < 0); - } - - public boolean intersects(Range other) { - - int code = code(); - int ocode = other.code(); - - if (code == 0 || ocode == 0) { - return false; - } - - switch (code) { - case 1: // has a - switch (ocode) { - case 1: // has a - return a.compareTo(other.a) == 0; - case 2: // has b - return a.compareTo(other.b) == 0; - case 3: // has range - return other.intersects(a); - } - break; - case 2: // has b - switch (ocode) { - case 1: // has a - return b.compareTo(other.a) == 0; - case 2: // has b - return b.compareTo(other.b) == 0; - case 3: // has range - return other.intersects(b); - } - break; - case 3: // has range - switch (ocode) { - case 1: // has a - return intersects(other.a); - case 2: // has b - return intersects(other.b); - case 3: // has range - return !(other.b.compareTo(a) < 0 - ||other.a.compareTo(b) > 0); - } - break; - - } - - return false; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/River.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,345 +0,0 @@ -package de.intevation.flys.model; - -import de.intevation.flys.backend.SessionHolder; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.MathContext; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - -import org.hibernate.Query; -import org.hibernate.Session; - - -@Entity -@Table(name = "rivers") -public class River -implements Serializable -{ - public static final MathContext PRECISION = new MathContext(6); - - public static final double EPSILON = 1e-5; - - public static final Comparator<Double> KM_CMP = new Comparator<Double>() { - @Override - public int compare(Double a, Double b) { - double diff = a - b; - if (diff < -EPSILON) return -1; - if (diff > EPSILON) return +1; - return 0; - } - }; - - private Integer id; - - private Long officialNumber; - - private String name; - - private boolean kmUp; - - private List<Gauge> gauges; - - private List<MeasurementStation> measurementstations; - - private Unit wstUnit; - - @Id - @SequenceGenerator( - name = "SEQUENCE_RIVERS_ID_SEQ", - sequenceName = "RIVERS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_RIVERS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "official_number") - public Long getOfficialNumber() { - return officialNumber; - } - - public void setOfficialNumber(Long officialNumber) { - this.officialNumber = officialNumber; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "km_up") - public boolean getKmUp() { - return kmUp; - } - - public void setKmUp(boolean kmUp) { - this.kmUp = kmUp; - } - - public River() { - } - - public River(String name, Unit wstUnit) { - this.name = name; - this.wstUnit = wstUnit; - } - - @OneToMany - @JoinColumn(name="river_id") - public List<Gauge> getGauges() { - return gauges; - } - - public void setGauges(List<Gauge> gauges) { - this.gauges = gauges; - } - - - @OneToMany - @OrderBy("station") - @JoinColumn(name="river_id") - public List<MeasurementStation> getMeasurementStations() { - return measurementstations; - } - - public void setMeasurementStations(List<MeasurementStation> mstations) { - this.measurementstations = mstations; - } - - @OneToOne - @JoinColumn(name = "wst_unit_id" ) - public Unit getWstUnit() { - return wstUnit; - } - - public void setWstUnit(Unit wstUnit) { - this.wstUnit = wstUnit; - } - - - - @Override - public String toString() { - return name != null ? name : ""; - } - - - /** - * This method returns the gauges that intersect with <i>a</i> and - * <i>b</i>, - * - * @param a A start point. - * @param b An end point. - * - * @return the intersecting gauges. - */ - public List<Gauge> determineGauges(double a, double b) { - Session session = SessionHolder.HOLDER.get(); - - if (a > b) { double t = a; a = b; b = t; } - - Query query = session.createQuery( - "from Gauge where river=:river " + - "and not (range.a > :b or range.b < :a) order by a"); - query.setParameter("river", this); - query.setParameter("a", new BigDecimal(a, PRECISION)); - query.setParameter("b", new BigDecimal(b, PRECISION)); - - return query.list(); - } - - public Gauge maxOverlap(double a, double b) { - List<Gauge> gauges = determineGauges(a, b); - if (gauges == null) { - return null; - } - - if (a > b) { double t = a; a = b; b = t; } - - double max = -Double.MAX_VALUE; - - Gauge result = null; - - for (Gauge gauge: gauges) { - Range r = gauge.getRange(); - double c = r.getA().doubleValue(); - double d = r.getB().doubleValue(); - - double start = c >= a ? c : a; - double stop = d <= b ? d : b; - - double length = stop - start; - - if (length > max) { - max = length; - result = gauge; - } - } - - return result; - } - - public Gauge determineGaugeByName(String name) { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from Gauge where river=:river and name=:name"); - query.setParameter("river", this); - query.setParameter("name", name); - List<Gauge> gauges = query.list(); - return gauges.isEmpty() ? null : gauges.get(0); - } - - public Gauge determineGaugeByPosition(double p) { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from Gauge g where river=:river " + - "and :p between g.range.a and g.range.b"); - query.setParameter("river", this); - query.setParameter("p", new BigDecimal(p, PRECISION)); - List<Gauge> gauges = query.list(); - return gauges.isEmpty() ? null : gauges.get(0); - } - - public Gauge determineGaugeByStation(double a, double b) { - - if (a > b) { double t = a; a = b; b = t; } - - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from Gauge where river.id=:river " + - "and station between :a and :b"); - query.setParameter("river", getId()); - query.setParameter("a", new BigDecimal(a)); - query.setParameter("b", new BigDecimal(b)); - - List<Gauge> gauges = query.list(); - return gauges.isEmpty() ? null : gauges.get(0); - } - - public double[] determineMinMaxQ() { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "select min(wqr.q) as min, max(wqr.q) as max " + - "from Wst as w " + - "join w.columns as wc " + - "join wc.columnQRanges as wcqr " + - "join wcqr.wstQRange as wqr " + - "where w.kind = 0 and river_id = :river"); - - query.setParameter("river", getId()); - - double minmax[] = new double[] { Double.MAX_VALUE, Double.MIN_VALUE }; - - List<Object> results = query.list(); - - if (!results.isEmpty()) { - Object[] arr = (Object[]) results.get(0); - BigDecimal minq = (BigDecimal)arr[0]; - BigDecimal maxq = (BigDecimal)arr[1]; - minmax[0] = minq.doubleValue(); - minmax[1] = maxq.doubleValue(); - } - - return minmax; - } - - - /** - * This method returns the first gauge that is intersected by <i>a</i> and - * <i>b</i>, - * - * @param a A start point. - * @param b An end point. - * - * @return the first intersecting gauge. - */ - public Gauge determineGauge(double a, double b) { - List<Gauge> gauges = determineGauges(a, b); - - int idx = a < b ? 0 : gauges.size() - 1; - - return gauges.isEmpty() ? null : gauges.get(idx); - } - - /** - * Returns the min and max distance of this river. The first position in the - * resulting array contains the min distance, the second position the max - * distance. - * - * @return the min and max distance of this river. - */ - public double[] determineMinMaxDistance() { - List<Gauge> gauges = getGauges(); - - if (gauges == null || gauges.isEmpty()) { - return null; - } - - double minmax[] = new double[] { Double.MAX_VALUE, Double.MIN_VALUE }; - - for (Gauge g: gauges) { - Range r = g.getRange(); - - if (r == null) { - continue; - } - - double a = r.getA().doubleValue(); - minmax[0] = minmax[0] < a ? minmax[0] : a; - - BigDecimal bigB = r.getB(); - if (bigB != null) { - double b = bigB.doubleValue(); - minmax[1] = minmax[1] > b ? minmax[1] : b; - } - } - - return minmax; - } - - public Map<Double, Double> queryGaugeDatumsKMs() { - List<Gauge> gauges = getGauges(); - Map result = new TreeMap<Double, Double>(KM_CMP); - - for (Gauge gauge: gauges) { - BigDecimal km = gauge.getStation(); - BigDecimal datum = gauge.getDatum(); - if (km != null && datum != null) { - result.put(km.doubleValue(), datum.doubleValue()); - } - } - - return result; - } - -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/RiverAxis.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,146 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.MultiLineString; - -import de.intevation.flys.backend.SessionHolder; -import de.intevation.flys.model.AxisKind; - - -/** - * A river has one axis that is used for calculation. - * Additional axes of a river can be used to be painted int maps etc. - * which one is the main river axis can be determined over the axis kind. - */ -@Entity -@Table(name = "river_axes") -public class RiverAxis -implements Serializable -{ - private Integer id; - private AxisKind kind; - private River river; - private String name; - private MultiLineString geom; - - public static final int KIND_UNKOWN = 0; - public static final int KIND_CURRENT = 1; - public static final int KIND_OTHER = 2; - - public RiverAxis() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - /** - * Get kind. - * - * @return kind as AxisKind. - */ - @OneToOne - @JoinColumn(name = "kind_id") - public AxisKind getKind() { - return kind; - } - - /** - * Set kind. - * - * @param kind the value to set. - */ - public void setKind(AxisKind kind) { - this.kind = kind; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public MultiLineString getGeom() { - return geom; - } - - - public void setGeom(MultiLineString geom) { - this.geom = geom; - } - - - public static List<RiverAxis> getRiverAxis(String river) - throws IllegalArgumentException { - return getRiverAxis(river, KIND_CURRENT); - } - - public static List<RiverAxis> getRiverAxis(String river, String name, int kind) - throws HibernateException { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from RiverAxis as ax where river.name =:river" + - " and kind.id =:kind" + - " and ax.name=:name"); - query.setParameter("river", river); - query.setParameter("kind", kind); - query.setParameter("name", name); - - List<RiverAxis> list = query.list(); - return list.isEmpty() ? null : list; - } - - public static List<RiverAxis> getRiverAxis(String river, int kind) - throws HibernateException { - Session session = SessionHolder.HOLDER.get(); - Query query = session.createQuery( - "from RiverAxis where river.name =:river AND kind.id =:kind"); - query.setParameter("river", river); - query.setParameter("kind", kind); - - List<RiverAxis> list = query.list(); - return list.isEmpty() ? null : list; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/RiverAxisKm.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,104 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.hibernate.Session; -import org.hibernate.Query; -import org.hibernate.annotations.Type; - -import com.vividsolutions.jts.geom.Point; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "river_axes_km") -public class RiverAxisKm -implements Serializable -{ - private Integer id; - private River river; - private BigDecimal km; - private Point geom; - - - public RiverAxisKm() { - } - - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "km") - public BigDecimal getKm() { - return km; - } - - - public void setKm(BigDecimal km) { - this.km = km; - } - - - @Column(name = "geom") - @Type(type = "org.hibernatespatial.GeometryUserType") - public Point getGeom() { - return geom; - } - - - public void setGeom(Point geom) { - this.geom = geom; - } - - - /** - * Returns a list of RiverAxisKm objects for a given river. - * - * @param riverid The ID of a river in the database. - * - * @return a list of RiverAxisKm objects. - */ - public static List<RiverAxisKm> getRiverAxisKms(int riverid) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "from RiverAxisKm where river.id =:riverid"); - query.setParameter("riverid", riverid); - - List<RiverAxisKm> list = query.list(); - - return list; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SQRelation.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,105 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; -import javax.persistence.GenerationType; - - -@Entity -@Table(name = "sq_relation") -public class SQRelation implements Serializable { - - private Integer id; - - private River river; - - private TimeInterval timeInterval; - - private String description; - - private List<SQRelationValue> values; - - - protected SQRelation() { - } - - - public SQRelation(River river, TimeInterval timeInterval, String desc) { - this.river = river; - this.timeInterval = timeInterval; - this.description = desc; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_SQ_ID_SEQ", - sequenceName = "SQ_RELATION_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SQ_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - - @OneToMany - @JoinColumn(name = "sq_relation_id") - public List<SQRelationValue> getValues() { - return values; - } - - public void setValues(List<SQRelationValue> values) { - this.values = values; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SQRelationValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,191 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.JoinColumn; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.OneToOne; -import javax.persistence.GenerationType; - - -@Entity -@Table(name = "sq_relation_value") -public class SQRelationValue implements Serializable { - - private Integer id; - - private SQRelation sqRelation; - - private String parameter; - - private MeasurementStation measurementStation; - - private Double a; - private Double b; - private Double qMax; - private Double rSQ; - private Integer nTot; - private Integer nOutlier; - private Double cFerguson; - private Double cDuan; - - - protected SQRelationValue() { - } - - - public SQRelationValue( - SQRelation sqRelation, - String parameter, - MeasurementStation measurementStation, - Double a, - Double b, - Double qMax, - Double rSQ, - Integer nTot, - Integer nOutlier, - Double cFerguson, - Double cDuan - ) { - this.sqRelation = sqRelation; - this.parameter = parameter; - this.measurementStation = measurementStation; - this.a = a; - this.b = b; - this.qMax = qMax; - this.rSQ = rSQ; - this.nTot = nTot; - this.nOutlier = nOutlier; - this.cFerguson = cFerguson; - this.cDuan = cDuan; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_SQ_VALUE_ID_SEQ", - sequenceName = "SQ_RELATION_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SQ_VALUE_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - @OneToOne - @JoinColumn(name = "sq_relation_id") - public SQRelation getSqRelation() { - return sqRelation; - } - - public void setSqRelation(SQRelation sqRelation) { - this.sqRelation = sqRelation; - } - - - @Column(name = "parameter") - public String getParameter() { - return parameter; - } - - public void setParameter(String parameter) { - this.parameter = parameter; - } - - @OneToOne - @JoinColumn(name = "measurement_station_id") - public MeasurementStation getMeasurementStation() { - return measurementStation; - } - - public void setMeasurementStation(MeasurementStation measurementStation) { - this.measurementStation = measurementStation; - } - - - @Column(name = "a") - public Double getA() { - return a; - } - - public void setA(Double a) { - this.a = a; - } - - - @Column(name = "b") - public Double getB() { - return b; - } - - public void setB(Double b) { - this.b = b; - } - - @Column(name = "qmax") - public Double getQMax() { - return qMax; - } - - public void setQMax(Double qMax) { - this.qMax = qMax; - } - - @Column(name = "rsq") - public Double getRSQ() { - return rSQ; - } - - public void setRSQ(Double rSQ) { - this.rSQ = rSQ; - } - - @Column(name = "ntot") - public Integer getNTot () { - return nTot; - } - - public void setNTot(Integer nTot) { - this.nTot = nTot; - } - - @Column(name = "noutl") - public Integer getNOutlier() { - return nOutlier; - } - - public void setNOutlier(Integer nOutlier) { - this.nOutlier = nOutlier; - } - - @Column(name = "cferguson") - public Double getCFerguson() { - return cFerguson; - } - - public void setCFerguson(Double cFerguson) { - this.cFerguson = cFerguson; - } - - @Column(name = "cduan") - public Double getCDuan() { - return cDuan; - } - - public void setCDuan(Double cDuan) { - this.cDuan = cDuan; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SectieKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "sectie_kinds") -public class SectieKind implements Serializable { - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return name of the kind of sectie as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/SedimentDensity.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,103 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - - -@Entity -@Table(name = "sediment_density") -public class SedimentDensity implements Serializable { - - private Integer id; - - private River river; - - private Depth depth; - - private List<SedimentDensityValue> values; - - private String description; - - - public SedimentDensity() { - } - - - public SedimentDensity(River river, Depth depth, String desc) { - this.river = river; - this.depth = depth; - this.description = desc; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_SEDIMENT_DENSITY_ID_SEQ", - sequenceName = "SEDIMENT_DENSITY_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SEDIMENT_DENSITY_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name = "depth_id") - public Depth getDepth() { - return depth; - } - - public void setDepth(Depth depth) { - this.depth = depth; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @OneToMany - @JoinColumn(name="sediment_density_id") - public List<SedimentDensityValue> getValues() { - return values; - } - - public void setValues(List<SedimentDensityValue> values) { - this.values = values; - } - - public void addValue(SedimentDensityValue value) { - this.values.add(value); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SedimentDensityValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - - -@Entity -@Table(name = "sediment_density_values") -public class SedimentDensityValue implements Serializable { - - private Integer id; - - private SedimentDensity sedimentDensity; - - private BigDecimal station; - private BigDecimal shoreOffset; - private BigDecimal density; - private BigDecimal year; - - private String description; - - - public SedimentDensityValue() { - } - - - public SedimentDensityValue( - SedimentDensity sedimentDensity, - BigDecimal station, - BigDecimal shoreOffset, - BigDecimal density, - BigDecimal year, - String desc - ) { - this.sedimentDensity = sedimentDensity; - this.station = station; - this.shoreOffset = shoreOffset; - this.density = density; - this.year = year; - this.description = desc; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_SEDIMENT_DENSITY_VALUES_ID_SEQ", - sequenceName = "SEDIMENT_DENSITY_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SEDIMENT_DENSITY_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "sediment_density_id") - public SedimentDensity getSedimentDensity() { - return sedimentDensity; - } - - public void setSedimentDensity(SedimentDensity sedimentDensity) { - this.sedimentDensity = sedimentDensity; - } - - @Column(name = "station") - public BigDecimal getStation() { - return station; - } - - public void setStation(BigDecimal station) { - this.station = station; - } - - @Column(name = "shore_offset") - public BigDecimal getShoreOffset() { - return shoreOffset; - } - - public void setShoreOffset(BigDecimal shoreOffset) { - this.shoreOffset = shoreOffset; - } - - @Column(name = "density") - public BigDecimal getDensity() { - return density; - } - - public void setDensity(BigDecimal density) { - this.density = density; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Column(name = "year") - public BigDecimal getYear() { - return year; - } - - public void setYear(BigDecimal year) { - this.year = year; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SedimentYield.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,145 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - - -@Entity -@Table(name = "sediment_yield") -public class SedimentYield -implements Serializable -{ - private static Logger logger = Logger.getLogger(SedimentYield.class); - - private Integer id; - - private River river; - - private GrainFraction grainFraction; - - private Unit unit; - - private TimeInterval timeInterval; - - private String description; - - private List<SedimentYieldValue> values; - - - public SedimentYield() { - this.values = new ArrayList<SedimentYieldValue>(); - } - - public SedimentYield(River river, Unit unit, TimeInterval timeInterval) { - this(); - - this.river = river; - this.unit = unit; - this.timeInterval = timeInterval; - } - - - public SedimentYield( - River river, - Unit unit, - TimeInterval timeInterval, - GrainFraction grainFraction - ) { - this(river, unit, timeInterval); - - this.grainFraction = grainFraction; - } - - - public SedimentYield( - River river, - Unit unit, - TimeInterval timeInterval, - GrainFraction grainFraction, - String description - ) { - this(river, unit, timeInterval, grainFraction); - - this.description = description; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_SEDIMENT_YIELD_ID_SEQ", - sequenceName = "SEDIMENT_YIELD_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SEDIMENT_YIELD_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id") - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @OneToOne - @JoinColumn(name="grain_fraction_id") - public GrainFraction getGrainFraction() { - return grainFraction; - } - - public void setGrainFraction(GrainFraction grainFraction) { - this.grainFraction = grainFraction; - } - - @OneToOne - @JoinColumn(name = "unit_id") - public Unit getUnit() { - return unit; - } - - public void setUnit(Unit unit) { - this.unit = unit; - } - - @OneToOne - @JoinColumn(name = "time_interval_id") - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SedimentYieldValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; - -import org.apache.log4j.Logger; - - -@Entity -@Table(name = "sediment_yield_values") -public class SedimentYieldValue -implements Serializable -{ - private static Logger logger = Logger.getLogger(SedimentYieldValue.class); - - private Integer id; - - private SedimentYield sedimentYield; - - private Double station; - private Double value; - - private Unit unit; - - - public SedimentYieldValue() { - } - - public SedimentYieldValue( - SedimentYield sedimentYield, - Double station, - Double value - ) { - this.sedimentYield = sedimentYield; - this.station = station; - this.value = value; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_SEDIMENT_YIELD_VALuES_ID_SEQ", - sequenceName = "SEDIMENT_YIELD_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_SEDIMENT_YIELD_VALuES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "sediment_yield_id" ) - public SedimentYield getSedimentYield() { - return sedimentYield; - } - - public void setSedimentYield(SedimentYield sedimentYield) { - this.sedimentYield = sedimentYield; - } - - @Column(name="station") - public Double getStation() { - return station; - } - - public void setStation(Double station) { - this.station = station; - } - - @Column(name = "value") - public Double getValue() { - return value; - } - - public void setValue(Double value) { - this.value = value; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/SobekKind.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "sobek_kinds") -public class SobekKind implements Serializable { - - private Integer id; - private String name; - - @Id - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - /** - * Get name. - * - * @return name of the kind of sobek as String. - */ - @Column(name = "name") - public String getName() { - return name; - } - - /** - * Set name. - * - * @param name the value to set. - */ - public void setName(String name) { - this.name = name; - } -}
--- a/flys-backend/src/main/java/de/intevation/flys/model/TimeInterval.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; - -@Entity -@Table(name = "time_intervals") -public class TimeInterval -implements Serializable -{ - private Integer id; - private Date startTime; - private Date stopTime; - - public TimeInterval() { - } - - public TimeInterval(Date startTime, Date stopTime) { - this.startTime = startTime; - this.stopTime = stopTime; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_TIME_INTERVALS_ID_SEQ", - sequenceName = "TIME_INTERVALS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_TIME_INTERVALS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @Column(name = "start_time") // FIXME: type mapping needed? - public Date getStartTime() { - return startTime; - } - - public void setStartTime(Date startTime) { - this.startTime = startTime; - } - - @Column(name = "stop_time") // FIXME: type mapping needed? - public Date getStopTime() { - return stopTime; - } - - public void setStopTime(Date stopTime) { - this.stopTime = stopTime; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Unit.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - - -@Entity -@Table(name = "units") -public class Unit -implements Serializable -{ - protected Integer id; - protected String name; - - - public Unit() { - } - - - public Unit(String name) { - this.name = name; - } - - - @Id - @SequenceGenerator( - name = "SEQUENCE_UNITS_ID_SEQ", - sequenceName = "UNITS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_UNITS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - @Column(name = "name") - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/Wst.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,215 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -import org.apache.log4j.Logger; - -import org.hibernate.Session; -import org.hibernate.SQLQuery; -import org.hibernate.Query; -import org.hibernate.type.StandardBasicTypes; - -import de.intevation.flys.backend.SessionHolder; - - -@Entity -@Table(name = "wsts") -public class Wst -implements Serializable -{ - private static Logger logger = Logger.getLogger(Wst.class); - - private Integer id; - private River river; - private String description; - private Integer kind; - - private List<WstColumn> columns; - - - public static final String SQL_SELECT_MINMAX = - "select min(q) as minQ, max(q) as maxQ from wst_q_values " + - "where wst_id = :wst and not (a > :km or b < :km)"; - - public Wst() { - } - - public Wst(River river, String description) { - this(river, description, 0); - } - - public Wst(River river, String description, Integer kind) { - this.river = river; - this.description = description; - this.kind = kind; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_WSTS_ID_SEQ", - sequenceName = "WSTS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_WSTS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "river_id" ) - public River getRiver() { - return river; - } - - public void setRiver(River river) { - this.river = river; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Column(name = "kind") - public Integer getKind() { - return kind; - } - - public void setKind(Integer kind) { - this.kind = kind; - } - - @OneToMany - @JoinColumn(name="wst_id") - public List<WstColumn> getColumns() { - return columns; - } - - public void setColumns(List<WstColumn> columns) { - this.columns = columns; - } - - - /** - * Determines the min and max Q values of this WST. The min value is placed - * in the first field of the resulting array - the max value is placed in - * the second field. - * - * @return the min and max Q values of this WST. - */ - public double[] determineMinMaxQ() { - double[] ab = river.determineMinMaxDistance(); - return determineMinMaxQ(new Range(ab[0], ab[1], river)); - } - - - /** - * Determines the min and max Q values of this WST in the given range. The - * min value is placed in the first field of the resulting array - the max - * value is placed in the second field. - * - * @param range The range used for querying the Q values. - * - * @return the min and max Q values of this WST. - */ - public double[] determineMinMaxQ(Range range) { - if (range != null) { - return determineMinMaxQ( - range.getA().doubleValue(), - range.getB().doubleValue()); - } - - return null; - } - - - /** - * Determines the min and max Q values of this WST in the given range. The - * min value is placed in the first field of the resulting array - the max - * value is placed in the second field. - * - * @param fromKm the lower km value. - * @param toKm the upper km value. - * - * @return the min and max Q values of this WST. - */ - public double[] determineMinMaxQ(double fromKm, double toKm) { - Session session = SessionHolder.HOLDER.get(); - - Query query = session.createQuery( - "select min(q), max(q) from WstQRange where " + - " id in " + - " (select wstQRange.id from WstColumnQRange where " + - " wstColumn.id in (select id from WstColumn where wst.id = :wst)) " + - " and range.id in " + - " (select id from Range where not (a > :end or b < :start))"); - - query.setParameter("wst", getId()); - query.setParameter("start", new BigDecimal(fromKm)); - query.setParameter("end", new BigDecimal(toKm)); - - List<Object []> results = query.list(); - - if (results.isEmpty()) { - return null; - } - - Object [] result = results.get(0); - - return new double [] { - ((BigDecimal)result[0]).doubleValue(), - ((BigDecimal)result[1]).doubleValue() }; - } - - - public double[] determineMinMaxQFree(double km) { - Session session = SessionHolder.HOLDER.get(); - - SQLQuery sqlQuery = session.createSQLQuery(SQL_SELECT_MINMAX) - .addScalar("minQ", StandardBasicTypes.DOUBLE) - .addScalar("maxQ", StandardBasicTypes.DOUBLE); - - sqlQuery.setInteger("wst", getId()); - sqlQuery.setDouble("km", km); - - List<Object[]> minmaxQ = sqlQuery.list(); - - - if (minmaxQ.isEmpty()) { - return null; - } - - Object[] mm = minmaxQ.get(0); - - if (mm[0] == null || mm[1] == null) { - logger.warn ("No min/max Q for km " + km + " found."); - return null; - } - - return new double[] { (Double) mm[0], (Double) mm[1] }; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/WstColumn.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,134 +0,0 @@ -package de.intevation.flys.model; - -import java.util.List; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import javax.persistence.OneToMany; - -@Entity -@Table(name = "wst_columns") -public class WstColumn -implements Serializable -{ - private Integer id; - private Wst wst; - private String name; - private String description; - private Integer position; - private TimeInterval timeInterval; - - private List<WstColumnQRange> columnQRanges; - private List<WstColumnValue> columnValues; - - public WstColumn() { - } - - public WstColumn( - Wst wst, - String name, - String description, - Integer position, - TimeInterval timeInterval - ) { - this.wst = wst; - this.name = name; - this.description = description; - this.position = position; - this.timeInterval = timeInterval; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_WST_COLUMNS_ID_SEQ", - sequenceName = "WST_COLUMNS_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_WST_COLUMNS_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "wst_id" ) - public Wst getWst() { - return wst; - } - - public void setWst(Wst wst) { - this.wst = wst; - } - - @Column(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Column(name = "description") - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Column(name = "position") - public Integer getPosition() { - return position; - } - - public void setPosition(Integer position) { - this.position = position; - } - - @OneToOne - @JoinColumn(name = "time_interval_id" ) - public TimeInterval getTimeInterval() { - return timeInterval; - } - - public void setTimeInterval(TimeInterval timeInterval) { - this.timeInterval = timeInterval; - } - - @OneToMany - @JoinColumn(name="wst_column_id") - public List<WstColumnQRange> getColumnQRanges() { - return columnQRanges; - } - - public void setColumnQRanges(List<WstColumnQRange> columnQRanges) { - this.columnQRanges = columnQRanges; - } - - @OneToMany - @JoinColumn(name="wst_column_id") - public List<WstColumnValue> getColumnValues() { - return columnValues; - } - - public void setColumnValues(List<WstColumnValue> columnValues) { - this.columnValues = columnValues; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/WstColumnQRange.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -package de.intevation.flys.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "wst_column_q_ranges") -public class WstColumnQRange -implements Serializable -{ - private Integer id; - private WstColumn wstColumn; - private WstQRange wstQRange; - - public WstColumnQRange() { - } - - public WstColumnQRange( - WstColumn wstColumn, - WstQRange wstQRange - ) { - this.wstColumn = wstColumn; - this.wstQRange = wstQRange; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_WST_Q_RANGES_ID_SEQ", - sequenceName = "WST_Q_RANGES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_WST_Q_RANGES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "wst_column_id" ) - public WstColumn getWstColumn() { - return wstColumn; - } - - public void setWstColumn(WstColumn wstColumn) { - this.wstColumn = wstColumn; - } - - @OneToOne - @JoinColumn(name = "wst_q_range_id" ) - public WstQRange getWstQRange() { - return wstQRange; - } - - public void setWstQRange(WstQRange wstQRange) { - this.wstQRange = wstQRange; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : -
--- a/flys-backend/src/main/java/de/intevation/flys/model/WstColumnValue.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,85 +0,0 @@ -package de.intevation.flys.model; - -import java.math.BigDecimal; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "wst_column_values") -public class WstColumnValue -implements Serializable -{ - private Integer id; - private WstColumn wstColumn; - private BigDecimal position; - private BigDecimal w; - - public WstColumnValue() { - } - - public WstColumnValue( - WstColumn wstColumn, - BigDecimal position, - BigDecimal w - ) { - this.wstColumn = wstColumn; - this.position = position; - this.w = w; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_WST_COLUMN_VALUES_ID_SEQ", - sequenceName = "WST_COLUMN_VALUES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_WST_COLUMN_VALUES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "wst_column_id") - public WstColumn getWstColumn() { - return wstColumn; - } - - public void setWstColumn(WstColumn wstColumn) { - this.wstColumn = wstColumn; - } - - @Column(name = "position") // FIXME: type mapping needed? - public BigDecimal getPosition() { - return position; - } - - public void setPosition(BigDecimal position) { - this.position = position; - } - - @Column(name = "w") // FIXME: type mapping needed? - public BigDecimal getW() { - return w; - } - - public void setW(BigDecimal w) { - this.w = w; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/model/WstQRange.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,70 +0,0 @@ -package de.intevation.flys.model; - -import java.math.BigDecimal; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.GeneratedValue; -import javax.persistence.Column; -import javax.persistence.SequenceGenerator; -import javax.persistence.GenerationType; -import javax.persistence.OneToOne; -import javax.persistence.JoinColumn; - -@Entity -@Table(name = "wst_q_ranges") -public class WstQRange -implements Serializable -{ - private Integer id; - private Range range; - private BigDecimal q; - - public WstQRange() { - } - - public WstQRange(Range range, BigDecimal q) { - this.range = range; - this.q = q; - } - - @Id - @SequenceGenerator( - name = "SEQUENCE_WST_Q_RANGES_ID_SEQ", - sequenceName = "WST_Q_RANGES_ID_SEQ", - allocationSize = 1) - @GeneratedValue( - strategy = GenerationType.SEQUENCE, - generator = "SEQUENCE_WST_Q_RANGES_ID_SEQ") - @Column(name = "id") - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @OneToOne - @JoinColumn(name = "range_id" ) - public Range getRange() { - return range; - } - - public void setRange(Range range) { - this.range = range; - } - - @Column(name = "q") // FIXME: type mapping needed?! - public BigDecimal getQ() { - return q; - } - - public void setQ(BigDecimal q) { - this.q = q; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/utils/DBCPConnectionProvider.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,253 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package de.intevation.flys.utils; - -import java.sql.Connection; -import java.sql.SQLException; - -import java.util.Iterator; -import java.util.Properties; -import java.util.Map; -import java.util.Collections; -import java.util.StringTokenizer; - -import org.apache.commons.dbcp.BasicDataSource; -import org.apache.commons.dbcp.BasicDataSourceFactory; - -import org.apache.log4j.Logger; - -import org.hibernate.HibernateException; - -import org.hibernate.connection.ConnectionProviderFactory; -import org.hibernate.connection.ConnectionProvider; - -import org.hibernate.cfg.Environment; - -/** - * <p>A connection provider that uses an Apache commons DBCP connection pool.</p> - * - * <p>To use this connection provider set:<br> - * <code>hibernate.connection.provider_class org.hibernate.connection.DBCPConnectionProvider</code></p> - * - * <pre>Supported Hibernate properties: - * hibernate.connection.driver_class - * hibernate.connection.url - * hibernate.connection.username - * hibernate.connection.password - * hibernate.connection.isolation - * hibernate.connection.autocommit - * hibernate.connection.pool_size - * hibernate.connection (JDBC driver properties)</pre> - * <br> - * All DBCP properties are also supported by using the hibernate.dbcp prefix. - * A complete list can be found on the DBCP configuration page: - * <a href="http://jakarta.apache.org/commons/dbcp/configuration.html">http://jakarta.apache.org/commons/dbcp/configuration.html</a>. - * <br> - * <pre>Example: - * hibernate.connection.provider_class org.hibernate.connection.DBCPConnectionProvider - * hibernate.connection.driver_class org.hsqldb.jdbcDriver - * hibernate.connection.username sa - * hibernate.connection.password - * hibernate.connection.url jdbc:hsqldb:test - * hibernate.connection.pool_size 20 - * hibernate.dbcp.initialSize 10 - * hibernate.dbcp.maxWait 3000 - * hibernate.dbcp.validationQuery select 1 from dual</pre> - * - * <p>More information about configuring/using DBCP can be found on the - * <a href="http://jakarta.apache.org/commons/dbcp/">DBCP website</a>. - * There you will also find the DBCP wiki, mailing lists, issue tracking - * and other support facilities</p> - * - * @see org.hibernate.connection.ConnectionProvider - * @author Dirk Verbeeck - */ -public class DBCPConnectionProvider -implements ConnectionProvider -{ - private static Logger log = Logger.getLogger(DBCPConnectionProvider.class); - - private static final String PREFIX = "hibernate.dbcp."; - - private BasicDataSource ds; - - // Old Environment property for backward-compatibility - // (property removed in Hibernate3) - private static final String DBCP_PS_MAXACTIVE = - "hibernate.dbcp.ps.maxActive"; - - // Property doesn't exists in Hibernate2 - private static final String AUTOCOMMIT = - "hibernate.connection.autocommit"; - - public void configure(Properties props) throws HibernateException { - try { - log.debug("Configure DBCPConnectionProvider"); - - // DBCP properties used to create the BasicDataSource - Properties dbcpProperties = new Properties(); - - // DriverClass & url - String jdbcDriverClass = props.getProperty(Environment.DRIVER); - String jdbcUrl = props.getProperty(Environment.URL); - dbcpProperties.put("driverClassName", jdbcDriverClass); - dbcpProperties.put("url", jdbcUrl); - - // Username / password - String username = props.getProperty(Environment.USER); - String password = props.getProperty(Environment.PASS); - dbcpProperties.put("username", username); - dbcpProperties.put("password", password); - - // Isolation level - String isolationLevel = props.getProperty(Environment.ISOLATION); - if (isolationLevel != null - && (isolationLevel = isolationLevel.trim()).length() > 0) { - dbcpProperties.put("defaultTransactionIsolation", isolationLevel); - } - - // Turn off autocommit (unless autocommit property is set) - String autocommit = props.getProperty(AUTOCOMMIT); - if (autocommit != null - && (autocommit = autocommit.trim()).length() > 0) { - dbcpProperties.put("defaultAutoCommit", autocommit); - } else { - dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE)); - } - - // Pool size - String poolSize = props.getProperty(Environment.POOL_SIZE); - if (poolSize != null - && (poolSize = poolSize.trim()).length() > 0 - && Integer.parseInt(poolSize) > 0) { - dbcpProperties.put("maxActive", poolSize); - } - - // Copy all "driver" properties into "connectionProperties" - Properties driverProps = - ConnectionProviderFactory.getConnectionProperties(props); - - if (driverProps.size() > 0) { - StringBuilder connectionProperties = new StringBuilder(); - for (Iterator iter = driverProps.entrySet().iterator(); - iter.hasNext(); - ) { - Map.Entry entry = (Map.Entry)iter.next(); - String key = (String)entry.getKey(); - String value = (String)entry.getValue(); - connectionProperties - .append(key) - .append('=') - .append(value); - if (iter.hasNext()) { - connectionProperties.append(';'); - } - } - dbcpProperties.put( - "connectionProperties", connectionProperties.toString()); - } - - // Copy all DBCP properties removing the prefix - for (Iterator iter = props.entrySet().iterator() ; iter.hasNext() ;) { - Map.Entry entry = (Map.Entry)iter.next(); - String key = (String)entry.getKey(); - if (key.startsWith(PREFIX)) { - String property = key.substring(PREFIX.length()); - String value = (String)entry.getValue(); - dbcpProperties.put(property, value); - } - } - - // Backward-compatibility - if (props.getProperty(DBCP_PS_MAXACTIVE) != null) { - dbcpProperties.put( - "poolPreparedStatements", - String.valueOf(Boolean.TRUE)); - dbcpProperties.put( - "maxOpenPreparedStatements", - props.getProperty(DBCP_PS_MAXACTIVE)); - } - - // Some debug info - /* // commented out, because it leaks the password - if (log.isDebugEnabled()) { - log.debug("Creating a DBCP BasicDataSource" + - " with the following DBCP factory properties:"); - StringWriter sw = new StringWriter(); - dbcpProperties.list(new PrintWriter(sw, true)); - log.debug(sw.toString()); - } - */ - - // Let the factory create the pool - ds = (BasicDataSource)BasicDataSourceFactory - .createDataSource(dbcpProperties); - - // This needs to be done manually as it is somehow ignored - // by the BasicDataSourceFactory if you set it as a dbcpProperty - String connectionInitSqls = props.getProperty("connectionInitSqls"); - if (connectionInitSqls != null) { - StringTokenizer tokenizer = new StringTokenizer(connectionInitSqls, ";"); - ds.setConnectionInitSqls(Collections.list(tokenizer)); - } - // The BasicDataSource has lazy initialization - // borrowing a connection will start the DataSource - // and make sure it is configured correctly. - - // Connection conn = ds.getConnection(); - // conn.close(); - } - catch (Exception e) { - String message = "Could not create a DBCP pool"; - log.fatal(message, e); - if (ds != null) { - BasicDataSource x = ds; ds = null; - try { - x.close(); - } - catch (SQLException sqle) { - } - } - throw new HibernateException(message, e); - } - log.debug("Configure DBCPConnectionProvider complete"); - } - - public Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - public void closeConnection(Connection conn) throws SQLException { - conn.close(); - } - - public void close() throws HibernateException { - try { - if (ds != null) { - BasicDataSource x = ds; ds = null; - x.close(); - } - } - catch (SQLException sqle) { - throw new HibernateException("Could not close DBCP pool", sqle); - } - } - - public boolean supportsAggressiveRelease() { - return false; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/utils/DateGuesser.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,258 +0,0 @@ -package de.intevation.flys.utils; - -/** - * Copyright (c) 2006 by Intevation GmbH - * - * @author Sascha L. Teichmann (teichmann@intevation.de) - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL coming with FLYS for details. - */ - -import java.util.Date; -import java.util.Calendar; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -public final class DateGuesser { - public static final String [] MONTH = { - "jan", "feb", "mrz", "apr", "mai", "jun", - "jul", "aug", "sep", "okt", "nov", "dez" - }; - - public static final int guessMonth(String s) { - s = s.toLowerCase(); - for (int i = 0; i < MONTH.length; ++i) - if (MONTH[i].equals(s)) { - return i; - } - return -1; - } - - public static final Pattern YYYY_MM_DD = - Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})$"); - - public static final Pattern DD_MM_YYYY = - Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})$"); - - public static final Pattern MMM_YYYY = - Pattern.compile("^(\\d{0,2})\\.?(\\w{3})\\.?(\\d{2,4})$"); - - public static final Pattern GARBAGE_YYYY = - Pattern.compile("^\\D*(\\d{2,4})$"); - - public static final Pattern YYYY_MM_DDThh_mm = - Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})$"); - - public static final Pattern YYYY_MM_DDThh_mm_ss = - Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$"); - - public static final Pattern DD_MM_YYYYThh_mm = - Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})T(\\d{1,2}):(\\d{2})$"); - - public static final Pattern DD_MM_YYYYThh_mm_ss = - Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})T(\\d{1,2}):(\\d{2}):(\\d{2})$"); - - public static final Pattern DDMMYY = - Pattern.compile("^(\\d{1,2})(\\d{1,2})(\\d{1,2})$"); - - private DateGuesser() { - } - - public static final int calendarMonth(String month) { - return calendarMonth(Integer.parseInt(month)); - } - - public static final int calendarMonth(int month) { - return Math.max(Math.min(month-1, 11), 0); - } - - /** - * Guess date by trying all different patterns. - * Throws IllegalArgumentException if not able to guess. - * @param s The date to be guessed (e.g. 11.02.2001). - * @return the parsed Date. - */ - public static Date guessDate(String s) { - if (s == null || (s = s.trim()).length() == 0) { - throw new IllegalArgumentException(); - } - - Matcher m; - - m = YYYY_MM_DD.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(1); - String month = m.group(2); - String day = m.group(3); - cal.set( - Integer.parseInt(year), - calendarMonth(month), - Integer.parseInt(day), - 12, 0, 0); - return cal.getTime(); - } - - m = DD_MM_YYYY.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(3); - String month = m.group(2); - String day = m.group(1); - cal.set( - Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), - calendarMonth(month), - Integer.parseInt(m.group(1)), - 12, 0, 0); - return cal.getTime(); - } - - m = MMM_YYYY.matcher(s); - - if (m.matches()) { - int month = guessMonth(m.group(2)); - if (month >= 0) { - Calendar cal = Calendar.getInstance(); - String year = m.group(3); - String day = m.group(1); - cal.set( - Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), - month, - day.length() == 0 ? 15 : Integer.parseInt(day), - 12, 0, 0); - return cal.getTime(); - } - } - - m = YYYY_MM_DDThh_mm.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(1); - String month = m.group(2); - String day = m.group(3); - String hour = m.group(4); - String minute = m.group(5); - cal.set( - Integer.parseInt(year), - calendarMonth(month), - Integer.parseInt(day), - Integer.parseInt(hour), - Integer.parseInt(minute), - 0 - ); - return cal.getTime(); - } - - m = YYYY_MM_DDThh_mm_ss.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(1); - String month = m.group(2); - String day = m.group(3); - String hour = m.group(4); - String minute = m.group(5); - String second = m.group(6); - cal.set( - Integer.parseInt(year), - calendarMonth(month), - Integer.parseInt(day), - Integer.parseInt(hour), - Integer.parseInt(minute), - Integer.parseInt(second) - ); - return cal.getTime(); - } - - m = DD_MM_YYYYThh_mm.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(3); - String month = m.group(2); - String day = m.group(1); - String hour = m.group(4); - String minute = m.group(5); - cal.set( - Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), - calendarMonth(month), - Integer.parseInt(day), - Integer.parseInt(hour), - Integer.parseInt(minute), - 0 - ); - return cal.getTime(); - } - - m = DD_MM_YYYYThh_mm_ss.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(3); - String month = m.group(2); - String day = m.group(1); - String hour = m.group(4); - String minute = m.group(5); - String second = m.group(6); - cal.set( - Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), - calendarMonth(month), - Integer.parseInt(day), - Integer.parseInt(hour), - Integer.parseInt(minute), - Integer.parseInt(second) - ); - return cal.getTime(); - } - - m = DDMMYY.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String day = m.group(1); - String month = m.group(2); - String yearS = m.group(3); - int year = Integer.parseInt(yearS); - - if (year <= cal.get(Calendar.YEAR) % 100) { - year += 2000; - } - else { - year += 1900; - } - cal.set( - year, - Integer.parseInt(month), // month - Integer.parseInt(day), // day - 12, 0, 0); - return cal.getTime(); - } - - m = GARBAGE_YYYY.matcher(s); - - if (m.matches()) { - Calendar cal = Calendar.getInstance(); - String year = m.group(1); - cal.set( - Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), - 5, // month - 15, // day - 12, 0, 0); - return cal.getTime(); - } - - throw new IllegalArgumentException(); - } - - public static void main(String [] args) { - for (int i = 0; i < args.length; ++i) { - System.out.println(args[i] + ": " + guessDate(args[i])); - } - } -} -// end of file
--- a/flys-backend/src/main/java/de/intevation/flys/utils/EpsilonComparator.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,27 +0,0 @@ -package de.intevation.flys.utils; - -import java.util.Comparator; - -/** Comparator with some tolerance (epsilon). */ -public class EpsilonComparator implements Comparator<Double> -{ - public static final double EPSILON = 1e-4; - - /** Ready-made comparator with 1e-4 tolerance. */ - public static final EpsilonComparator CMP = new EpsilonComparator(EPSILON); - - private double epsilon; - - public EpsilonComparator(double epsilon) { - this.epsilon = epsilon; - } - - @Override - public int compare(Double a, Double b) { - double diff = a - b; - if (diff < -epsilon) return -1; - if (diff > epsilon) return +1; - return 0; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-backend/src/main/java/de/intevation/flys/utils/StringUtil.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,829 +0,0 @@ -package de.intevation.flys.utils; - -/** - * Copyright (c) 2006 by Intevation GmbH - * - * @author Sascha L. Teichmann (teichmann@intevation.de) - * @author Ludwig Reiter (ludwig@intevation.de) - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL coming with FLYS for details. - */ -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Locale; - -import java.net.URLEncoder; -import java.net.URLDecoder; - -import java.io.UnsupportedEncodingException; -import java.io.IOException; -import java.io.BufferedReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.PrintWriter; - - -public final class StringUtil { - final static String NUMBER_SEPERATOR = ";"; - final static String LINE_SEPERATOR = ":"; - - private StringUtil() { - } - - public static final String double2DArrayToString(double[][] values) { - - if (values == null) { - throw new IllegalArgumentException("keine double[][]-Werte"); - } - - StringBuilder strbuf = new StringBuilder(); - - for (int i=0; i < values.length; i++) { - if (i>0) { - strbuf.append(LINE_SEPERATOR); - } - for (int j=0; j < values[i].length; j++) { - if (j > 0) { - strbuf.append(NUMBER_SEPERATOR); - } - strbuf.append(values[i][j]); - } - } - - return strbuf.toString(); - } - - public static final double[][] stringToDouble2DArray(String str) { - if (str == null || str.length() == 0) { - return null; - } - - String[] lineSplit = str.split(LINE_SEPERATOR); - double[][] array2D = new double[lineSplit.length][]; - for (int i=0; i < lineSplit.length; i++) { - String[] numberSplit = lineSplit[i].split(NUMBER_SEPERATOR); - - double[] numbers = new double[numberSplit.length]; - for (int j=0; j < numberSplit.length; j++) { - numbers[j] = Double.valueOf(numberSplit[j]).doubleValue(); - } - - array2D[i] = numbers; - } - - return array2D; - } - - /** - * Remove first occurrence of "[" and "]" (if both do occur). - * @param value String to be stripped of [] (might be null). - * @return input string but with [ and ] removed, or input string if no - * brackets were found. - */ - public static final String unbracket(String value) { - // null- guard - if (value == null) return value; - - int start = value.indexOf("["); - int end = value.indexOf("]"); - - if (start < 0 || end < 0) { - return value; - } - - value = value.substring(start + 1, end); - - return value; - } - - - /** - * From "Q=1" make "W(Q=1)". - * @return original string wraped in "W()" if it contains a "Q", original - * string otherwise. - */ - public static String wWrap(String wOrQ) { - return (wOrQ != null && wOrQ.indexOf("Q") >=0) - ? "W(" + wOrQ + ")" - : wOrQ; - } - - - public static final String [] splitLines(String s) { - if (s == null) { - return null; - } - ArrayList<String> list = new ArrayList<String>(); - - BufferedReader in = null; - - try { - in = - new BufferedReader( - new StringReader(s)); - - String line; - - while ((line = in.readLine()) != null) { - list.add(line); - } - } - catch (IOException ioe) { - return null; - } - finally { - if (in != null) - try { - in.close(); - } - catch (IOException ioe) {} - } - - return list.toArray(new String[list.size()]); - } - - public static final String concat(String [] s) { - return concat(s, null); - } - - public static final String concat(String [] s, String glue) { - if (s == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < s.length; ++i) { - if (i > 0 && glue != null) { - sb.append(glue); - } - sb.append(s[i]); - } - return sb.toString(); - } - - public static final String [] splitAfter(String [] src, int N) { - if (src == null) { - return null; - } - - ArrayList<String> list = new ArrayList<String>(src.length); - for (int i = 0; i < src.length; ++i) { - String s = src[i]; - int R; - if (s == null || (R = s.length()) == 0) { - list.add(s); - } - else { - while (R > N) { - list.add(s.substring(0, N)); - s = s.substring(N); - R = s.length(); - } - list.add(s); - } - } - return list.toArray(new String[list.size()]); - } - - public static final String [] splitQuoted(String s) { - return splitQuoted(s, '"'); - } - - public static final String[] fitArray(String [] src, String [] dst) { - if (src == null) { - return dst; - } - if (dst == null) { - return src; - } - - if (src.length == dst.length) { - return src; - } - - System.arraycopy(src, 0, dst, 0, Math.min(dst.length, src.length)); - - return dst; - } - - public static final String [] splitQuoted(String s, char quoteChar) { - if (s == null) { - return null; - } - ArrayList<String> l = new ArrayList<String>(); - int mode = 0, last_mode = 0; - StringBuilder sb = new StringBuilder(); - for (int N = s.length(), i = 0; i < N; ++i) { - char c = s.charAt(i); - switch (mode) { - case 0: // unquoted mode - if (c == quoteChar) { - mode = 1; // to quoted mode - if (sb.length() > 0) { - l.add(sb.toString()); - sb.setLength(0); - } - } - else if (c == '\\') { - last_mode = 0; - mode = 2; // escape mode - } - else if (!Character.isWhitespace(c)) { - sb.append(c); - } - else if (sb.length() > 0) { - l.add(sb.toString()); - sb.setLength(0); - } - break; - case 1: // quote mode - if (c == '\\') { - last_mode = 1; - mode = 2; // escape mode - } - else if (c == quoteChar) { // leave quote mode - l.add(sb.toString()); - sb.setLength(0); - mode = 0; // to unquoted mode - } - else { - sb.append(c); - } - break; - case 2: // escape mode - sb.append(c); - mode = last_mode; - break; - } - } - if (sb.length() > 0) { - l.add(sb.toString()); - } - return l.toArray(new String[l.size()]); - } - - public static final String [] splitUnique(String s) { - return splitUnique(s, "[\\s,]+"); - } - - public static final String [] splitUnique(String s, String sep) { - return s != null ? unique(s.split(sep)) : null; - } - - public static final String [] unique(String [] str) { - if (str == null || str.length == 1) { - return str; - } - - Arrays.sort(str); - - for (int i = 1; i < str.length; ++i) - if (str[i].equals(str[i-1])) { - ArrayList<String> list = new ArrayList<String>(str.length); - - for (int j = 0; j < i; ++j) { - list.add(str[j]); - } - - String last = str[i]; - - for (++i; i < str.length; ++i) - if (!last.equals(str[i])) { - list.add(last = str[i]); - } - - return list.toArray(new String[list.size()]); - } - - return str; - } - - public static final String [] ensureEmptyExistence(String [] str) { - if (str == null) { - return null; - } - - for (int i = 0; i < str.length; ++i) - if (str[i].length() == 0) { - if (i != 0) { // copy to front - String t = str[0]; - str[0] = str[i]; - str[i] = t; - } - return str; - } - - String [] n = new String[str.length+1]; - n[0] = ""; - System.arraycopy(str, 0, n, 1, str.length); - return n; - } - - public static final String ensureWidthPadLeft(String s, int width, char pad) { - int N = s.length(); - if (N >= width) { - return s; - } - StringBuilder sb = new StringBuilder(width); - for (; N < width; ++N) { - sb.append(pad); - } - sb.append(s); - return sb.toString(); - } - - public static final String [] splitWhiteSpaceWithNAsPad( - String s, - int N, - String pad - ) { - if (s == null) { - return null; - } - - boolean copyChars = true; - int count = 0; // number of WS - - int S = s.length(); - - ArrayList<String> parts = new ArrayList<String>(); - - StringBuilder part = new StringBuilder(S); - - for (int i = 0; i < S; ++i) { - char c = s.charAt(i); - if (copyChars) { // char mode - if (Character.isWhitespace(c)) { - if (part.length() > 0) { - parts.add(part.toString()); - part.setLength(0); - } - count = 1; - copyChars = false; // to WS mode - } - else { - part.append(c); - } - } - else { // counting WS - if (Character.isWhitespace(c)) { - ++count; - } - else { - while (count >= N) {// enough to insert pad? - parts.add(pad); - count -= N; - } - part.append(c); - count = 0; - copyChars = true; // back to char mode - } - } - } // for all chars - - if (copyChars) { - if (part.length() > 0) { - parts.add(part.toString()); - } - } - else { - while (count >= N) { // enough to insert pad? - parts.add(pad); - count -= N; - } - } - - return parts.toArray(new String[parts.size()]); - } - - public static final String encodeURL(String url) { - try { - return url != null - ? URLEncoder.encode(url, "UTF-8") - : ""; - } - catch (UnsupportedEncodingException usee) { - throw new RuntimeException(usee.getLocalizedMessage()); - } - } - - public static final String decodeURL(String url) { - try { - return url != null - ? URLDecoder.decode(url, "UTF-8") - : ""; - } - catch (UnsupportedEncodingException usee) { - throw new RuntimeException(usee.getLocalizedMessage()); - } - } - - public static final boolean isEmpty(String s) { - return s == null || s.length() == 0; - } - - public static final String empty(String s) { - return s == null ? "" : s; - } - - - public static final String trim(String s) { - return s != null ? s.trim() : null; - } - - public static final String uniqueWhitespaces(String s) { - if (s == null) { - return null; - } - - boolean wasWS = false; - StringBuilder sb = new StringBuilder(); - - for (int N = s.length(), i = 0; i < N; ++i) { - char c = s.charAt(i); - if (Character.isWhitespace(c)) { - if (!wasWS) { - sb.append(c); - wasWS = true; - } - } - else { - sb.append(c); - wasWS = false; - } - } - - return sb.toString(); - } - - public static final String replaceNewlines(String s) { - return s == null - ? null - : s.replace('\r', ' ').replace('\n', ' '); - } - - /* - public static final String quoteReplacement(String s) { - - if (s == null || (s.indexOf('\\') == -1 && s.indexOf('$') == -1)) - return s; - - StringBuilder sb = new StringBuilder(); - - for (int N = s.length(), i = 0; i < N; ++i) { - char c = s.charAt(i); - if (c == '\\' || c == '$') sb.append('\\'); - sb.append(c); - } - - return sb.toString(); - } - */ - - public static final String quoteReplacement(String s) { - - if (s == null) { - return null; - } - - for (int N = s.length(), i = 0; i < N; ++i) { // plain check loop - char c = s.charAt(i); - if (c == '$' || c == '\\') { // first special -> StringBuilder - StringBuilder sb = new StringBuilder(s.substring(0, i)) - .append('\\') - .append(c); - for (++i; i < N; ++i) { // build StringBuilder with rest - if ((c = s.charAt(i)) == '$' || c == '\\') { - sb.append('\\'); - } - sb.append(c); - } - return sb.toString(); - } - } - - return s; - } - - public static final String repeat(String what, int times) { - return repeat(what, times, new StringBuilder()).toString(); - } - - public static final StringBuilder repeat(String what, int times, StringBuilder sb) { - while (times-- > 0) { - sb.append(what); - } - return sb; - } - - /** - * Returns the file name without extension. - */ - public static final String cutExtension(String s) { - if (s == null) { - return null; - } - int dot = s.lastIndexOf('.'); - return dot >= 0 - ? s.substring(0, dot) - : s; - } - - public static final String extension(String s) { - if (s == null) { - return null; - } - int dot = s.lastIndexOf('.'); - return dot >= 0 - ? s.substring(dot+1) - : s; - } - - public static final String [] splitExtension(String x) { - if (x == null) { - return null; - } - int i = x.lastIndexOf('.'); - return i < 0 - ? new String[] { x, null } - : new String[] { x.substring(0, Math.max(0, i)), x.substring(i+1).toLowerCase() }; - } - - public static String entityEncode(String s) { - if (s == null || s.length() == 0) { - return s; - } - - StringBuilder sb = new StringBuilder(); - for (int i=0, N =s.length(); i < N; i++) { - char c = s.charAt(i); - switch (c) { - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '&': - sb.append("&"); - break; - default: - sb.append(c); - } - } - return sb.toString(); - } - - public static String entityDecode(String s) { - if (s == null || s.length() == 0) { - return s; - } - - boolean amp = false; - StringBuilder sb = new StringBuilder(); - StringBuilder ampbuf = new StringBuilder(); - for (int i=0, N =s.length(); i < N; i++) { - char c = s.charAt(i); - if (amp) { - if (c == ';') { - amp = false; - String str = ampbuf.toString(); - ampbuf.setLength(0); - if (str.equals("lt")) { - sb.append('<'); - } - else if (str.equals("gt")) { - sb.append('>'); - } - else if (str.equals("amp")) { - sb.append('&'); - } - else { - sb.append('&').append(str).append(';'); - } - } - else { - ampbuf.append(c); - } - } - else if (c=='&') { - amp = true; - } - else { - sb.append(c); - } - - } - return sb.toString(); - } - - public static final String quote(String s) { - return quote(s, '"'); - } - - public static final String quote(String s, char quoteChar) { - if (s == null) { - return null; - } - - int N = s.length(); - - if (N == 0) - return new StringBuilder(2) - .append(quoteChar) - .append(quoteChar) - .toString(); - - StringBuilder sb = null; - - int i = 0; - - for (; i < N; ++i) { - char c = s.charAt(i); - - if (Character.isWhitespace(c)) { - sb = new StringBuilder() - .append(quoteChar) - .append(s.substring(0, i+1)); - break; - } - else if (c == quoteChar) { - sb = new StringBuilder() - .append(quoteChar) - .append(s.substring(0, i)) - .append('\\') - .append(quoteChar); - break; - } - } - - if (sb == null) { - return s; - } - - for (++i; i < N; ++i) { - char c = s.charAt(i); - if (c == quoteChar || c == '\\') { - sb.append('\\'); - } - - sb.append(c); - } - - return sb.append(quoteChar).toString(); - } - - /* - public static String sprintf(String format, Object... args) { - return sprintf(null, format, args); - } - */ - - public static String sprintf(Locale locale, String format, Object ... args) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - pw.printf(locale, format, args); - pw.flush(); - return sw.toString(); - } - - - public static void testQuote() { - System.err.println("testing quote:"); - - String cases [] = { - "", "''", - "test", "test", - "test test", "'test test'", - " test", "' test'", - "test ", "'test '", - " test ", "' test '", - "'test", "'\\'test'", - "'", "'\\''", - " ' ' ", "' \\' \\' '", - "te'st", "'te\\'st'" - }; - - int failed = 0; - - for (int i = 0; i < cases.length; i += 2) { - String in = cases[i]; - String out = cases[i+1]; - - String res = quote(in, '\''); - if (!res.equals(out)) { - ++failed; - System.err.println( - "quote failed on: >" + in + - "< result: >" + res + - "< expected: >" + out + "<"); - } - } - - int T = cases.length/2; - - System.err.println("tests total: " + T); - System.err.println("tests failed: " + failed); - System.err.println("tests passed: " + (T - failed)); - } - - public static void testQuoteReplacement() { - System.err.println("testing quoteReplacement:"); - - String cases [] = { - "", "", - "test", "test", - "$", "\\$", - "\\", "\\\\", - "\\$", "\\\\\\$", - "test\\$", "test\\\\\\$", - "\\test", "\\\\test", - "test$", "test\\$", - "test$test", "test\\$test", - "$test$", "\\$test\\$" - }; - - int failed = 0; - - for (int i = 0; i < cases.length; i += 2) { - String in = cases[i]; - String out = cases[i+1]; - - String res = quoteReplacement(in); - if (!res.equals(out)) { - ++failed; - System.err.println( - "quoteReplacement failed on: '" + in + - "' result: '" + res + - "' expected: '" + out + "'"); - } - } - - int T = cases.length/2; - - System.err.println("tests total: " + T); - System.err.println("tests failed: " + failed); - System.err.println("tests passed: " + (T - failed)); - } - - public static void testStringArray2D() { - int total = 0; - int fail = 0; - int passed = 0; - - System.err.println("testing StringArray2D:"); - - double[][] testarray = {{1.0, 2.0, 3.0}, - {1.1, 2.1, 3.1}, - {100.2, 200.2} - }; - String str = double2DArrayToString(testarray); - - total += 1; - if (str.equals("1.0;2.0;3.0:1.1;2.1;3.1:100.2;200.2")) { - passed +=1; - } - else { - fail +=1; - System.err.println("Der Ergebnis-String ist nicht richtig:"); - System.err.println(str); - } - - - - double[][] testarray2 = stringToDouble2DArray(str); - boolean failed = false; - - total +=1; - for (int i=0; i < testarray.length; i++) - for (int j=0; j < testarray[i].length; j++) - if (testarray[i][j] != testarray2[i][j]) { - System.err.println("Test scheitert bei i=" +i +" j=" +j); - System.err.println("alter Wert=" + testarray[i][j] +" neuer Wert=" +testarray2[i][j]); - failed = true; - } - if (failed) { - fail +=1; - } - else { - passed +=1; - } - System.err.println("tests total: "+ total); - System.err.println("tests failed: "+ fail); - System.err.println("tests passed: "+ passed); - } - - public static void main(String [] args) { - - testQuoteReplacement(); - testQuote(); - testStringArray2D(); - } - - /** Check for occurence of needle in hay, converting both to lowercase - * to be ignorant of cases. */ - public static boolean containsIgnoreCase(String hay, String needle) { - return hay.toLowerCase().contains(needle.toLowerCase()); - } -} -// end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/App.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,30 @@ +package de.intevation.flys; + +import de.intevation.flys.backend.SessionFactoryProvider; +import de.intevation.flys.backend.FLYSCredentials; + +import org.hibernate.cfg.Configuration; + +import org.hibernate.dialect.resolver.DialectFactory; + +public class App +{ + public static void dumpSchema(Configuration cfg) { + System.out.println("BEGIN;"); + + String [] setupScript = cfg.generateSchemaCreationScript( + DialectFactory.constructDialect( + FLYSCredentials.getDefault().getDialect())); + + for (String line: setupScript) { + System.out.println(line + ";"); + } + + System.out.println("COMMIT;"); + } + + public static void main(String [] args) { + dumpSchema(SessionFactoryProvider.createConfiguration()); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/Credentials.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,90 @@ +package de.intevation.flys.backend; + +public abstract class Credentials +{ + protected String user; + protected String password; + protected String dialect; + protected String driver; + protected String url; + protected String connectionInitSqls; + protected Class [] classes; + + public Credentials() { + } + + public Credentials( + String user, + String password, + String dialect, + String driver, + String url, + String connectionInitSqls, + Class [] classes + ) { + this.user = user; + this.password = password; + this.dialect = dialect; + this.driver = driver; + this.url = url; + this.connectionInitSqls = connectionInitSqls; + this.classes = classes; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getDialect() { + return dialect; + } + + public void setDialect(String dialect) { + this.dialect = dialect; + } + + public String getDriver() { + return driver; + } + + public void setDriver(String driver) { + this.driver = driver; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getConnectionInitSqls() { + return connectionInitSqls; + } + + public void setConnectionInitSqls(String connectionInitSqls) { + this.connectionInitSqls = connectionInitSqls; + } + + public Class [] getClasses() { + return classes; + } + + public void setClasses(Class [] classes) { + this.classes = classes; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/FLYSCredentials.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,253 @@ +package de.intevation.flys.backend; + +import de.intevation.artifacts.common.utils.Config; + +import de.intevation.flys.model.Annotation; +import de.intevation.flys.model.AnnotationType; +import de.intevation.flys.model.Attribute; +import de.intevation.flys.model.AxisKind; +import de.intevation.flys.model.BedHeightEpoch; +import de.intevation.flys.model.BedHeightEpochValue; +import de.intevation.flys.model.BedHeightSingle; +import de.intevation.flys.model.BedHeightSingleValue; +import de.intevation.flys.model.BedHeightType; +import de.intevation.flys.model.Building; +import de.intevation.flys.model.BoundaryKind; +import de.intevation.flys.model.CrossSection; +import de.intevation.flys.model.CrossSectionLine; +import de.intevation.flys.model.CrossSectionPoint; +import de.intevation.flys.model.CrossSectionTrack; +import de.intevation.flys.model.CrossSectionTrackKind; +import de.intevation.flys.model.DGM; +import de.intevation.flys.model.Depth; +import de.intevation.flys.model.DischargeTable; +import de.intevation.flys.model.DischargeTableValue; +import de.intevation.flys.model.DischargeZone; +import de.intevation.flys.model.Edge; +import de.intevation.flys.model.ElevationModel; +import de.intevation.flys.model.FedState; +import de.intevation.flys.model.Fixpoint; +import de.intevation.flys.model.Floodmaps; +import de.intevation.flys.model.Floodmark; +import de.intevation.flys.model.Floodplain; +import de.intevation.flys.model.FloodplainKind; +import de.intevation.flys.model.FlowVelocityMeasurement; +import de.intevation.flys.model.FlowVelocityMeasurementValue; +import de.intevation.flys.model.FlowVelocityModel; +import de.intevation.flys.model.FlowVelocityModelValue; +import de.intevation.flys.model.Gauge; +import de.intevation.flys.model.GaugeLocation; +import de.intevation.flys.model.GrainFraction; +import de.intevation.flys.model.HWSKind; +import de.intevation.flys.model.HWSLine; +import de.intevation.flys.model.HWSPoint; +import de.intevation.flys.model.HYK; +import de.intevation.flys.model.HYKEntry; +import de.intevation.flys.model.HYKFlowZone; +import de.intevation.flys.model.HYKFlowZoneType; +import de.intevation.flys.model.HYKFormation; +import de.intevation.flys.model.HydrBoundary; +import de.intevation.flys.model.HydrBoundaryPoly; +import de.intevation.flys.model.Jetty; +import de.intevation.flys.model.LocationSystem; +import de.intevation.flys.model.MainValue; +import de.intevation.flys.model.MainValueType; +import de.intevation.flys.model.MeasurementStation; +import de.intevation.flys.model.MorphologicalWidth; +import de.intevation.flys.model.MorphologicalWidthValue; +import de.intevation.flys.model.NamedMainValue; +import de.intevation.flys.model.Position; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; +import de.intevation.flys.model.RiverAxis; +import de.intevation.flys.model.RiverAxisKm; +import de.intevation.flys.model.SQRelation; +import de.intevation.flys.model.SQRelationValue; +import de.intevation.flys.model.SectieKind; +import de.intevation.flys.model.SobekKind; +import de.intevation.flys.model.SedimentDensity; +import de.intevation.flys.model.SedimentDensityValue; +import de.intevation.flys.model.SedimentYield; +import de.intevation.flys.model.SedimentYieldValue; +import de.intevation.flys.model.TimeInterval; +import de.intevation.flys.model.Unit; +import de.intevation.flys.model.Wst; +import de.intevation.flys.model.WstColumn; +import de.intevation.flys.model.WstColumnQRange; +import de.intevation.flys.model.WstColumnValue; +import de.intevation.flys.model.WstQRange; + +public class FLYSCredentials +extends Credentials +{ + public static final String XPATH_USER = + "/artifact-database/backend-database/user/text()"; + + public static final String XPATH_PASSWORD = + "/artifact-database/backend-database/password/text()"; + + public static final String XPATH_DIALECT = + "/artifact-database/backend-database/dialect/text()"; + + public static final String XPATH_DRIVER = + "/artifact-database/backend-database/driver/text()"; + + public static final String XPATH_URL = + "/artifact-database/backend-database/url/text()"; + + public static final String XPATH_CONNECTION_INIT_SQLS = + "/artifact-database/backend-database/connection-init-sqls/text()"; + + public static final String DEFAULT_USER = + System.getProperty("flys.backend.user", "flys"); + + public static final String DEFAULT_PASSWORD = + System.getProperty("flys.backend.password", "flys"); + + public static final String DEFAULT_DIALECT = + System.getProperty( + "flys.backend.dialect", + "org.hibernate.dialect.PostgreSQLDialect"); + + public static final String DEFAULT_DRIVER = + System.getProperty( + "flys.backend.driver", + "org.postgresql.Driver"); + + public static final String DEFAULT_URL = + System.getProperty( + "flys.backend.url", + "jdbc:postgresql://localhost:5432/flys"); + + public static final String DEFAULT_CONNECTION_INIT_SQLS = + System.getProperty( + "flys.backend.connection.init.sqls"); + + public static final Class [] CLASSES = { + Annotation.class, + AnnotationType.class, + Attribute.class, + AxisKind.class, + BedHeightEpoch.class, + BedHeightEpochValue.class, + BedHeightSingle.class, + BedHeightSingleValue.class, + BedHeightType.class, + Building.class, + BoundaryKind.class, + CrossSection.class, + CrossSectionLine.class, + CrossSectionPoint.class, + CrossSectionTrack.class, + CrossSectionTrackKind.class, + Depth.class, + DGM.class, + DischargeTable.class, + DischargeTableValue.class, + DischargeZone.class, + Edge.class, + ElevationModel.class, + FedState.class, + Fixpoint.class, + Floodmark.class, + Floodplain.class, + FloodplainKind.class, + Floodmaps.class, + FlowVelocityMeasurement.class, + FlowVelocityMeasurementValue.class, + FlowVelocityModel.class, + FlowVelocityModelValue.class, + Gauge.class, + GaugeLocation.class, + GrainFraction.class, + HWSKind.class, + HWSLine.class, + HWSPoint.class, + HydrBoundary.class, + HydrBoundaryPoly.class, + HYK.class, + HYKEntry.class, + HYKFormation.class, + HYKFlowZoneType.class, + HYKFlowZone.class, + Jetty.class, + LocationSystem.class, + MainValueType.class, + MeasurementStation.class, + MorphologicalWidth.class, + MorphologicalWidthValue.class, + NamedMainValue.class, + MainValue.class, + Position.class, + Range.class, + River.class, + RiverAxis.class, + RiverAxisKm.class, + SectieKind.class, + SobekKind.class, + SedimentDensity.class, + SedimentDensityValue.class, + SedimentYield.class, + SedimentYieldValue.class, + SQRelation.class, + SQRelationValue.class, + TimeInterval.class, + Unit.class, + WstColumn.class, + WstColumnQRange.class, + WstColumnValue.class, + Wst.class, + WstQRange.class + }; + + public FLYSCredentials() { + } + + public FLYSCredentials( + String user, + String password, + String dialect, + String driver, + String url, + String connectionInitSqls + ) { + super( + user, password, dialect, driver, url, connectionInitSqls, CLASSES); + } + + private static Credentials instance; + + public static synchronized Credentials getInstance() { + if (instance == null) { + String user = + Config.getStringXPath(XPATH_USER, DEFAULT_USER); + String password = + Config.getStringXPath(XPATH_PASSWORD, DEFAULT_PASSWORD); + String dialect = + Config.getStringXPath(XPATH_DIALECT, DEFAULT_DIALECT); + String driver = + Config.getStringXPath(XPATH_DRIVER, DEFAULT_DRIVER); + String url = + Config.getStringXPath(XPATH_URL, DEFAULT_URL); + String connectionInitSqls = + Config.getStringXPath( + XPATH_CONNECTION_INIT_SQLS, + DEFAULT_CONNECTION_INIT_SQLS); + + instance = new FLYSCredentials( + user, password, dialect, driver, url, connectionInitSqls); + } + return instance; + } + + public static Credentials getDefault() { + return new FLYSCredentials( + DEFAULT_USER, + DEFAULT_PASSWORD, + DEFAULT_DIALECT, + DEFAULT_DRIVER, + DEFAULT_URL, + DEFAULT_CONNECTION_INIT_SQLS); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/SedDBCredentials.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,209 @@ +package de.intevation.flys.backend; + +import de.intevation.artifacts.common.utils.Config; + +import de.intevation.seddb.model.Bezugspegel; +import de.intevation.seddb.model.Bezugspegelgew; +import de.intevation.seddb.model.BezugspegelgewId; +import de.intevation.seddb.model.Bild; +import de.intevation.seddb.model.Gewaesser; +import de.intevation.seddb.model.Gfaenger; +import de.intevation.seddb.model.Glotlinks; +import de.intevation.seddb.model.GlotlinksId; +import de.intevation.seddb.model.Glotrechte; +import de.intevation.seddb.model.Gprobe; +import de.intevation.seddb.model.GprobeId; +import de.intevation.seddb.model.Gsiebsatz; +import de.intevation.seddb.model.Gsiebung; +import de.intevation.seddb.model.Gsiebungsieb; +import de.intevation.seddb.model.GsiebungsiebId; +import de.intevation.seddb.model.Hpeilpunkt; +import de.intevation.seddb.model.HpeilpunktId; +import de.intevation.seddb.model.Hpeilung; +import de.intevation.seddb.model.Messung; +import de.intevation.seddb.model.Messunglotcount; +import de.intevation.seddb.model.MessunglotcountId; +import de.intevation.seddb.model.Messungsta; +import de.intevation.seddb.model.MessungstaId; +import de.intevation.seddb.model.Messunguferbezug; +import de.intevation.seddb.model.MessunguferbezugId; +import de.intevation.seddb.model.Mpeilpunkt; +import de.intevation.seddb.model.MpeilpunktId; +import de.intevation.seddb.model.Mpeilung; +import de.intevation.seddb.model.Probebild; +import de.intevation.seddb.model.Siebanalyse; +import de.intevation.seddb.model.Slotlinks; +import de.intevation.seddb.model.SlotlinksId; +import de.intevation.seddb.model.Slotrechte; +import de.intevation.seddb.model.Sohlprobe; +import de.intevation.seddb.model.Sohltest; +import de.intevation.seddb.model.Sprobe; +import de.intevation.seddb.model.SprobeId; +import de.intevation.seddb.model.Ssiebung; +import de.intevation.seddb.model.Ssiebungsieb; +import de.intevation.seddb.model.SsiebungsiebId; +import de.intevation.seddb.model.Station; +import de.intevation.seddb.model.Stationgew; +import de.intevation.seddb.model.StationgewId; +import de.intevation.seddb.model.TmpGloChanged; +import de.intevation.seddb.model.TmpMesAchanged; +import de.intevation.seddb.model.TmpMesGchanged; +import de.intevation.seddb.model.TmpMesQchanged; +import de.intevation.seddb.model.TmpMesSchanged; +import de.intevation.seddb.model.Zzarchiv; +import de.intevation.seddb.model.Zzprobenahmeart; +import de.intevation.seddb.model.Zzsondierungart; +import de.intevation.seddb.model.Zzthema; + +public class SedDBCredentials +extends Credentials +{ + public static final String XPATH_USER = + "/artifact-database/seddb-database/user/text()"; + + public static final String XPATH_PASSWORD = + "/artifact-database/seddb-database/password/text()"; + + public static final String XPATH_DIALECT = + "/artifact-database/seddb-database/dialect/text()"; + + public static final String XPATH_DRIVER = + "/artifact-database/seddb-database/driver/text()"; + + public static final String XPATH_URL = + "/artifact-database/seddb-database/url/text()"; + + public static final String XPATH_CONNECTION_INIT_SQLS = + "/artifact-database/seddb-database/connection-init-sqls/text()"; + + public static final String DEFAULT_USER = + System.getProperty("flys.seddb.user", "seddb"); + + public static final String DEFAULT_PASSWORD = + System.getProperty("flys.seddb.password", "seddb"); + + public static final String DEFAULT_DIALECT = + System.getProperty( + "flys.seddb.dialect", + "org.hibernate.dialect.PostgreSQLDialect"); + + public static final String DEFAULT_DRIVER = + System.getProperty( + "flys.seddb.driver", + "org.postgresql.Driver"); + + public static final String DEFAULT_URL = + System.getProperty( + "flys.seddb.url", + "jdbc:postgresql://localhost:5432/seddb"); + + public static final String DEFAULT_CONNECTION_INIT_SQLS = + System.getProperty( + "flys.seddb.connection.init.sqls"); + + public static final Class [] CLASSES = { + BezugspegelgewId.class, + Bezugspegelgew.class, + Bezugspegel.class, + Bild.class, + Gewaesser.class, + Gfaenger.class, + GlotlinksId.class, + Glotlinks.class, + Glotrechte.class, + GprobeId.class, + Gprobe.class, + Gsiebsatz.class, + Gsiebung.class, + GsiebungsiebId.class, + Gsiebungsieb.class, + HpeilpunktId.class, + Hpeilpunkt.class, + Hpeilung.class, + Messung.class, + MessunglotcountId.class, + Messunglotcount.class, + MessungstaId.class, + Messungsta.class, + MessunguferbezugId.class, + Messunguferbezug.class, + MpeilpunktId.class, + Mpeilpunkt.class, + Mpeilung.class, + Probebild.class, + Siebanalyse.class, + SlotlinksId.class, + Slotlinks.class, + Slotrechte.class, + Sohlprobe.class, + Sohltest.class, + SprobeId.class, + Sprobe.class, + Ssiebung.class, + SsiebungsiebId.class, + Ssiebungsieb.class, + StationgewId.class, + Stationgew.class, + Station.class, + TmpGloChanged.class, + TmpMesAchanged.class, + TmpMesGchanged.class, + TmpMesQchanged.class, + TmpMesSchanged.class, + Zzarchiv.class, + Zzprobenahmeart.class, + Zzsondierungart.class, + Zzthema.class + }; + + private static Credentials instance; + + public SedDBCredentials() { + } + + public SedDBCredentials( + String user, + String password, + String dialect, + String driver, + String url, + String connectionInitSqls + ) { + super( + user, password, dialect, driver, url, connectionInitSqls, CLASSES); + } + + public static synchronized Credentials getInstance() { + if (instance == null) { + String user = + Config.getStringXPath(XPATH_USER, DEFAULT_USER); + String password = + Config.getStringXPath(XPATH_PASSWORD, DEFAULT_PASSWORD); + String dialect = + Config.getStringXPath(XPATH_DIALECT, DEFAULT_DIALECT); + String driver = + Config.getStringXPath(XPATH_DRIVER, DEFAULT_DRIVER); + String url = + Config.getStringXPath(XPATH_URL, DEFAULT_URL); + String connectionInitSqls = + Config.getStringXPath( + XPATH_CONNECTION_INIT_SQLS, + DEFAULT_CONNECTION_INIT_SQLS); + + instance = new SedDBCredentials( + user, password, dialect, driver, url, connectionInitSqls); + } + return instance; + } + + public static Credentials getDefault() { + return new SedDBCredentials( + DEFAULT_USER, + DEFAULT_PASSWORD, + DEFAULT_DIALECT, + DEFAULT_DRIVER, + DEFAULT_URL, + DEFAULT_CONNECTION_INIT_SQLS); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/SedDBSessionHolder.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,43 @@ +package de.intevation.flys.backend; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; + +public class SedDBSessionHolder +{ + private static Logger log = + Logger.getLogger(SedDBSessionHolder.class); + + public static final ThreadLocal<Session> HOLDER = + new ThreadLocal<Session>() { + @Override + protected Session initialValue() { + return create(); + } + }; + + private SedDBSessionHolder() { + } + + public synchronized static Session create() { + log.debug("create"); + SessionFactory sessionFactory = + SessionFactoryProvider.getSedDBSessionFactory(); + return sessionFactory.openSession(); + } + + public static Session acquire() { + log.debug("acquire"); + Session session = create(); + HOLDER.set(session); + return session; + } + + public static void release() { + log.debug("release"); + HOLDER.remove(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/SessionFactoryProvider.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,170 @@ +package de.intevation.flys.backend; + +import java.util.Properties; + +import org.apache.log4j.Logger; + +import org.hibernate.SessionFactory; + +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; + +import org.hibernate.impl.SessionFactoryImpl; + +public final class SessionFactoryProvider +{ + private static Logger log = Logger.getLogger(SessionFactoryProvider.class); + + //public static final boolean ENABLE_JMX = + // Boolean.getBoolean("flys.backend.enablejmx"); + + private static SessionFactory flysSessionFactory; + private static SessionFactory sedDBSessionFactory; + + private SessionFactoryProvider() { + } + + public static synchronized SessionFactory getSessionFactory() { + if (flysSessionFactory == null) { + flysSessionFactory = + createSessionFactory(FLYSCredentials.getInstance()); + } + return flysSessionFactory; + } + + public static SessionFactory createSessionFactory() { + return createSessionFactory(FLYSCredentials.getDefault()); + } + + public static synchronized SessionFactory getSedDBSessionFactory() { + if (sedDBSessionFactory == null) { + sedDBSessionFactory = + createSessionFactory(SedDBCredentials.getInstance()); + } + return sedDBSessionFactory; + } + + public static SessionFactory createSedDBSessionFactory() { + return createSessionFactory(SedDBCredentials.getDefault()); + } + + public static SessionFactory createSessionFactory( + Credentials credentials + ) { + Configuration cfg = createConfiguration(credentials); + + SessionFactory factory = cfg.buildSessionFactory(); + + /* + if (ENABLE_JMX) { + registerAsMBean(factory); + } + else { + log.info("No JMX support for hibernate."); + } + */ + + return factory; + } + + /** XXX: Commented out till it is configured correctly. + public static void registerAsMBean(SessionFactory factory) { + + // + + StatisticsService statsMBean = new StatisticsService(); + statsMBean.setSessionFactory(factory); + statsMBean.setStatisticsEnabled(true); + + try { + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + mbs.registerMBean( + statsMBean, + new ObjectName("Hibernate:application=Statistics")); + + log.info("Enabled JMX support for hibernate."); + } + catch (MalformedObjectNameException mone) { + log.warn(mone, mone); + } + catch (InstanceAlreadyExistsException iaee) { + log.warn(iaee, iaee); + } + catch (MBeanRegistrationException mbre) { + log.warn(mbre, mbre); + } + catch (NotCompliantMBeanException ncmbe) { + log.warn(ncmbe, ncmbe); + } + } + */ + + public static Configuration createConfiguration() { + return createConfiguration(FLYSCredentials.getInstance()); + } + + public static Configuration createConfiguration( + Credentials credentials + ) { + Configuration cfg = new Configuration(); + + for (Class<?> clazz: credentials.getClasses()) { + cfg.addAnnotatedClass(clazz); + } + + if (log.isDebugEnabled()) { + log.debug("user: " + credentials.getUser()); + log.debug("dialect: " + credentials.getDialect()); + log.debug("driver: " + credentials.getDriver()); + log.debug("url: " + credentials.getUrl()); + } + + Properties props = new Properties(); + + // We rely on our own connection pool + props.setProperty( + "hibernate.connection.provider_class", + "de.intevation.flys.utils.DBCPConnectionProvider"); + + props.setProperty(Environment.DIALECT, credentials.getDialect()); + props.setProperty(Environment.USER, credentials.getUser()); + props.setProperty(Environment.PASS, credentials.getPassword()); + props.setProperty(Environment.DRIVER, credentials.getDriver()); + props.setProperty(Environment.URL, credentials.getUrl()); + + String connectionInitSqls = credentials.getConnectionInitSqls(); + if (connectionInitSqls != null) { + props.setProperty("connectionInitSqls", connectionInitSqls); + } + + cfg.mergeProperties(props); + + return cfg; + } + + + public static String getProperty(SessionFactoryImpl factory, String key) { + Properties props = factory.getProperties(); + return props.getProperty(key); + } + + public static String getUser(SessionFactoryImpl factory) { + return getProperty(factory, Environment.USER); + } + + + public static String getPass(SessionFactoryImpl factory) { + return getProperty(factory, Environment.PASS); + } + + + public static String getURL(SessionFactoryImpl factory) { + return getProperty(factory, Environment.URL); + } + + + public static String getDriver(SessionFactoryImpl factory) { + return getProperty(factory, Environment.DRIVER); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/SessionHolder.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,44 @@ +package de.intevation.flys.backend; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; + + +public class SessionHolder +{ + private static Logger log = + Logger.getLogger(SessionHolder.class); + + public static final ThreadLocal<Session> HOLDER = + new ThreadLocal<Session>() { + @Override + protected Session initialValue() { + return create(); + } + }; + + private SessionHolder() { + } + + public synchronized static Session create() { + log.debug("create"); + SessionFactory sessionFactory = + SessionFactoryProvider.getSessionFactory(); + return sessionFactory.openSession(); + } + + public static Session acquire() { + log.debug("acquire"); + Session session = create(); + HOLDER.set(session); + return session; + } + + public static void release() { + log.debug("release"); + HOLDER.remove(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/backend/SpatialInfo.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,176 @@ +package de.intevation.flys.backend; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; + +import de.intevation.flys.model.Building; +import de.intevation.flys.model.CrossSectionTrack; +import de.intevation.flys.model.Fixpoint; +import de.intevation.flys.model.River; +import de.intevation.flys.model.RiverAxis; +import de.intevation.flys.model.HWSLine; + + +public class SpatialInfo { + + private static Logger logger = Logger.getLogger(SpatialInfo.class); + + protected static String RIVERNAME = System.getProperty( + "flys.backend.spatial.river", "Saar"); + + protected Session session; + + + public static void main(String[] args) { + logger.info("Start SpatialInfo application."); + + SpatialInfo spatial = null; + + try { + spatial = new SpatialInfo(); + + River river = spatial.getRiver(RIVERNAME); + if (river == null) { + logger.warn("Could not find river '" + RIVERNAME + "'!"); + return; + } + + logger.info("Spatial information of River '" + RIVERNAME + "'"); + spatial.doRiverAxisInfo(river); + spatial.doCrossSectionTracksInfo(river); + spatial.doBuildingsInfo(river); + spatial.doFixpointsInfo(river); + } + finally { + if (spatial != null) { + spatial.close(); + } + } + + logger.info("Finish SpatialInfo application."); + } + + + public SpatialInfo() { + session = SessionFactoryProvider + .createSessionFactory() + .openSession(); + } + + + public void close() { + session.close(); + } + + + protected River getRiver(String rivername) { + Query query = session.createQuery( + "from River where name =:name"); + query.setParameter("name", rivername); + + List<River> list = query.list(); + + if (list == null || list.size() == 0) { + logger.warn("No river '" + rivername + "' found!"); + return null; + } + + return list.get(0); + } + + + protected void doRiverAxisInfo(River river) { + try { + List<RiverAxis> axis = RiverAxis.getRiverAxis(river.getName()); + if (axis != null && axis.size() > 0) { + logger.debug("TODO: Compute length and boundary."); + } + else { + logger.warn("River has no RiverAxis."); + } + } + catch(HibernateException iae) { + logger.warn("No vaild river axis found for " + river.getName()); + return; + } + + } + + + protected void doCrossSectionTracksInfo(River river) { + Query query = session.createQuery( + "from CrossSectionTrack where river =:river"); + query.setParameter("river", river); + + List<CrossSectionTrack> list = query.list(); + + if (list == null || list.size() == 0) { + logger.warn("No CrossSectionTracks for '" + river.getName() + "' found!"); + return; + } + else { + logger.info("River contains " + list.size() + " CrossSectionTracks."); + } + } + + + protected void doBuildingsInfo(River river) { + Query query = session.createQuery( + "from Building where river =:river"); + query.setParameter("river", river); + + List<Building> list = query.list(); + + if (list == null || list.size() == 0) { + logger.warn("No Buildings for '" + river.getName() + "' found!"); + return; + } + else { + logger.info("River contains " + list.size() + " Buildings."); + } + } + + + protected void doFixpointsInfo(River river) { + Query query = session.createQuery( + "from Fixpoint where river =:river"); + query.setParameter("river", river); + + List<Fixpoint> list = query.list(); + + if (list == null || list.size() == 0) { + logger.warn("No Fixpoints for '" + river.getName() + "' found!"); + return; + } + else { + logger.info("River contains " + list.size() + " Fixpoints."); + } + } + + @Deprecated + protected void doLinesInfo(River river) { + doHWSLinesInfo(river); + } + + protected void doHWSLinesInfo(River river) { + Query query = session.createQuery( + "from hws_lines where river =:river"); + query.setParameter("river", river); + + List<HWSLine> list = query.list(); + + if (list == null || list.size() == 0) { + logger.warn("No Lines for '" + river.getName() + "' found!"); + return; + } + else { + logger.info("River contains " + list.size() + " Lines."); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/Config.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,224 @@ +package de.intevation.flys.importer; + +public class Config +{ + public static final String SKIP_DEFAULT = + "flys.backend.importer.skip.default"; + + public static final String DRY_RUN = + "flys.backend.importer.dry.run"; + + public static final String INFO_GEW_FILE = + "flys.backend.importer.infogew.file"; + + public static final String ANNOTATION_TYPES = + "flys.backend.importer.annotation.types"; + + public static final String SKIP_GAUGES = + "flys.backend.importer.skip.gauges"; + + public static final String SKIP_BWASTR = + "flys.backend.importer.skip.bwastr"; + + public static final String SKIP_HISTORICAL_DISCHARGE_TABLES = + "flys.backend.importer.skip.historical.discharge.tables"; + + public static final String SKIP_ANNOTATIONS = + "flys.backend.importer.skip.annotations"; + + public static final String SKIP_PRFS = + "flys.backend.importer.skip.prfs"; + + public static final String SKIP_DA50S = + "flys.backend.importer.skip.da50s"; + + public static final String SKIP_W80S = + "flys.backend.importer.skip.w80s"; + + public static final String SKIP_W80_CSVS = + "flys.backend.importer.skip.w80.csvs"; + + public static final String SKIP_HYKS = + "flys.backend.importer.skip.hyks"; + + public static final String SKIP_WST = + "flys.backend.importer.skip.wst"; + + public static final String SKIP_EXTRA_WSTS = + "flys.backend.importer.skip.extra.wsts"; + + public static final String SKIP_FIXATIONS = + "flys.backend.importer.skip.fixations"; + + public static final String SKIP_OFFICIAL_LINES = + "flys.backend.importer.skip.official.lines"; + + public static final String SKIP_FLOOD_WATER = + "flys.backend.importer.skip.flood.water"; + + public static final String SKIP_FLOOD_PROTECTION = + "flys.backend.importer.skip.flood.protection"; + + public static final String SKIP_BED_HEIGHT_SINGLE = + "flys.backend.importer.skip.bed.height.single"; + + public static final String SKIP_DA66S = + "flys.backend.importer.skip.da66s"; + + public static final String SKIP_BED_HEIGHT_EPOCH = + "flys.backend.importer.skip.bed.height.epoch"; + + public static final String SKIP_SEDIMENT_DENSITY = + "flys.backend.importer.skip.sediment.density"; + + public static final String SKIP_MORPHOLOGICAL_WIDTH = + "flys.backend.importer.skip.morphological.width"; + + public static final String SKIP_FLOW_VELOCITY = + "flys.backend.importer.skip.flow.velocity"; + + public static final String SKIP_SEDIMENT_YIELD = + "flys.backend.importer.skip.sediment.yield"; + + public static final String SKIP_WATERLEVELS = + "flys.backend.importer.skip.waterlevels"; + + public static final String SKIP_WATERLEVEL_DIFFERENCES = + "flys.backend.importer.skip.waterlevel.differences"; + + public static final String SKIP_MEASUREMENT_STATIONS = + "flys.backend.importer.skip.measurement.stations"; + + public static final String SKIP_SQ_RELATION = + "flys.backend.importer.skip.sq.relation"; + + + public static final Config INSTANCE = new Config(); + + private Config () { + } + + public static final boolean getFlag(String key) { + String flag = System.getProperty(key); + return flag != null + ? Boolean.valueOf(flag) + : Boolean.getBoolean(SKIP_DEFAULT); + } + + public boolean dryRun() { + return getFlag(DRY_RUN); + } + + public String getInfoGewFile() { + return System.getProperty(INFO_GEW_FILE); + } + + public String getAnnotationTypes() { + return System.getProperty(ANNOTATION_TYPES); + } + + public boolean skipGauges() { + return getFlag(SKIP_GAUGES); + } + + public boolean skipHistoricalDischargeTables() { + return getFlag(SKIP_HISTORICAL_DISCHARGE_TABLES); + } + + public boolean skipBWASTR() { + return getFlag(SKIP_BWASTR); + } + + public boolean skipAnnotations() { + return getFlag(SKIP_ANNOTATIONS); + } + + public boolean skipPRFs() { + return getFlag(SKIP_PRFS); + } + + public boolean skipDA50s() { + return getFlag(SKIP_DA50S); + } + + public boolean skipW80CSVs() { + return getFlag(SKIP_W80_CSVS); + } + + public boolean skipW80s() { + return getFlag(SKIP_W80S); + } + + public boolean skipHYKs() { + return getFlag(SKIP_HYKS); + } + + public boolean skipWst() { + return getFlag(SKIP_WST); + } + + public boolean skipExtraWsts() { + return getFlag(SKIP_EXTRA_WSTS); + } + + public boolean skipFixations() { + return getFlag(SKIP_FIXATIONS); + } + + public boolean skipOfficialLines() { + return getFlag(SKIP_OFFICIAL_LINES); + } + + public boolean skipFloodWater() { + return getFlag(SKIP_FLOOD_WATER); + } + + public boolean skipFloodProtection() { + return getFlag(SKIP_FLOOD_PROTECTION); + } + + public boolean skipDA66s() { + return getFlag(SKIP_DA66S); + } + + public boolean skipBedHeightSingle() { + return getFlag(SKIP_BED_HEIGHT_SINGLE); + } + + public boolean skipBedHeightEpoch() { + return getFlag(SKIP_BED_HEIGHT_EPOCH); + } + + public boolean skipSedimentDensity() { + return getFlag(SKIP_SEDIMENT_DENSITY); + } + + public boolean skipMorphologicalWidth() { + return getFlag(SKIP_MORPHOLOGICAL_WIDTH); + } + + public boolean skipFlowVelocity() { + return getFlag(SKIP_FLOW_VELOCITY); + } + + public boolean skipSedimentYield() { + return getFlag(SKIP_SEDIMENT_YIELD); + } + + public boolean skipWaterlevels() { + return getFlag(SKIP_WATERLEVELS); + } + + public boolean skipWaterlevelDifferences() { + return getFlag(SKIP_WATERLEVEL_DIFFERENCES); + } + + public boolean skipMeasurementStations() { + return getFlag(SKIP_MEASUREMENT_STATIONS); + } + + public boolean skipSQRelation() { + return getFlag(SKIP_SQ_RELATION); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportAnnotation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,146 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Annotation; +import de.intevation.flys.model.AnnotationType; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.Position; +import de.intevation.flys.model.Attribute; +import de.intevation.flys.model.River; +import de.intevation.flys.model.Edge; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportAnnotation +implements Comparable<ImportAnnotation> +{ + protected ImportAttribute attribute; + protected ImportPosition position; + protected ImportRange range; + protected ImportEdge edge; + protected ImportAnnotationType type; + + protected Annotation peer; + + public ImportAnnotation() { + } + + public ImportAnnotation( + ImportAttribute attribute, + ImportPosition position, + ImportRange range, + ImportEdge edge, + ImportAnnotationType type + ) { + this.attribute = attribute; + this.position = position; + this.range = range; + this.edge = edge; + this.type = type; + } + + public int compareTo(ImportAnnotation other) { + int d = attribute.compareTo(other.attribute); + if (d != 0) { + return d; + } + + if ((d = position.compareTo(other.position)) != 0) { + return d; + } + + if ((d = range.compareTo(other.range)) != 0) { + return d; + } + + if (edge == null && other.edge != null) return -1; + if (edge != null && other.edge == null) return +1; + if (edge == null && other.edge == null) return 0; + + if ((d = edge.compareTo(other.edge)) != 0) { + return d; + } + + if (type == null && other.type != null) return -1; + if (type != null && other.type == null) return +1; + if (type == null && other.type == null) return 0; + + return type.compareTo(other.type); + } + + public ImportAttribute getAttribute() { + return attribute; + } + + public void setAttribute(ImportAttribute attribute) { + this.attribute = attribute; + } + + public ImportPosition getPosition() { + return position; + } + + public void setPosition(ImportPosition position) { + this.position = position; + } + + public ImportRange getRange() { + return range; + } + + public void setRange(ImportRange range) { + this.range = range; + } + + public ImportEdge getEdge() { + return edge; + } + + public void setEdge(ImportEdge edge) { + this.edge = edge; + } + + public ImportAnnotationType getType() { + return type; + } + + public void setType(ImportAnnotationType type) { + this.type = type; + } + + public Annotation getPeer(River river) { + if (peer == null) { + Range r = range.getPeer(river); + Attribute a = attribute.getPeer(); + Position p = position.getPeer(); + Edge e = edge != null ? edge.getPeer() : null; + AnnotationType t = type != null ? type.getPeer() : null; + + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from Annotation where " + + "range=:range and " + + "attribute=:attribute and " + + "position=:position and " + + "edge=:edge and " + + "type=:type"); + query.setParameter("range", r); + query.setParameter("attribute", a); + query.setParameter("position", p); + query.setParameter("edge", e); + query.setParameter("type", t); + List<Annotation> annotations = query.list(); + if (annotations.isEmpty()) { + peer = new Annotation(r, a, p, e, t); + session.save(peer); + } + else { + peer = annotations.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportAnnotationType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,54 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.AnnotationType; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportAnnotationType +implements Comparable<ImportAnnotationType> +{ + protected String name; + protected AnnotationType peer; + + public ImportAnnotationType() { + } + + public ImportAnnotationType(String name) { + this.name = name; + } + + public int compareTo(ImportAnnotationType other) { + return name.compareTo(other.name); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public AnnotationType getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from AnnotationType where name=:name"); + query.setParameter("name", name); + List<AnnotationType> types = query.list(); + if (types.isEmpty()) { + peer = new AnnotationType(name); + session.save(peer); + } + else { + peer = types.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportAttribute.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,65 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Attribute; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportAttribute +implements Comparable<ImportAttribute> +{ + protected String value; + + protected Attribute peer; + + public ImportAttribute() { + } + + public ImportAttribute(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public int compareTo(ImportAttribute other) { + return value.compareTo(other.value); + } + + @Override + public boolean equals(Object other) { + if (other == this) return true; + if (!(other instanceof ImportAttribute)) return false; + return value.equals(((ImportAttribute)other).value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + public Attribute getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from Attribute where value=:value"); + query.setString("value", value); + List<Attribute> attributes = query.list(); + if (attributes.isEmpty()) { + peer = new Attribute(value); + session.save(peer); + } + else { + peer = attributes.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeight.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,44 @@ +package de.intevation.flys.importer; + + +import java.sql.SQLException; + +import org.hibernate.exception.ConstraintViolationException; + +import de.intevation.flys.model.River; + + +public interface ImportBedHeight { + + String getDescription(); + + void addValue(ImportBedHeightValue value); + + void storeDependencies(River river) + throws SQLException, ConstraintViolationException; + + Object getPeer(River river); + + int getValueCount(); + + void setYear(int year); + + void setTimeInterval(ImportTimeInterval timeInterval); + + void setSoundingWidth(int soundingWidth); + + void setDescription(String description); + + void setEvaluationBy(String evaluationBy); + + void setRange(ImportRange range); + + void setType(ImportBedHeightType type); + + void setLocationSystem(ImportLocationSystem locationSystem); + + void setCurElevationModel(ImportElevationModel model); + + void setOldElevationModel(ImportElevationModel model); +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightEpoch.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,198 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.Query; +import org.hibernate.Session; + +import de.intevation.flys.model.BedHeightEpoch; +import de.intevation.flys.model.ElevationModel; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; +import de.intevation.flys.model.TimeInterval; + + +/** Import Bed Height Data, 'epoch' type from csv file. */ +public class ImportBedHeightEpoch implements ImportBedHeight { + + /** Private logger. */ + private static Logger log = Logger.getLogger(ImportBedHeightEpoch.class); + + protected String evaluationBy; + + /** De facto the file name. */ + protected String description; + + protected ImportTimeInterval timeInterval; + protected ImportRange range; + protected ImportElevationModel curElevationModel; + protected ImportElevationModel oldElevationModel; + + protected List<ImportBedHeightEpochValue> values; + + protected BedHeightEpoch peer; + + public ImportBedHeightEpoch(String description) { + this.description = description; + this.values = new ArrayList<ImportBedHeightEpochValue>(); + } + + public String getDescription() { + return description; + } + + public int getValueCount() { + return values.size(); + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + public void setEvaluationBy(String evaluationBy) { + this.evaluationBy = evaluationBy; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setRange(ImportRange range) { + this.range = range; + } + + public void setCurElevationModel(ImportElevationModel curElevationModel) { + this.curElevationModel = curElevationModel; + } + + public void setOldElevationModel(ImportElevationModel oldElevationModel) { + this.oldElevationModel = oldElevationModel; + } + + /** Does nothing. */ + public void setYear(int year) { + // do nothing + } + + /** Does nothing. */ + public void setSoundingWidth(int soundingWidth) { + // do nothing + } + + + /** Does nothing. */ + public void setLocationSystem(ImportLocationSystem locationSystem) { + // do nothing + } + + + /** Does nothing. */ + public void setType(ImportBedHeightType type) { + // do nothing + } + + @Override + public void addValue(ImportBedHeightValue value) { + values.add((ImportBedHeightEpochValue) value); + } + + @Override + public void storeDependencies(River river) { + log.info("Store dependencies for epoch: '" + getDescription() + "'"); + + BedHeightEpoch peer = getPeer(river); + + if (curElevationModel != null) { + curElevationModel.storeDependencies(); + } + + if (oldElevationModel != null) { + oldElevationModel.storeDependencies(); + } + + if (peer != null) { + log.debug("store values now..."); + + for (ImportBedHeightEpochValue value : values) { + value.storeDependencies(peer); + } + } + + Session session = ImporterSession.getInstance().getDatabaseSession(); + session.flush(); + } + + /** + * Asserts all dependent entities (ElevationModel, TimeInterval, Range, + * BedHeighEpoch) are in db and returns bound (either newly created or + * freshly fetched) BedHeightEpoch. + */ + @Override + public BedHeightEpoch getPeer(River river) { + if (peer == null) { + ElevationModel theCurModel = null; + if (curElevationModel != null) { + curElevationModel.storeDependencies(); + theCurModel = curElevationModel.getPeer(); + } + + if (theCurModel == null) { + log.warn("BHE: Skip file - invalid current elevation model."); + return null; + } + + TimeInterval theTime = null; + if (timeInterval != null) { + theTime = timeInterval.getPeer(); + } + + if (theTime == null) { + log.warn("BHE: Skip file - invalid time range."); + return null; + } + + Range theRange = range != null ? range.getPeer(river) : null; + + if (theRange == null) { + log.warn("BHE: invalid km range."); + } + + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + Query query = session.createQuery("from BedHeightEpoch where " + + " river=:river and " + " timeInterval=:timeInterval and " + + " curElevationModel=:curElevationModel and " + + " range=:range and " + " evaluationBy=:evaluationBy and " + + " description=:description"); + + query.setParameter("river", river); + query.setParameter("timeInterval", theTime); + query.setParameter("curElevationModel", theCurModel); + query.setParameter("range", theRange); + query.setParameter("evaluationBy", evaluationBy); + query.setParameter("description", description); + + List<BedHeightEpoch> bedHeights = query.list(); + + if (bedHeights.isEmpty()) { + log.info("Create new BedHeightEpoch DB instance."); + + peer = new BedHeightEpoch(river, theTime, theRange, + theCurModel, + oldElevationModel != null ? oldElevationModel.getPeer() + : null, evaluationBy, description); + + session.save(peer); + } + else { + peer = bedHeights.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightEpochValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,75 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.BedHeightEpoch; +import de.intevation.flys.model.BedHeightEpochValue; + + +public class ImportBedHeightEpochValue implements ImportBedHeightValue { + + private static final Logger log = + Logger.getLogger(ImportBedHeightEpochValue.class); + + + private BigDecimal station; + private BigDecimal height; + + private BedHeightEpochValue peer; + + + public ImportBedHeightEpochValue() { + } + + + public ImportBedHeightEpochValue(BigDecimal station, BigDecimal height) { + this.station = station; + this.height = height; + } + + + public void storeDependencies(BedHeightEpoch bedHeight) { + getPeer(bedHeight); + } + + + public BedHeightEpochValue getPeer(BedHeightEpoch bedHeight) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from BedHeightEpochValue where " + + " bedHeight=:bedHeight and " + + " station=:station and " + + " height=:height"); + + query.setParameter("bedHeight", bedHeight); + query.setParameter("station", station); + query.setParameter("height", height); + + List<BedHeightEpochValue> values = query.list(); + + if (values.isEmpty()) { + peer = new BedHeightEpochValue( + bedHeight, + station, + height + ); + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightSingle.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,198 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.BedHeightSingle; +import de.intevation.flys.model.BedHeightType; +import de.intevation.flys.model.ElevationModel; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; + + +public class ImportBedHeightSingle implements ImportBedHeight +{ + private static Logger log = Logger.getLogger(ImportBedHeightSingle.class); + + protected Integer year; + protected int soundingWidth; + + protected String evaluationBy; + protected String description; + + protected ImportRange range; + protected ImportBedHeightType type; + protected ImportLocationSystem locationSystem; + protected ImportElevationModel curElevationModel; + protected ImportElevationModel oldElevationModel; + + protected List<ImportBedHeightSingleValue> values; + + protected BedHeightSingle peer; + + + public ImportBedHeightSingle(String description) { + this.description = description; + this.values = new ArrayList<ImportBedHeightSingleValue>(); + } + + + public String getDescription() { + return description; + } + + public int getValueCount() { + return values.size(); + } + + + public void setYear(int year) { + this.year = year; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + // do nothing + } + + public void setSoundingWidth(int soundingWidth) { + this.soundingWidth = soundingWidth; + } + + public void setEvaluationBy(String evaluationBy) { + this.evaluationBy = evaluationBy; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setRange(ImportRange range) { + this.range = range; + } + + public void setType(ImportBedHeightType type) { + this.type = type; + } + + public void setLocationSystem(ImportLocationSystem locationSystem) { + this.locationSystem = locationSystem; + } + + public void setCurElevationModel(ImportElevationModel curElevationModel) { + this.curElevationModel = curElevationModel; + } + + public void setOldElevationModel(ImportElevationModel oldElevationModel) { + this.oldElevationModel = oldElevationModel; + } + + @Override + public void addValue(ImportBedHeightValue value) { + values.add((ImportBedHeightSingleValue) value); + } + + @Override + public void storeDependencies(River river) { + log.info("Store dependencies for single: '" + getDescription() + "'"); + + if (type != null) { + type.storeDependencies(); + } + + if (locationSystem != null) { + locationSystem.storeDependencies(); + } + + if (curElevationModel != null) { + curElevationModel.storeDependencies(); + } + + if (oldElevationModel != null) { + oldElevationModel.storeDependencies(); + } + + BedHeightSingle peer = getPeer(river); + + if (peer != null) { + for (ImportBedHeightSingleValue value: values) { + value.storeDependencies(peer); + } + } + + Session session = ImporterSession.getInstance().getDatabaseSession(); + session.flush(); + } + + @Override + public BedHeightSingle getPeer(River river) { + if (peer == null) { + BedHeightType theType = type != null ? type.getPeer() : null; + ElevationModel theCurModel = curElevationModel.getPeer(); + Range theRange = range != null ? range.getPeer(river) : null; + + if (theType == null) { + log.warn("BHS: No bed height type given. Skip file '" + + description + "'"); + return null; + } + + if (theCurModel == null) { + log.warn("BHS: No elevation model given. Skip file '" + + description + "'"); + return null; + } + + if (theRange == null) { + log.warn("BHS: No km-range given: '" + + description + "'"); + } + + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from BedHeightSingle where " + + "river=:river and year=:year and soundingWidth=:soundingWidth " + + "and type=:type and locationSystem=:locationSystem and " + + "curElevationModel=:curElevationModel and range=:range"); + + query.setParameter("river", river); + query.setParameter("year", year); + query.setParameter("soundingWidth", soundingWidth); + query.setParameter("type", theType); + query.setParameter("locationSystem", locationSystem.getPeer()); + query.setParameter("curElevationModel", theCurModel); + query.setParameter("range", range.getPeer(river)); + + List<BedHeightSingle> bedHeights = query.list(); + if (bedHeights.isEmpty()) { + log.info("Create new BedHeightSingle DB instance."); + + peer = new BedHeightSingle( + river, + year, + soundingWidth, + theType, + locationSystem.getPeer(), + theCurModel, + oldElevationModel != null ? oldElevationModel.getPeer() : null, + range.getPeer(river), + evaluationBy, + description + ); + + session.save(peer); + } + else { + peer = bedHeights.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightSingleValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,105 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.BedHeightSingle; +import de.intevation.flys.model.BedHeightSingleValue; + + +public class ImportBedHeightSingleValue implements ImportBedHeightValue { + + private static final Logger log = + Logger.getLogger(ImportBedHeightSingleValue.class); + + + protected ImportBedHeightSingle bedHeight; + + protected BigDecimal station; + protected BigDecimal height; + protected BigDecimal uncertainty; + protected BigDecimal dataGap; + protected BigDecimal soundingWidth; + protected BigDecimal width; + + protected BedHeightSingleValue peer; + + + public ImportBedHeightSingleValue( + ImportBedHeightSingle bedHeight, + BigDecimal station, + BigDecimal height, + BigDecimal uncertainty, + BigDecimal dataGap, + BigDecimal soundingWidth, + BigDecimal width + ) { + this.bedHeight = bedHeight; + this.station = station; + this.height = height; + this.uncertainty = uncertainty; + this.dataGap = dataGap; + this.soundingWidth = soundingWidth; + this.width = width; + } + + + public void storeDependencies(BedHeightSingle bedHeight) { + getPeer(bedHeight); + } + + + /** + * Add this value to database or return database bound Value, assuring + * that the BedHeightSingle exists in db already. + */ + public BedHeightSingleValue getPeer(BedHeightSingle bedHeight) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from BedHeightSingleValue where " + + " bedHeight=:bedHeight and " + + " station=:station and " + + " height=:height and " + + " uncertainty=:uncertainty and " + + " dataGap=:dataGap and " + + " soundingWidth=:soundingWidth and " + + " width=:width"); + + query.setParameter("bedHeight", bedHeight); + query.setParameter("station", station); + query.setParameter("height", height); + query.setParameter("uncertainty", uncertainty); + query.setParameter("dataGap", dataGap); + query.setParameter("soundingWidth", soundingWidth); + query.setParameter("width", width); + + List<BedHeightSingleValue> values = query.list(); + if (values.isEmpty()) { + peer = new BedHeightSingleValue( + bedHeight, + station, + height, + uncertainty, + dataGap, + soundingWidth, + width + ); + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,61 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.BedHeightType; + + +public class ImportBedHeightType { + + private static final Logger log = + Logger.getLogger(ImportBedHeightType.class); + + protected String name; + + protected BedHeightType peer; + + public ImportBedHeightType(BedHeightType peer) { + this.peer = peer; + name = peer.getName(); + } + + + public ImportBedHeightType(String name) { + this.name = name; + } + + + public void storeDependencies() { + getPeer(); + } + + + public BedHeightType getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from BedHeightType where name=:name and description=:description"); + + query.setParameter("name", name); + + List<BedHeightType> types = query.list(); + + if (types.isEmpty()) { + peer = new BedHeightType(name); + session.save(peer); + } + else { + peer = types.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportBedHeightValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,7 @@ +package de.intevation.flys.importer; + + +public interface ImportBedHeightValue { + +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportCrossSection.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,120 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.River; +import de.intevation.flys.model.CrossSection; +import de.intevation.flys.model.TimeInterval; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +import org.apache.log4j.Logger; + +/** CrossSection to be imported, holds list of ImportCrossSectionLines. */ +public class ImportCrossSection +{ + private static Logger log = Logger.getLogger(ImportRiver.class); + + protected ImportRiver river; + protected String description; + protected ImportTimeInterval timeInterval; + protected List<ImportCrossSectionLine> lines; + + protected CrossSection peer; + + public ImportCrossSection() { + } + + public ImportCrossSection( + ImportRiver river, + String description, + ImportTimeInterval timeInterval, + List<ImportCrossSectionLine> lines + ) { + this.river = river; + this.description = description; + this.timeInterval = timeInterval; + this.lines = lines; + wireWithLines(); + } + + public void wireWithLines() { + for (ImportCrossSectionLine line: lines) { + line.setCrossSection(this); + } + } + + public ImportRiver getRiver() { + return river; + } + + public void setRiver(ImportRiver river) { + this.river = river; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ImportTimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + public void storeDependencies() { + + log.info("store cross section '" + description + "'"); + + getPeer(); + + int i = 1, N = lines.size(); + + for (ImportCrossSectionLine line: lines) { + line.storeDependencies(); + log.info(" stored " + i + " lines. remaining: " + (N-i)); + ++i; + } + } + + public CrossSection getPeer() { + + if (peer == null) { + River r = river.getPeer(); + TimeInterval t = timeInterval != null + ? timeInterval.getPeer() + : null; + + Session session = + ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from CrossSection where " + + "river=:r and " + + "timeInterval=:t and " + + "description=:d"); + + query.setParameter("r", r); + query.setParameter("t", t); + query.setParameter("d", description); + + List<CrossSection> crossSections = query.list(); + if (crossSections.isEmpty()) { + peer = new CrossSection(r, t, description); + session.save(peer); + } + else { + peer = crossSections.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportCrossSectionLine.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,127 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.CrossSection; +import de.intevation.flys.model.CrossSectionPoint; +import de.intevation.flys.model.CrossSectionLine; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; +import java.util.Comparator; +import java.util.Map; +import java.util.TreeMap; + +/** + * A CrossSectionLine (containing points) ready to be transformed into a mapped + * object and written to db (used in importer). + */ +public class ImportCrossSectionLine +{ + public static final Comparator<CrossSectionPoint> INDEX_CMP = + new Comparator<CrossSectionPoint>() { + public int compare(CrossSectionPoint a, CrossSectionPoint b) { + return a.getColPos().compareTo(b.getColPos()); + } + }; + + protected Double km; + protected ImportCrossSection crossSection; + protected List<XY> points; + + protected CrossSectionLine peer; + + public ImportCrossSectionLine() { + } + + public ImportCrossSectionLine(Double km, List<XY> points) { + this.km = km; + this.points = points; + } + + public ImportCrossSection getCrossSection() { + return crossSection; + } + + public void setCrossSection(ImportCrossSection crossSection) { + this.crossSection = crossSection; + } + + public Double getKm() { + return km; + } + + public void setKm(Double km) { + this.km = km; + } + + public void storeDependencies() { + storePoints(); + } + + + /** Write a line and its points. */ + protected void storePoints() { + CrossSectionLine csl = getPeer(); + + Map<CrossSectionPoint, CrossSectionPoint> map = + new TreeMap<CrossSectionPoint, CrossSectionPoint>(INDEX_CMP); + + // Build index for faster (index) collision lookup. + List<CrossSectionPoint> ps = csl.getPoints(); + if (ps != null) { + for (CrossSectionPoint point: ps) { + map.put(point, point); + } + } + + Session session = + ImporterSession.getInstance().getDatabaseSession(); + + CrossSectionPoint key = new CrossSectionPoint(); + + // Somehow it looks as if even with the map it is still possible that + // multiple points with same id enter hibernate (and then violate a + // constraint). -> TODO + for (XY xy: points) { + key.setColPos(xy.getIndex()); + CrossSectionPoint csp = map.get(key); + if (csp == null) { // create new + csp = new CrossSectionPoint( + csl, key.getColPos(), + Double.valueOf(xy.getX()), + Double.valueOf(xy.getY())); + } + else { // update old + csp.setX(Double.valueOf(xy.getX())); + csp.setY(Double.valueOf(xy.getY())); + } + session.save(csp); + } + } + + public CrossSectionLine getPeer() { + if (peer == null) { + CrossSection cs = crossSection.getPeer(); + + Session session = + ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from CrossSectionLine where crossSection=:cs and km=:km"); + query.setParameter("cs", cs); + query.setParameter("km", km); + + List<CrossSectionLine> lines = query.list(); + if (lines.isEmpty()) { + peer = new CrossSectionLine(cs, km); + session.save(peer); + } + else { + peer = lines.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportDepth.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,70 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.Depth; + + +public class ImportDepth { + + private static Logger log = Logger.getLogger(ImportDepth.class); + + + protected Depth peer; + + protected BigDecimal lower; + protected BigDecimal upper; + + + public ImportDepth(BigDecimal lower, BigDecimal upper) { + this.lower = lower; + this.upper = upper; + } + + + public void storeDependencies() { + log.info("store dependencies"); + + getPeer(); + } + + + public Depth getPeer() { + log.info("get peer"); + + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from Depth where " + + " lower=:lower and " + + " upper=:upper"); + + query.setParameter("lower", lower); + query.setParameter("upper", upper); + + List<Depth> depths = query.list(); + + if (depths.isEmpty()) { + log.debug("Create new Depth DB instance."); + + peer = new Depth(lower, upper); + + session.save(peer); + } + else { + peer = depths.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportDischargeTable.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,116 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.DischargeTable; +import de.intevation.flys.model.Gauge; +import de.intevation.flys.model.TimeInterval; + +import org.apache.log4j.Logger; + +public class ImportDischargeTable +{ + private static Logger log = Logger.getLogger(ImportDischargeTable.class); + + protected DischargeTable peer; + + protected String description; + + protected Integer kind; + + protected List<ImportDischargeTableValue> dischargeTableValues; + + protected ImportTimeInterval timeInterval; + + public ImportDischargeTable() { + this(0, null); + } + + public ImportDischargeTable(int kind, String description) { + this.kind = kind; + this.description = description; + dischargeTableValues = new ArrayList<ImportDischargeTableValue>(); + } + + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public void addDischargeTableValue(ImportDischargeTableValue value) { + dischargeTableValues.add(value); + } + + + public void setDischargeTableValues(List<ImportDischargeTableValue> values){ + this.dischargeTableValues = values; + } + + + public List<ImportDischargeTableValue> getDischargeTableValues() { + return dischargeTableValues; + } + + public ImportTimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + + public DischargeTable getPeer(Gauge gauge) { + if (peer == null) { + TimeInterval ti = timeInterval != null + ? timeInterval.getPeer() + : null; + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from DischargeTable where " + + "gauge.id=:gauge and kind=:kind and " + + "description=:description and timeInterval=:interval"); + query.setParameter("gauge", gauge.getId()); + query.setParameter("description", description); + query.setParameter("kind", kind); + query.setParameter("interval", ti); + + List<DischargeTable> dischargeTables = query.list(); + if (dischargeTables.isEmpty()) { + peer = new DischargeTable(gauge, description, null, kind, ti); + session.save(peer); + } + else { + peer = dischargeTables.get(0); + } + } + + return peer; + } + + + public void storeDependencies(Gauge gauge) { + log.info("store discharge table '" + description + "'"); + storeDischargeTableValues(gauge); + } + + + public void storeDischargeTableValues(Gauge gauge) { + DischargeTable dischargeTable = getPeer(gauge); + + for (ImportDischargeTableValue value: dischargeTableValues) { + value.getPeer(dischargeTable); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportDischargeTableValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,34 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import de.intevation.flys.model.DischargeTable; +import de.intevation.flys.model.DischargeTableValue; + + +public class ImportDischargeTableValue +{ + private BigDecimal q; + private BigDecimal w; + + private DischargeTableValue peer; + + public ImportDischargeTableValue() { + } + + + public ImportDischargeTableValue(BigDecimal q, BigDecimal w) { + this.q = q; + this.w = w; + } + + + public DischargeTableValue getPeer(DischargeTable dischargeTable) { + if (peer == null) { + peer = ImporterSession.getInstance() + .getDischargeTableValue(dischargeTable, q, w); + } + + return peer; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportDischargeZone.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,86 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.DischargeZone; +import de.intevation.flys.model.River; + + +public class ImportDischargeZone { + + private static final Logger log = + Logger.getLogger(ImportDischargeZone.class); + + + private String gaugeName; + + private BigDecimal value; + + private String lowerDischarge; + private String upperDischarge; + + private DischargeZone peer; + + + public ImportDischargeZone( + String gaugeName, + BigDecimal value, + String lowerDischarge, + String upperDischarge + ) { + this.gaugeName = gaugeName; + this.value = value; + this.lowerDischarge = lowerDischarge; + this.upperDischarge = upperDischarge; + } + + + public void storeDependencies(River river) { + log.debug("store dependencies"); + + getPeer(river); + } + + + public DischargeZone getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from DischargeZone where " + + " river=:river and " + + " gaugeName=:gaugeName and " + + " value=:value" + ); + + query.setParameter("river", river); + query.setParameter("gaugeName", gaugeName); + query.setParameter("value", value); + + List<DischargeZone> zone = query.list(); + + if (zone.isEmpty()) { + peer = new DischargeZone( + river, + gaugeName, + value, + lowerDischarge, + upperDischarge); + + session.save(peer); + } + else { + peer = zone.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportEdge.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,75 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Edge; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +import java.math.BigDecimal; + +public class ImportEdge +implements Comparable<ImportEdge> +{ + protected BigDecimal top; + protected BigDecimal bottom; + + protected Edge peer; + + public ImportEdge() { + } + + public ImportEdge(BigDecimal top, BigDecimal bottom) { + this.top = top; + this.bottom = bottom; + } + + public BigDecimal getTop() { + return top; + } + + public void setTop(BigDecimal top) { + this.top = top; + } + + public BigDecimal getBottom() { + return bottom; + } + + public void setBottom(BigDecimal bottom) { + this.bottom = bottom; + } + + private static final int compare(BigDecimal a, BigDecimal b) { + if (a == null && b != null) return -1; + if (a != null && b == null) return +1; + if (a == null && b == null) return 0; + return a.compareTo(b); + } + + public int compareTo(ImportEdge other) { + int cmp = compare(top, other.top); + return cmp != 0 ? cmp : compare(bottom, other.bottom); + } + + public Edge getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from Edge where top=:top and bottom=:bottom"); + query.setParameter("top", top); + query.setParameter("bottom", bottom); + List<Edge> edges = query.list(); + if (edges.isEmpty()) { + peer = new Edge(top, bottom); + session.save(peer); + } + else { + peer = edges.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportElevationModel.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,64 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.ElevationModel; + + +public class ImportElevationModel { + + private static final Logger log = + Logger.getLogger(ImportElevationModel.class); + + protected String name; + + protected ImportUnit unit; + + protected ElevationModel peer; + + + public ImportElevationModel(String name, ImportUnit unit) { + this.name = name; + this.unit = unit; + } + + + public void storeDependencies() { + ElevationModel model = getPeer(); + } + + public ElevationModel getPeer() { + if (unit == null) { + log.warn("No elevation model specified."); + return null; + } + + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from ElevationModel where " + + "name=:name and unit=:unit"); + query.setParameter("name", name); + query.setParameter("unit", unit.getPeer()); + List<ElevationModel> models = query.list(); + + if (models.isEmpty()) { + log.info("Create new ElevationModel DB instance."); + + peer = new ElevationModel(name, unit.getPeer()); + session.save(peer); + } + else { + peer = models.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportFlowVelocityMeasurement.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,82 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.FlowVelocityMeasurement; +import de.intevation.flys.model.River; + + +public class ImportFlowVelocityMeasurement { + + private static final Logger log = Logger + .getLogger(ImportFlowVelocityMeasurement.class); + + private String description; + + private List<ImportFlowVelocityMeasurementValue> values; + + private FlowVelocityMeasurement peer; + + public ImportFlowVelocityMeasurement() { + this(null); + } + + public ImportFlowVelocityMeasurement(String description) { + this.description = description; + this.values = new ArrayList<ImportFlowVelocityMeasurementValue>(); + } + + public void setDescription(String description) { + this.description = description; + } + + public void addValue(ImportFlowVelocityMeasurementValue value) { + this.values.add(value); + } + + public void storeDependencies(River river) { + log.debug("store dependencies"); + + FlowVelocityMeasurement peer = getPeer(river); + + if (peer != null) { + for (ImportFlowVelocityMeasurementValue value : values) { + value.storeDependencies(peer); + } + } + } + + public FlowVelocityMeasurement getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + Query query = session + .createQuery("from FlowVelocityMeasurement where " + + " river=:river and " + " description=:description"); + + query.setParameter("river", river); + query.setParameter("description", description); + + List<FlowVelocityMeasurement> measurement = query.list(); + + if (measurement.isEmpty()) { + peer = new FlowVelocityMeasurement(river, description); + + session.save(peer); + } + else { + peer = measurement.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportFlowVelocityMeasurementValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,97 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.Date; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.FlowVelocityMeasurement; +import de.intevation.flys.model.FlowVelocityMeasurementValue; + + +public class ImportFlowVelocityMeasurementValue { + + private static final Logger log = + Logger.getLogger(ImportFlowVelocityMeasurementValue.class); + + + private Date datetime; + + private String description; + + private BigDecimal station; + private BigDecimal w; + private BigDecimal q; + private BigDecimal v; + + private FlowVelocityMeasurementValue peer; + + + public ImportFlowVelocityMeasurementValue( + Date datetime, + BigDecimal station, + BigDecimal w, + BigDecimal q, + BigDecimal v, + String description + ) { + this.datetime = datetime; + this.station = station; + this.w = w; + this.q = q; + this.v = v; + this.description = description; + } + + + + public void storeDependencies(FlowVelocityMeasurement measurement) { + log.debug("store dependencies"); + + getPeer(measurement); + } + + + public FlowVelocityMeasurementValue getPeer(FlowVelocityMeasurement m) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from FlowVelocityMeasurementValue where " + + " measurement=:measurement and " + + " station=:station and " + + " datetime=:datetime" + ); + + query.setParameter("measurement", m); + query.setParameter("station", station); + query.setParameter("datetime", datetime); + + List<FlowVelocityMeasurementValue> values = query.list(); + + if (values.isEmpty()) { + peer = new FlowVelocityMeasurementValue( + m, + datetime, + station, + w, + q, + v, + description); + + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportFlowVelocityModel.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,109 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.DischargeZone; +import de.intevation.flys.model.FlowVelocityModel; +import de.intevation.flys.model.River; + + +public class ImportFlowVelocityModel { + + private static final Logger log = Logger + .getLogger(ImportFlowVelocityModel.class); + + private String description; + + private ImportDischargeZone dischargeZone; + + private List<ImportFlowVelocityModelValue> values; + + private FlowVelocityModel peer; + + public ImportFlowVelocityModel() { + values = new ArrayList<ImportFlowVelocityModelValue>(); + } + + public ImportFlowVelocityModel(String description) { + this(); + + this.description = description; + } + + public ImportFlowVelocityModel(ImportDischargeZone dischargeZone, + String description) { + this(); + + this.dischargeZone = dischargeZone; + this.description = description; + } + + public void setDischargeZone(ImportDischargeZone dischargeZone) { + this.dischargeZone = dischargeZone; + } + + public void setDescription(String description) { + this.description = description; + } + + public void addValue(ImportFlowVelocityModelValue value) { + this.values.add(value); + } + + public void storeDependencies(River river) { + log.debug("store dependencies"); + + if (dischargeZone == null) { + log.warn("skip flow velocity model: No discharge zone specified."); + return; + } + + dischargeZone.storeDependencies(river); + + FlowVelocityModel peer = getPeer(river); + + if (peer != null) { + int i = 0; + + for (ImportFlowVelocityModelValue value : values) { + value.storeDependencies(peer); + i++; + } + + log.info("stored " + i + " flow velocity model values."); + } + } + + public FlowVelocityModel getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + DischargeZone zone = dischargeZone.getPeer(river); + + Query query = session.createQuery("from FlowVelocityModel where " + + " dischargeZone=:dischargeZone"); + + query.setParameter("dischargeZone", zone); + + List<FlowVelocityModel> model = query.list(); + + if (model.isEmpty()) { + peer = new FlowVelocityModel(zone, description); + session.save(peer); + } + else { + peer = model.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportFlowVelocityModelValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,74 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.FlowVelocityModel; +import de.intevation.flys.model.FlowVelocityModelValue; + + +public class ImportFlowVelocityModelValue { + + private BigDecimal station; + private BigDecimal q; + private BigDecimal totalChannel; + private BigDecimal mainChannel; + private BigDecimal shearStress; + + private FlowVelocityModelValue peer; + + + public ImportFlowVelocityModelValue( + BigDecimal station, + BigDecimal q, + BigDecimal totalChannel, + BigDecimal mainChannel, + BigDecimal shearStress + ) { + this.station = station; + this.q = q; + this.totalChannel = totalChannel; + this.mainChannel = mainChannel; + this.shearStress = shearStress; + } + + + public void storeDependencies(FlowVelocityModel model) { + getPeer(model); + } + + + public FlowVelocityModelValue getPeer(FlowVelocityModel model) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from FlowVelocityModelValue where " + + " flowVelocity=:model and " + + " station between :station - 0.00001 and :station + 0.00001" + ); + + query.setParameter("model", model); + query.setParameter("station", station.doubleValue()); + + List<FlowVelocityModelValue> values = query.list(); + + if (values.isEmpty()) { + peer = new FlowVelocityModelValue( + model, station, q, totalChannel, mainChannel, shearStress); + + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportGauge.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,274 @@ +package de.intevation.flys.importer; + +import java.io.File; + +import java.util.ArrayList; +import java.util.List; + +import java.math.BigDecimal; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.model.River; +import de.intevation.flys.model.Gauge; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.io.IOException; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.parsers.AtFileParser; +import de.intevation.flys.importer.parsers.StaFileParser; + +/** Gauge not in DB. */ +public class ImportGauge +{ + private static Logger log = Logger.getLogger(ImportGauge.class); + + public static final String HISTORICAL_DISCHARGE_TABLES = + "Histor.Abflusstafeln"; + + protected ImportRange range; + + protected File staFile; + protected File atFile; + + protected String name; + protected BigDecimal aeo; + protected BigDecimal datum; + protected BigDecimal station; + protected Long officialNumber; + + protected Gauge peer; + + protected ImportDischargeTable dischargeTable; + + protected List<ImportMainValueType> mainValueTypes; + protected List<ImportNamedMainValue> namedMainValues; + protected List<ImportMainValue> mainValues; + protected List<ImportDischargeTable> historicalDischargeTables; + + public ImportGauge() { + historicalDischargeTables = new ArrayList<ImportDischargeTable>(); + } + + public ImportGauge(ImportRange range, File staFile, File atFile) { + this(); + this.range = range; + this.staFile = staFile; + this.atFile = atFile; + } + + public void setRange(ImportRange range) { + this.range = range; + } + + public void setStaFile(File staFile) { + this.staFile = staFile; + } + + public File getStaFile() { + return staFile; + } + + public void setAtFile(File atFile) { + this.atFile = atFile; + } + + public File getAtFile() { + return atFile; + } + + public BigDecimal getAeo() { + return aeo; + } + + public void setAeo(BigDecimal aeo) { + this.aeo = aeo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigDecimal getDatum() { + return datum; + } + + public void setDatum(BigDecimal datum) { + this.datum = datum; + } + + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + public Long getOfficialNumber() { + return officialNumber; + } + + public void setOfficialNumber(Long officialNumber) { + this.officialNumber = officialNumber; + } + + public ImportDischargeTable getDischargeTable() { + return dischargeTable; + } + + public void setDischargeTable(ImportDischargeTable dischargeTable) { + this.dischargeTable = dischargeTable; + } + + public List<ImportMainValueType> getMainValueTypes() { + return mainValueTypes; + } + + public void setMainValueTypes(List<ImportMainValueType> mainValueTypes) { + this.mainValueTypes = mainValueTypes; + } + + public List<ImportNamedMainValue> getNamedMainValues() { + return namedMainValues; + } + + public void setNamedMainValues(List<ImportNamedMainValue> namedMainValues) { + this.namedMainValues = namedMainValues; + } + + public List<ImportMainValue> getMainValues() { + return mainValues; + } + + public void setMainValues(List<ImportMainValue> mainValues) { + this.mainValues = mainValues; + } + + public void parseDependencies() throws IOException { + StaFileParser sfp = new StaFileParser(); + sfp.parse(this); + + AtFileParser afp = new AtFileParser(); + setDischargeTable(afp.parse(getAtFile())); + parseHistoricalDischargeTables(); + } + + public void parseHistoricalDischargeTables() throws IOException { + if (Config.INSTANCE.skipHistoricalDischargeTables()) { + log.info("skip historical discharge tables"); + return; + } + + log.info("parse historical discharge tables"); + + File riverDir = atFile.getParentFile().getParentFile(); + + File histDischargeDir = FileTools.repair( + new File(riverDir, HISTORICAL_DISCHARGE_TABLES)); + + if (!histDischargeDir.isDirectory() || !histDischargeDir.canRead()) { + log.info("cannot find '" + histDischargeDir + "'"); + return; + } + + histDischargeDir = FileTools.repair( + new File(histDischargeDir, getName())); + + if (!histDischargeDir.isDirectory() || !histDischargeDir.canRead()) { + log.info("cannot find '" + histDischargeDir + "'"); + return; + } + + File [] files = histDischargeDir.listFiles(); + + if (files == null) { + log.info("cannot read directory '" + histDischargeDir + "'"); + return; + } + + for (File file: files) { + if (!file.isFile() || !file.canRead()) { + continue; + } + String name = file.getName().toLowerCase(); + if (!name.endsWith(".at")) { + continue; + } + log.info("found at file '" + file.getName() + "'"); + + AtFileParser afp = new AtFileParser(); + historicalDischargeTables.add( + afp.parse(file, HISTORICAL_DISCHARGE_TABLES + "/", 1)); + } + } + + public void storeDependencies(River river) { + + Gauge gauge = getPeer(river); + + log.info("store main value types"); + for (ImportMainValueType mainValueType: mainValueTypes) { + mainValueType.getPeer(); + } + + log.info("store named main values"); + for (ImportNamedMainValue namedMainValue: namedMainValues) { + namedMainValue.getPeer(); + } + + log.info("store main values"); + for (ImportMainValue mainValue: mainValues) { + mainValue.getPeer(river); + } + + storeDischargeTable(gauge); + storeHistoricalDischargeTable(gauge); + } + + public void storeDischargeTable(Gauge gauge) { + log.info("store discharge table"); + dischargeTable.getPeer(gauge); + dischargeTable.storeDependencies(gauge); + } + + public void storeHistoricalDischargeTable(Gauge gauge) { + log.info("store historical discharge tables"); + for (ImportDischargeTable hdt: historicalDischargeTables) { + hdt.storeDependencies(gauge); + } + } + + public Gauge getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from Gauge where name=:name " + + "and river.id=:river"); + query.setString("name", name); + query.setParameter("river", river.getId()); + List<Gauge> gauges = query.list(); + if (gauges.isEmpty()) { + peer = new Gauge( + name, river, + station, aeo, datum, + officialNumber, + range.getPeer(river)); + session.save(peer); + } + else { + peer = gauges.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportGrainFraction.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,80 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.GrainFraction; + + +public class ImportGrainFraction { + + private static final Logger log = + Logger.getLogger(ImportGrainFraction.class); + + private String name; + + private Double lower; + private Double upper; + + private GrainFraction peer; + + + public ImportGrainFraction(String name) { + this.name = name; + } + + + public ImportGrainFraction( + String name, + Double lower, + Double upper + ) { + this.name = name; + this.lower = lower; + this.upper = upper; + } + + + public void storeDependencies() { + log.debug("store dependencies"); + + getPeer(); + } + + + public GrainFraction getPeer() { + log.debug("get peer"); + + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from GrainFraction where " + + " name=:name and " + + " lower=:lower and " + + " upper=:upper" + ); + + query.setParameter("name", name); + query.setParameter("lower", lower); + query.setParameter("upper", upper); + + List<GrainFraction> fractions = query.list(); + if (fractions.isEmpty()) { + log.info("create new GrainFraction"); + + peer = new GrainFraction(name, lower, upper); + session.save(peer); + } + else { + peer = fractions.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportHYK.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,80 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.HYK; +import de.intevation.flys.model.River; + +import java.util.List; +import java.util.ArrayList; + +import org.hibernate.Session; +import org.hibernate.Query; + +import org.apache.log4j.Logger; + +public class ImportHYK +{ + private static Logger log = Logger.getLogger(ImportHYK.class); + + protected ImportRiver river; + protected String description; + + protected List<ImportHYKEntry> entries; + + protected HYK peer; + + public ImportHYK() { + entries = new ArrayList<ImportHYKEntry>(); + } + + public ImportHYK(ImportRiver river, String description) { + this(); + this.river = river; + this.description = description; + } + + public ImportRiver getRiver() { + return river; + } + + public void setRiver(ImportRiver river) { + this.river = river; + } + + public void addEntry(ImportHYKEntry entry) { + entries.add(entry); + entry.setHYK(this); + } + + public void storeDependencies() { + log.info("store HYK '" + description + "'"); + getPeer(); + for (int i = 0, N = entries.size(); i < N; ++i) { + ImportHYKEntry entry = entries.get(i); + log.info(" store km " + entry.getKm() + + " (" + (i+1) + " of " + N + ")"); + entry.storeDependencies(); + } + } + + public HYK getPeer() { + if (peer == null) { + River r = river.getPeer(); + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery( + "from HYK where river=:river and description=:description"); + query.setParameter("river", r); + query.setParameter("description", description); + List<HYK> hyks = query.list(); + if (hyks.isEmpty()) { + peer = new HYK(r, description); + session.save(peer); + } + else { + peer = hyks.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportHYKEntry.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,93 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.HYKEntry; +import de.intevation.flys.model.HYK; + +import java.util.Date; +import java.util.List; +import java.util.ArrayList; + +import java.math.BigDecimal; + +import org.hibernate.Session; +import org.hibernate.Query; + +public class ImportHYKEntry +{ + protected ImportHYK hyk; + protected BigDecimal km; + protected Date measure; + + protected List<ImportHYKFormation> formations; + + protected HYKEntry peer; + + public ImportHYKEntry() { + formations = new ArrayList<ImportHYKFormation>(); + } + + public ImportHYKEntry( + ImportHYK hyk, + BigDecimal km, + Date measure + ) { + this(); + this.hyk = hyk; + this.km = km; + this.measure = measure; + } + + public ImportHYK getHYK() { + return hyk; + } + + public void setHYK(ImportHYK hyk) { + this.hyk = hyk; + } + + public BigDecimal getKm() { + return km; + } + + public void setKm(BigDecimal km) { + this.km = km; + } + + public void addFormation(ImportHYKFormation formation) { + int numFormation = formations.size(); + formations.add(formation); + formation.setFormationNum(numFormation); + formation.setEntry(this); + } + + public void storeDependencies() { + getPeer(); + for (ImportHYKFormation formation: formations) { + formation.storeDependencies(); + } + } + + public HYKEntry getPeer() { + if (peer == null) { + HYK h = hyk.getPeer(); + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery( + "from HYKEntry where HYK=:hyk " + + "and km=:km and measure=:measure"); + query.setParameter("hyk", h); + query.setParameter("km", km); + query.setParameter("measure", measure); + List<HYKEntry> entries = query.list(); + if (entries.isEmpty()) { + peer = new HYKEntry(h, km, measure); + session.save(peer); + } + else { + peer = entries.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportHYKFlowZone.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,76 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.HYKFormation; +import de.intevation.flys.model.HYKFlowZone; +import de.intevation.flys.model.HYKFlowZoneType; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +import java.math.BigDecimal; + +public class ImportHYKFlowZone +{ + protected ImportHYKFormation formation; + protected ImportHYKFlowZoneType type; + protected BigDecimal a; + protected BigDecimal b; + + protected HYKFlowZone peer; + + public ImportHYKFlowZone() { + } + + public ImportHYKFlowZone( + ImportHYKFormation formation, + ImportHYKFlowZoneType type, + BigDecimal a, + BigDecimal b + ) { + this.formation = formation; + this.type = type; + this.a = a; + this.b = b; + } + + public ImportHYKFormation getFormation() { + return formation; + } + + public void setFormation(ImportHYKFormation formation) { + this.formation = formation; + } + + public void storeDependencies() { + getPeer(); + } + + public HYKFlowZone getPeer() { + if (peer == null) { + HYKFormation f = formation.getPeer(); + HYKFlowZoneType t = type.getPeer(); + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery( + "from HYKFlowZone where formation=:formation " + + "and type=:type and a=:a and b=:b"); + query.setParameter("formation", f); + query.setParameter("type", t); + query.setParameter("a", a); + query.setParameter("b", b); + List<HYKFlowZone> zones = query.list(); + if (zones.isEmpty()) { + peer = new HYKFlowZone(f, t, a, b); + session.save(peer); + } + else { + peer = zones.get(0); + } + + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportHYKFlowZoneType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,41 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.HYKFlowZoneType; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportHYKFlowZoneType +{ + private String name; + private HYKFlowZoneType peer; + + public ImportHYKFlowZoneType() { + } + + public ImportHYKFlowZoneType(String name) { + this.name = name; + } + + public HYKFlowZoneType getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery( + "from HYKFlowZoneType where name=:name"); + query.setParameter("name", name); + List<HYKFlowZoneType> flowZoneTypes = query.list(); + if (flowZoneTypes.isEmpty()) { + peer = new HYKFlowZoneType(name); + session.save(peer); + } + else { + peer = flowZoneTypes.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportHYKFormation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,150 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.HYKFormation; +import de.intevation.flys.model.HYKEntry; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.math.BigDecimal; + +public class ImportHYKFormation +{ + protected int formationNum; + protected ImportHYKEntry entry; + protected BigDecimal top; + protected BigDecimal bottom; + protected BigDecimal distanceVL; + protected BigDecimal distanceHF; + protected BigDecimal distanceVR; + + protected List<ImportHYKFlowZone> zones; + + protected HYKFormation peer; + + public ImportHYKFormation() { + zones = new ArrayList<ImportHYKFlowZone>(); + } + + public ImportHYKFormation( + int formationNum, + ImportHYKEntry entry, + BigDecimal top, + BigDecimal bottom, + BigDecimal distanceVL, + BigDecimal distanceHF, + BigDecimal distanceVR + ) { + this(); + this.formationNum = formationNum; + this.entry = entry; + this.top = top; + this.bottom = bottom; + this.distanceVL = distanceVL; + this.distanceHF = distanceHF; + this.distanceVR = distanceVR; + } + + public void addFlowZone(ImportHYKFlowZone zone) { + zones.add(zone); + zone.setFormation(this); + } + + public int getFormationNum() { + return formationNum; + } + + public void setFormationNum(int formationNum) { + this.formationNum = formationNum; + } + + public ImportHYKEntry getEntry() { + return entry; + } + + public void setEntry(ImportHYKEntry entry) { + this.entry = entry; + } + + public BigDecimal getTop() { + return top; + } + + public void setTop(BigDecimal top) { + this.top = top; + } + + public BigDecimal getBottom() { + return bottom; + } + + public void setBottom(BigDecimal bottom) { + this.bottom = bottom; + } + + public BigDecimal getDistanceVL() { + return distanceVL; + } + + public void setDistanceVL(BigDecimal distanceVL) { + this.distanceVL = distanceVL; + } + + public BigDecimal getDistanceHF() { + return distanceHF; + } + + public void setDistanceHF(BigDecimal distanceHF) { + this.distanceHF = distanceHF; + } + + public BigDecimal getDistanceVR() { + return distanceVR; + } + + public void setDistanceVR(BigDecimal distanceVR) { + this.distanceVR = distanceVR; + } + + public void storeDependencies() { + getPeer(); + for (ImportHYKFlowZone zone: zones) { + zone.storeDependencies(); + } + } + + public HYKFormation getPeer() { + if (peer == null) { + HYKEntry e = entry.getPeer(); + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery( + "from HYKFormation where formationNum=:formationNum " + + "and entry=:entry and top=:top and bottom=:bottom " + + "and distanceVL=:distanceVL and distanceHF=:distanceHF " + + "and distanceVR=:distanceVR"); + query.setParameter("formationNum", formationNum); + query.setParameter("entry", e); + query.setParameter("top", top); + query.setParameter("bottom", bottom); + query.setParameter("distanceVL", distanceVL); + query.setParameter("distanceHF", distanceHF); + query.setParameter("distanceVR", distanceVR); + List<HYKFormation> formations = query.list(); + if (formations.isEmpty()) { + peer = new HYKFormation( + formationNum, e, top, bottom, + distanceVL, distanceHF, distanceVR); + session.save(peer); + } + else { + peer = formations.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportLocationSystem.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,60 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.LocationSystem; + + +public class ImportLocationSystem { + + private static final Logger log = + Logger.getLogger(ImportLocationSystem.class); + + + protected String name; + protected String description; + + protected LocationSystem peer; + + + public ImportLocationSystem(String name, String description) { + this.name = name; + this.description = description; + } + + public void storeDependencies() { + log.info("store LocationSystem '" + name + "'"); + LocationSystem ls = getPeer(); + + Session session = ImporterSession.getInstance().getDatabaseSession(); + session.flush(); + } + + public LocationSystem getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from LocationSystem where " + + "name=:name and description=:description"); + query.setParameter("name", name); + query.setParameter("description", description); + + List<LocationSystem> lss = query.list(); + if (lss.isEmpty()) { + peer = new LocationSystem(name, description); + session.save(peer); + } + else { + peer = lss.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportMainValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,92 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import java.math.BigDecimal; + +import de.intevation.flys.model.MainValue; +import de.intevation.flys.model.Gauge; +import de.intevation.flys.model.River; +import de.intevation.flys.model.NamedMainValue; +import de.intevation.flys.model.TimeInterval; + +import org.hibernate.Session; +import org.hibernate.Query; + +public class ImportMainValue +{ + protected ImportGauge gauge; + protected ImportNamedMainValue mainValue; + protected BigDecimal value; + protected ImportTimeInterval timeInterval; + + protected MainValue peer; + + public ImportMainValue() { + } + + public ImportMainValue( + ImportGauge gauge, + ImportNamedMainValue mainValue, + BigDecimal value, + ImportTimeInterval timeInterval + ) { + this.gauge = gauge; + this.mainValue = mainValue; + this.value = value; + this.timeInterval = timeInterval; + } + + public ImportGauge getGauge() { + return gauge; + } + + public void setGauge(ImportGauge gauge) { + this.gauge = gauge; + } + + public ImportNamedMainValue getMainValue() { + return mainValue; + } + + public void setMainValue(ImportNamedMainValue mainValue) { + this.mainValue = mainValue; + } + + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + public MainValue getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from MainValue where " + + "gauge.id=:gauge_id and mainValue.id=:name_id " + + "and timeInterval = :time " + + "and value=:value"); + Gauge g = gauge.getPeer(river); + NamedMainValue n = mainValue.getPeer(); + TimeInterval t = timeInterval != null + ? timeInterval.getPeer() + : null; + query.setParameter("gauge_id", g.getId()); + query.setParameter("name_id", n.getId()); + query.setParameter("value", value); + query.setParameter("time", t); + List<MainValue> values = query.list(); + if (values.isEmpty()) { + peer = new MainValue(g, n, value, null); + session.save(peer); + } + else { + peer = values.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportMainValueType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,65 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.MainValueType; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportMainValueType +implements Comparable<ImportMainValueType> +{ + protected String name; + + protected MainValueType peer; + + public ImportMainValueType() { + } + + public ImportMainValueType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int compareTo(ImportMainValueType other) { + return name.compareTo(other.name); + } + + @Override + public boolean equals(Object other) { + if (other == this) return true; + if (!(other instanceof ImportMainValueType)) return false; + return name.equals(((ImportMainValueType)other).name); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + public MainValueType getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from MainValueType where name=:name"); + query.setString("name", name); + List<MainValueType> values = query.list(); + if (values.isEmpty()) { + peer = new MainValueType(name); + session.save(peer); + } + else { + peer = values.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportMeasurementStation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,113 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.Session; + +import de.intevation.flys.model.Gauge; +import de.intevation.flys.model.MeasurementStation; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; +import de.intevation.flys.model.TimeInterval; + + +public class ImportMeasurementStation { + + private static final Logger log = Logger + .getLogger(ImportMeasurementStation.class); + + private MeasurementStation peer; + + public String name; + public Double station; + public ImportRange range; + public String measurementType; + public String riverside; + public String gauge; + public ImportTimeInterval observationTimerange; + public String operator; + public String description; + + public ImportMeasurementStation() { + } + + private Gauge getGaugeFromDB() { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + org.hibernate.Query query = session + .createQuery("FROM Gauge WHERE name=:name"); + + query.setParameter("name", gauge); + List<Gauge> gauges = query.list(); + + return gauges.isEmpty() ? null : gauges.get(0); + } + + public boolean storeDependencies(River river) { + getPeer(river); + + return peer != null; + } + + public Object getPeer(River river) { + if (peer == null) { + Gauge gauge = null; + try { + gauge = getGaugeFromDB(); + if (gauge == null) { + log.warn("No gauge found for measurement station '" + name + + "'"); + } + } + catch (Exception e) { + log.error("Exception: " + e.getMessage()); + } + + Range range = null; + + if (this.range != null) { + range = this.range.getPeer(river); + } + + if (range == null) { + log.warn("No range found for measurement station '" + name + "'"); + } + + TimeInterval observationTimerange = this.observationTimerange + .getPeer(); + if (observationTimerange == null) { + log.warn("No time range found for measurement station '" + + name + "'"); + } + + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + org.hibernate.Query query = session + .createQuery( + "FROM MeasurementStation " + + "WHERE river=:river" + + " AND station=:station " + + " AND measurement_type=:measurement_type "); + + query.setParameter("river", river); + query.setParameter("station", station); + query.setParameter("measurement_type", measurementType); + + List<MeasurementStation> stations = query.list(); + + if (stations.isEmpty()) { + log.info("create new measurement station '" + name + "'"); + + peer = new MeasurementStation(river, name, measurementType, + riverside, station, range, gauge, this.gauge, + observationTimerange, operator, description); + + session.save(peer); + } + } + + return peer; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportMorphWidth.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,81 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.MorphologicalWidth; +import de.intevation.flys.model.River; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; + + +public class ImportMorphWidth { + + private static Logger log = Logger.getLogger(ImportMorphWidth.class); + + protected MorphologicalWidth peer; + + protected ImportUnit unit; + + protected List<ImportMorphWidthValue> values; + + public ImportMorphWidth() { + this.values = new ArrayList<ImportMorphWidthValue>(); + } + + public void addValue(ImportMorphWidthValue value) { + this.values.add(value); + } + + public void setUnit(ImportUnit unit) { + this.unit = unit; + } + + public void storeDependencies(River river) { + log.info("store dependencies"); + + MorphologicalWidth peer = getPeer(river); + + if (peer != null) { + log.info("store morphological width values"); + + for (ImportMorphWidthValue value : values) { + value.storeDependencies(peer); + } + } + } + + public MorphologicalWidth getPeer(River river) { + log.info("get peer"); + + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + Query query = session.createQuery("from MorphologicalWidth where " + + " river=:river and " + " unit=:unit"); + + query.setParameter("river", river); + query.setParameter("unit", unit.getPeer()); + + List<MorphologicalWidth> widths = query.list(); + + if (widths.isEmpty()) { + log.debug("Create new MorphologicalWidth DB instance."); + + peer = new MorphologicalWidth(river, unit.getPeer()); + + session.save(peer); + } + else { + peer = widths.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportMorphWidthValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,81 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.MorphologicalWidth; +import de.intevation.flys.model.MorphologicalWidthValue; + + +public class ImportMorphWidthValue { + + private static Logger log = Logger.getLogger(ImportMorphWidthValue.class); + + + protected MorphologicalWidthValue peer; + + protected BigDecimal station; + protected BigDecimal width; + + protected String description; + + + public ImportMorphWidthValue( + BigDecimal station, + BigDecimal width, + String description + ) { + this.station = station; + this.width = width; + this.description = description; + } + + + public void storeDependencies(MorphologicalWidth parent) { + getPeer(parent); + } + + + public MorphologicalWidthValue getPeer(MorphologicalWidth parent) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from MorphologicalWidthValue where " + + " morphologicalWidth=:morphologicalWidth and " + + " station=:station and " + + " width=:width and " + + " description=:description"); + + query.setParameter("morphologicalWidth", parent); + query.setParameter("station", station); + query.setParameter("width", width); + query.setParameter("description", description); + + List<MorphologicalWidthValue> values = query.list(); + + if (values.isEmpty()) { + peer = new MorphologicalWidthValue( + parent, + station, + width, + description + ); + + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportNamedMainValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,66 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import de.intevation.flys.model.NamedMainValue; +import de.intevation.flys.model.MainValueType; + +import org.hibernate.Session; +import org.hibernate.Query; + +public class ImportNamedMainValue +{ + protected ImportMainValueType mainValueType; + protected String name; + + protected NamedMainValue peer; + + public ImportNamedMainValue() { + } + + public ImportNamedMainValue( + ImportMainValueType mainValueType, + String name + ) { + this.mainValueType = mainValueType; + this.name = name; + } + + public ImportMainValueType getMainValueType() { + return mainValueType; + } + + public void setMainValueType(ImportMainValueType mainValueType) { + this.mainValueType = mainValueType; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public NamedMainValue getPeer() { + if (peer == null) { + MainValueType type = mainValueType.getPeer(); + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from NamedMainValue where " + + "name=:name and type.id=:id"); + query.setString("name", name); + query.setParameter("id", type.getId()); + List<NamedMainValue> named = query.list(); + if (named.isEmpty()) { + peer = new NamedMainValue(name, type); + session.save(peer); + } + else { + peer = named.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportPosition.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,54 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Position; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportPosition +implements Comparable<ImportPosition> +{ + protected String value; + + protected Position peer; + + public ImportPosition() { + } + + public ImportPosition(String value) { + this.value = value; + } + + public int compareTo(ImportPosition other) { + return value.compareTo(other.value); + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Position getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from Position where value=:value"); + query.setString("value", value); + List<Position> positions = query.list(); + if (positions.isEmpty()) { + peer = new Position(value); + session.save(peer); + } + else { + peer = positions.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportRange.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,78 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +/** A range that is about to be imported. */ +public class ImportRange +implements Comparable<ImportRange> +{ + /** Private logger. */ + private static Logger log = Logger.getLogger(ImportRange.class); + + protected BigDecimal a; + protected BigDecimal b; + + protected Range peer; + + public ImportRange() { + } + + public ImportRange(BigDecimal a, BigDecimal b) { + this.a = a; + this.b = b; + } + + private static final int compare(BigDecimal a, BigDecimal b) { + if (a == null && b == null) { + return 0; + } + if (a == null && b != null) { + return -1; + } + if (a != null && b == null) { + return +1; + } + return a.compareTo(b); + } + + public void fixRangesOrder() { + if (compare(a, b) > 0) { + BigDecimal t = a; a = b; b = t; + } + } + + public int compareTo(ImportRange other) { + int cmp = compare(a, other.a); + if (cmp != 0) return cmp; + return compare(b, other.b); + } + + public BigDecimal getA() { + return a; + } + + public void setA(BigDecimal a) { + this.a = a; + } + + public BigDecimal getB() { + return b; + } + + public void setB(BigDecimal b) { + this.b = b; + } + + public Range getPeer(River river) { + if (peer == null) { + peer = ImporterSession.getInstance().getRange(river, a, b); + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportRiver.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,1464 @@ +package de.intevation.flys.importer; + +import de.intevation.artifacts.common.utils.FileTools.HashedFile; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.parsers.AnnotationClassifier; +import de.intevation.flys.importer.parsers.AnnotationsParser; +import de.intevation.flys.importer.parsers.BedHeightEpochParser; +import de.intevation.flys.importer.parsers.BedHeightSingleParser; +import de.intevation.flys.importer.parsers.CrossSectionParser; +import de.intevation.flys.importer.parsers.DA50Parser; +import de.intevation.flys.importer.parsers.DA66Parser; +import de.intevation.flys.importer.parsers.FlowVelocityMeasurementParser; +import de.intevation.flys.importer.parsers.FlowVelocityModelParser; +import de.intevation.flys.importer.parsers.HYKParser; +import de.intevation.flys.importer.parsers.MeasurementStationsParser; +import de.intevation.flys.importer.parsers.MorphologicalWidthParser; +import de.intevation.flys.importer.parsers.PRFParser; +import de.intevation.flys.importer.parsers.PegelGltParser; +import de.intevation.flys.importer.parsers.SQRelationParser; +import de.intevation.flys.importer.parsers.SedimentDensityParser; +import de.intevation.flys.importer.parsers.SedimentYieldParser; +import de.intevation.flys.importer.parsers.W80Parser; +import de.intevation.flys.importer.parsers.W80CSVParser; +import de.intevation.flys.importer.parsers.WaterlevelDifferencesParser; +import de.intevation.flys.importer.parsers.WaterlevelParser; +import de.intevation.flys.importer.parsers.WstParser; + +import de.intevation.flys.model.River; +import de.intevation.flys.model.Unit; + +import java.io.File; +import java.io.IOException; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; + + +/** Import all river-related data (files) that can be found. */ +public class ImportRiver +{ + /** Private logger. */ + private static Logger log = Logger.getLogger(ImportRiver.class); + + public static final String PEGEL_GLT = "PEGEL.GLT"; + + public static final String FIXATIONS = "Fixierungen"; + + public static final String EXTRA_LONGITUDINALS = + "Zus.L\u00e4ngsschnitte"; + + public static final String [] OFFICIAL_LINES_FOLDERS = { + "Basisdaten", + "Fixierungen" }; + + public static final String OFFICIAL_LINES = + "Amtl_Linien.wst"; + + public static final String FLOOD_WATER = "HW-Marken"; + + public static final String FLOOD_PROTECTION = + "HW-Schutzanlagen"; + + public static final String MINFO_DIR = "Morphologie"; + + public static final String BED_HEIGHT_DIR = "Sohlhoehen"; + + public static final String BED_HEIGHT_SINGLE_DIR = "Einzeljahre"; + + public static final String BED_HEIGHT_EPOCH_DIR = "Epochen"; + + public static final String SEDIMENT_DENSITY_DIR = "Sedimentdichte"; + + public static final String MORPHOLOGICAL_WIDTH_DIR = "morphologische_Breite"; + + public static final String FLOW_VELOCITY_DIR = "Geschwindigkeit_Schubspannung"; + + public static final String FLOW_VELOCITY_MODEL = "Modellrechnungen"; + + public static final String FLOW_VELOCITY_MEASUREMENTS = "v-Messungen"; + + public static final String SEDIMENT_YIELD_DIR = "Fracht"; + + public static final String SEDIMENT_YIELD_SINGLE_DIR = "Einzeljahre"; + + public static final String SEDIMENT_YIELD_EPOCH_DIR = "Epochen"; + + public static final String MINFO_FIXATIONS_DIR = "Fixierungsanalyse"; + + public static final String MINFO_WATERLEVELS_DIR = "Wasserspiegellagen"; + + public static final String MINFO_WATERLEVEL_DIFF_DIR = "Wasserspiegeldifferenzen"; + + public static final String MINFO_BASE_DIR = "Basisdaten"; + + public static final String MINFO_CORE_DATA_FILE = "Stammdaten_Messstellen.csv"; + + public static final String MINFO_SQ_DIR = "Feststofftransport-Abfluss-Beziehung"; + + protected String name; + + protected Long officialNumber; + + protected File wstFile; + + protected File bbInfoFile; + + protected List<ImportGauge> gauges; + + protected List<ImportAnnotation> annotations; + + protected List<ImportHYK> hyks; + + protected List<ImportCrossSection> crossSections; + + protected List<ImportWst> extraWsts; + + protected List<ImportWst> fixations; + + protected List<ImportWst> officialLines; + + protected List<ImportWst> floodWater; + + protected List<ImportWst> floodProtection; + + /** Wst-structures from waterlevel-csv files. */ + protected List<ImportWst> waterlevels; + + /** Wst-structures from waterlevel-difference-csv files. */ + protected List<ImportWst> waterlevelDifferences; + + protected List<ImportBedHeight> bedHeightSingles; + + protected List<ImportBedHeight> bedHeightEpochs; + + protected List<ImportSedimentDensity> sedimentDensities; + + protected List<ImportMorphWidth> morphologicalWidths; + + protected List<ImportFlowVelocityModel> flowVelocityModels; + + protected List<ImportFlowVelocityMeasurement> flowVelocityMeasurements; + + protected List<ImportSedimentYield> sedimentYields; + + protected List<ImportMeasurementStation> measurementStations; + + protected List<ImportSQRelation> sqRelations; + + protected ImportWst wst; + + protected ImportUnit wstUnit; + + protected AnnotationClassifier annotationClassifier; + + /** Database-mapped River instance. */ + protected River peer; + + + /** Callback-implementation for CrossSectionParsers: + * Accept files with different md5(?)sums than what has already been parsed, + * on successfull parse, add data. */ + class ImportRiverCrossSectionParserCallback implements CrossSectionParser.Callback { + Set<HashedFile> files = new HashSet<HashedFile>(); + String type; + + + /** + * Create new Callback, given type which is used for logging + * purposes only. + */ + public ImportRiverCrossSectionParserCallback (String type) { + this.type = type; + } + + + /** Accept file if not duplicate. */ + public boolean accept(File file) { + HashedFile hf = new HashedFile(file); + boolean success = files.add(hf); + if (!success) { + log.warn(type + " file '" + file + "' seems to be a duplicate."); + } + return success; + } + + + /** Add crosssection. */ + public void parsed(CrossSectionParser parser) { + log.debug("callback from " + type + " parser"); + + addCrossSections(parser); + } + } // ImportRiverCrossSectionParserCallback + + + public ImportRiver() { + hyks = new ArrayList<ImportHYK>(); + crossSections = new ArrayList<ImportCrossSection>(); + extraWsts = new ArrayList<ImportWst>(); + fixations = new ArrayList<ImportWst>(); + officialLines = new ArrayList<ImportWst>(); + floodWater = new ArrayList<ImportWst>(); + waterlevels = new ArrayList<ImportWst>(); + waterlevelDifferences = new ArrayList<ImportWst>(); + floodProtection = new ArrayList<ImportWst>(); + sedimentDensities = new ArrayList<ImportSedimentDensity>(); + morphologicalWidths = new ArrayList<ImportMorphWidth>(); + flowVelocityModels = new ArrayList<ImportFlowVelocityModel>(); + flowVelocityMeasurements = new ArrayList<ImportFlowVelocityMeasurement>(); + sedimentYields = new ArrayList<ImportSedimentYield>(); + measurementStations = new ArrayList<ImportMeasurementStation>(); + sqRelations = new ArrayList<ImportSQRelation>(); + } + + public ImportRiver( + String name, + File wstFile, + File bbInfoFile, + AnnotationClassifier annotationClassifier + ) { + this(); + this.name = name; + this.wstFile = wstFile; + this.bbInfoFile = bbInfoFile; + this.annotationClassifier = annotationClassifier; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getOfficialNumber() { + return this.officialNumber; + } + + public void setOfficialNumber(Long officialNumber) { + this.officialNumber = officialNumber; + } + + public File getWstFile() { + return wstFile; + } + + public void setWstFile(File wstFile) { + this.wstFile = wstFile; + } + + public File getBBInfo() { + return bbInfoFile; + } + + public void setBBInfo(File bbInfoFile) { + this.bbInfoFile = bbInfoFile; + } + + public ImportWst getWst() { + return wst; + } + + public void setWst(ImportWst wst) { + this.wst = wst; + } + + public File getMinfoDir() { + File riverDir = wstFile.getParentFile().getParentFile().getParentFile(); + return new File(riverDir, MINFO_DIR); + } + + public void parseDependencies() throws IOException { + parseGauges(); + parseAnnotations(); + parsePRFs(); + parseDA66s(); + parseDA50s(); + parseW80s(); + parseW80CSVs(); + parseHYKs(); + parseWst(); + parseExtraWsts(); + parseFixations(); + parseOfficialLines(); + parseFloodWater(); + parseFloodProtection(); + parseBedHeight(); + parseSedimentDensity(); + parseMorphologicalWidth(); + parseFlowVelocity(); + parseSedimentYield(); + parseWaterlevels(); + parseWaterlevelDifferences(); + parseMeasurementStations(); + parseSQRelation(); + } + + public void parseFloodProtection() throws IOException { + if (Config.INSTANCE.skipFloodProtection()) { + log.info("skip parsing flood protection"); + return; + } + + log.info("Parse flood protection wst file"); + + File riverDir = wstFile.getParentFile().getParentFile(); + + File dir = FileTools.repair(new File(riverDir, FLOOD_PROTECTION)); + + if (!dir.isDirectory() || !dir.canRead()) { + log.info("no directory '" + dir + "' found"); + return; + } + + File [] files = dir.listFiles(); + + if (files == null) { + log.warn("cannot read '" + dir + "'"); + return; + } + + for (File file: files) { + if (!file.isFile() || !file.canRead()) { + continue; + } + String name = file.getName().toLowerCase(); + if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { + continue; + } + log.info("found file '" + file.getName() + "'"); + WstParser wstParser = new WstParser(); + wstParser.parse(file); + ImportWst iw = wstParser.getWst(); + iw.setKind(5); + iw.setDescription(FLOOD_PROTECTION + "/" + iw.getDescription()); + floodProtection.add(iw); + } + } + + public void storeOfficialNumber() { + if (Config.INSTANCE.skipBWASTR()) { + log.info("skip storing official number."); + return; + } + getPeer().setOfficialNumber(officialNumber); + } + + public void parseBedHeight() throws IOException { + File minfoDir = getMinfoDir(); + File bedHeightDir = new File(minfoDir, BED_HEIGHT_DIR); + File singlesDir = new File(bedHeightDir, BED_HEIGHT_SINGLE_DIR); + File epochDir = new File(bedHeightDir, BED_HEIGHT_EPOCH_DIR); + + if (Config.INSTANCE.skipBedHeightSingle()) { + log.info("skip parsing bed height single."); + } + else { + log.info("Parse bed height single."); + parseBedHeightSingles(singlesDir); + } + + if (Config.INSTANCE.skipBedHeightEpoch()) { + log.info("skip parsing bed height epochs."); + } + else { + log.info("Parse bed height epochs."); + parseBedHeightEpochs(epochDir); + } + } + + + protected void parseSedimentDensity() throws IOException { + if (Config.INSTANCE.skipSedimentDensity()) { + log.info("skip parsing sediment density."); + return; + } + + log.debug("Parse sediment density"); + + File minfoDir = getMinfoDir(); + File sediment = new File(minfoDir, SEDIMENT_DENSITY_DIR); + + File[] files = sediment.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + sediment + "'"); + return; + } + + SedimentDensityParser parser = new SedimentDensityParser(); + + for (File file: files) { + parser.parse(file); + } + + sedimentDensities = parser.getSedimentDensities(); + + log.info("Parsed " + sedimentDensities.size() + " sediment densities."); + } + + + protected void parseMorphologicalWidth() throws IOException { + if (Config.INSTANCE.skipMorphologicalWidth()) { + log.info("skip parsing morphological width."); + return; + } + + log.debug("Parse morphological width"); + + File minfoDir = getMinfoDir(); + File morphDir = new File(minfoDir, MORPHOLOGICAL_WIDTH_DIR); + + File[] files = morphDir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + morphDir + "'"); + return; + } + + MorphologicalWidthParser parser = new MorphologicalWidthParser(); + + for (File file: files) { + parser.parse(file); + } + + morphologicalWidths = parser.getMorphologicalWidths(); + + log.info("Parsed " + morphologicalWidths.size() + " morph. widths files."); + } + + + protected void parseFlowVelocity() throws IOException { + if (Config.INSTANCE.skipFlowVelocity()) { + log.info("skip parsing flow velocity"); + return; + } + + log.debug("Parse flow velocity"); + + File minfoDir = getMinfoDir(); + File flowDir = new File(minfoDir, FLOW_VELOCITY_DIR); + File modelDir = new File(flowDir, FLOW_VELOCITY_MODEL); + File measureDir = new File(flowDir, FLOW_VELOCITY_MEASUREMENTS); + + File[] modelFiles = modelDir.listFiles(); + File[] measureFiles = measureDir.listFiles(); + + if (modelFiles == null) { + log.warn("Cannot read directory '" + modelDir + "'"); + } + else { + FlowVelocityModelParser parser = new FlowVelocityModelParser(); + + for (File model: modelFiles) { + log.debug("Parse file '" + model + "'"); + parser.parse(model); + } + + flowVelocityModels = parser.getModels(); + } + + if (measureFiles == null) { + log.warn("Cannot read directory '" + measureDir + "'"); + } + else { + FlowVelocityMeasurementParser parser = + new FlowVelocityMeasurementParser(); + + for (File measurement: measureFiles) { + log.debug("Parse file '" + measurement + "'"); + parser.parse(measurement); + } + + flowVelocityMeasurements = parser.getMeasurements(); + } + } + + + protected void parseSedimentYield() throws IOException { + if (Config.INSTANCE.skipSedimentYield()) { + log.info("skip parsing sediment yield data"); + return; + } + + log.debug("Parse sediment yield data"); + + File minfoDir = getMinfoDir(); + File sedimentYieldDir = new File(minfoDir, SEDIMENT_YIELD_DIR); + + File singleDir = new File(sedimentYieldDir, SEDIMENT_YIELD_SINGLE_DIR); + File epochDir = new File(sedimentYieldDir, SEDIMENT_YIELD_EPOCH_DIR); + + File[] singles = singleDir.listFiles(); + File[] epochs = epochDir.listFiles(); + + SedimentYieldParser parser = new SedimentYieldParser(); + + if (singles == null || singles.length == 0) { + log.warn("Cannot read directory '" + singleDir + "'"); + } + else { + for (File file: singles) { + if (file.isDirectory()) { + for (File child: file.listFiles()) { + parser.parse(child); + } + } + else { + parser.parse(file); + } + } + } + + if (epochs == null || epochs.length == 0) { + log.warn("Cannot read directory '" + epochDir + "'"); + } + else { + for (File file: epochs) { + if (file.isDirectory()) { + for (File child: file.listFiles()) { + parser.parse(child); + } + } + else { + parser.parse(file); + } + } + } + + sedimentYields = parser.getSedimentYields(); + } + + + protected void parseWaterlevels() throws IOException { + if (Config.INSTANCE.skipWaterlevels()) { + log.info("skip parsing waterlevels"); + return; + } + + log.info("Parse waterlevels"); + + File minfo = getMinfoDir(); + File fixDir = new File(minfo, MINFO_FIXATIONS_DIR); + File wspDir = new File(fixDir, MINFO_WATERLEVELS_DIR); + + File[] files = wspDir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory for wl '" + wspDir + "'"); + return; + } + + WaterlevelParser parser = new WaterlevelParser(); + + for (File file: files) { + parser.parse(file); + } + + // The parsed ImportWaterlevels are converted to + // 'fixation'-wsts now. + for(ImportWst iw: parser.getWaterlevels()) { + iw.setDescription("CSV/" + iw.getDescription()); + iw.setKind(6); + waterlevels.add(iw); + } + } + + protected void parseMeasurementStations() throws IOException { + if (Config.INSTANCE.skipMeasurementStations()) { + log.info("skip parsing measurement stations"); + return; + } + + log.info("Parse measurement stations"); + + File minfo = getMinfoDir(); + File minfoBaseDir = new File(minfo, MINFO_BASE_DIR); + File coredataFile = new File(minfoBaseDir, MINFO_CORE_DATA_FILE); + + if (coredataFile == null || !coredataFile.exists()) { + log.warn("No core data file '" + coredataFile.getAbsolutePath() + "' found"); + return; + } + + MeasurementStationsParser parser = new MeasurementStationsParser(); + try { + parser.parse(coredataFile); + measurementStations = parser.getMeasurementStations(); + + log.info("Successfully parsed " + measurementStations.size() + " measurement stations."); + } + catch (IOException ioe) { + log.error("unable to parse file '" + coredataFile.getName() + + ": " + ioe.getMessage()); + } + } + + + protected void parseWaterlevelDifferences() throws IOException { + if (Config.INSTANCE.skipWaterlevelDifferences()) { + log.info("skip parsing waterlevel differences"); + return; + } + + log.info("Parse waterlevel differences"); + + File minfo = getMinfoDir(); + File fixDir = new File(minfo, MINFO_FIXATIONS_DIR); + File diffDir = new File(fixDir, MINFO_WATERLEVEL_DIFF_DIR); + + File[] files = diffDir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + diffDir + "'"); + return; + } + + WaterlevelDifferencesParser parser = new WaterlevelDifferencesParser(); + + for (File file: files) { + parser.parse(file); + } + + // WaterlevelDifferences become Wsts now. + for(ImportWst iw: parser.getDifferences()) { + iw.setDescription("CSV/" + iw.getDescription()); + iw.setKind(7); + waterlevelDifferences.add(iw); + } + } + + + protected void parseSQRelation() throws IOException { + if (Config.INSTANCE.skipSQRelation()) { + log.info("skip parsing sq relation"); + return; + } + + log.info("Parse sq relations"); + + File minfo = getMinfoDir(); + File sqDir = new File(minfo, MINFO_SQ_DIR); + + File[] files = sqDir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + sqDir + "'"); + return; + } + + SQRelationParser parser = new SQRelationParser(); + + for (File file: files) { + parser.parse(file); + } + + sqRelations = parser.getSQRelations(); + + log.debug("Parsed " + sqRelations.size() + " SQ relations."); + } + + + protected void parseBedHeightSingles(File dir) throws IOException { + log.debug("Parse bed height singles"); + + File[] files = dir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + dir + "'"); + return; + } + + BedHeightSingleParser parser = new BedHeightSingleParser(); + + for (File file: files) { + parser.parse(file); + } + + bedHeightSingles = parser.getBedHeights(); + } + + + protected void parseBedHeightEpochs(File dir) throws IOException { + log.debug("Parse bed height epochs"); + + File[] files = dir.listFiles(); + + if (files == null) { + log.warn("Cannot read directory '" + dir + "'"); + return; + } + + BedHeightEpochParser parser = new BedHeightEpochParser(); + + for (File file: files) { + parser.parse(file); + } + + bedHeightEpochs = parser.getBedHeights(); + } + + + public void parseFloodWater() throws IOException { + if (Config.INSTANCE.skipFloodWater()) { + log.info("skip parsing flod water"); + return; + } + + log.info("Parse flood water wst file"); + + File riverDir = wstFile.getParentFile().getParentFile(); + + File dir = FileTools.repair(new File(riverDir, FLOOD_WATER)); + + if (!dir.isDirectory() || !dir.canRead()) { + log.info("no directory '" + dir + "' found"); + return; + } + + File [] files = dir.listFiles(); + + if (files == null) { + log.warn("cannot read '" + dir + "'"); + return; + } + + for (File file: files) { + if (!file.isFile() || !file.canRead()) { + continue; + } + String name = file.getName().toLowerCase(); + if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { + continue; + } + log.info("found file '" + file.getName() + "'"); + WstParser wstParser = new WstParser(); + wstParser.parse(file); + ImportWst iw = wstParser.getWst(); + iw.setKind(4); + iw.setDescription(FLOOD_WATER + "/" + iw.getDescription()); + floodWater.add(iw); + } + } + + public void parseOfficialLines() throws IOException { + if (Config.INSTANCE.skipOfficialLines()) { + log.info("skip parsing official lines"); + return; + } + + log.info("Parse official wst files"); + + File riverDir = wstFile.getParentFile().getParentFile(); + + for (String folder: OFFICIAL_LINES_FOLDERS) { + File dir = FileTools.repair(new File(riverDir, folder)); + + if (!dir.isDirectory() || !dir.canRead()) { + log.info("no directory '" + folder + "' found"); + continue; + } + + File file = FileTools.repair(new File(dir, OFFICIAL_LINES)); + if (!file.isFile() || !file.canRead()) { + log.warn("no official lines wst file found"); + continue; + } + log.debug("Found WST file: " + file); + + WstParser wstParser = new WstParser(); + wstParser.parse(file); + ImportWst iw = wstParser.getWst(); + iw.setKind(3); + iw.setDescription(folder + "/" + iw.getDescription()); + officialLines.add(iw); + } // for all folders + + } + + public void parseFixations() throws IOException { + if (Config.INSTANCE.skipFixations()) { + log.info("skip parsing fixations"); + return; + } + + log.info("Parse fixation wst files"); + + File riverDir = wstFile.getParentFile().getParentFile(); + + File fixDir = FileTools.repair( + new File(riverDir, FIXATIONS)); + + if (!fixDir.isDirectory() || !fixDir.canRead()) { + log.info("no fixation wst file directory found"); + return; + } + + File [] files = fixDir.listFiles(); + + if (files == null) { + log.warn("cannot read fixations wst file directory"); + return; + } + + for (File file: files) { + if (!file.isFile() || !file.canRead()) { + continue; + } + String name = file.getName().toLowerCase(); + if (!name.endsWith(".wst")) { + continue; + } + log.debug("Found WST file: " + file); + + WstParser wstParser = new WstParser(); + wstParser.parse(file); + ImportWst iw = wstParser.getWst(); + iw.setKind(2); + iw.setDescription(FIXATIONS+ "/" + iw.getDescription()); + fixations.add(iw); + } + } + + public void parseExtraWsts() throws IOException { + if (Config.INSTANCE.skipExtraWsts()) { + log.info("skip parsing extra WST files"); + return; + } + + log.info("Parse extra longitudinal wst files"); + + File riverDir = wstFile.getParentFile().getParentFile(); + + File extraDir = FileTools.repair( + new File(riverDir, EXTRA_LONGITUDINALS)); + + if (!extraDir.isDirectory() || !extraDir.canRead()) { + log.info("no extra longitudinal wst file directory found"); + return; + } + + File [] files = extraDir.listFiles(); + + if (files == null) { + log.warn("cannot read extra longitudinal wst file directory"); + return; + } + + for (File file: files) { + if (!file.isFile() || !file.canRead()) { + continue; + } + String name = file.getName().toLowerCase(); + if (!(name.endsWith(".zus") || name.endsWith(".wst"))) { + continue; + } + log.debug("Found WST file: " + file); + + WstParser wstParser = new WstParser(); + wstParser.parse(file); + ImportWst iw = wstParser.getWst(); + iw.setKind(1); + iw.setDescription(EXTRA_LONGITUDINALS + "/" + iw.getDescription()); + extraWsts.add(iw); + } + + } + + public void parseWst() throws IOException { + if (Config.INSTANCE.skipWst()) { + log.info("skip parsing WST file"); + return; + } + + WstParser wstParser = new WstParser(); + wstParser.parse(wstFile); + wst = wstParser.getWst(); + } + + public void parseGauges() throws IOException { + if (Config.INSTANCE.skipGauges()) { + log.info("skip parsing gauges"); + return; + } + + File gltFile = new File(wstFile.getParentFile(), PEGEL_GLT); + gltFile = FileTools.repair(gltFile); + + if (!gltFile.isFile() || !gltFile.canRead()) { + log.warn("cannot read gauges from '" + gltFile + "'"); + return; + } + + PegelGltParser pgltp = new PegelGltParser(); + pgltp.parse(gltFile); + + gauges = pgltp.getGauges(); + + for (ImportGauge gauge: gauges) { + gauge.parseDependencies(); + } + } + + public void parseAnnotations() throws IOException { + if (Config.INSTANCE.skipAnnotations()) { + log.info("skip parsing annotations"); + return; + } + + File riverDir = wstFile.getParentFile().getParentFile(); + AnnotationsParser aparser = + new AnnotationsParser(annotationClassifier); + aparser.parse(riverDir); + + annotations = aparser.getAnnotations(); + } + + public void parseHYKs() { + if (Config.INSTANCE.skipHYKs()) { + log.info("skip parsing HYK files"); + return; + } + + log.info("looking for HYK files"); + HYKParser parser = new HYKParser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + parser.parseHYKs(riverDir, new HYKParser.Callback() { + + Set<HashedFile> hfs = new HashSet<HashedFile>(); + + @Override + public boolean hykAccept(File file) { + HashedFile hf = new HashedFile(file); + boolean success = hfs.add(hf); + if (!success) { + log.warn("HYK file '" + file + "' seems to be a duplicate."); + } + return success; + } + + @Override + public void hykParsed(HYKParser parser) { + log.debug("callback from HYK parser"); + ImportHYK hyk = parser.getHYK(); + hyk.setRiver(ImportRiver.this); + hyks.add(hyk); + } + }); + } + + + /** Add cross sections with description, years and lines to + * store. */ + private void addCrossSections(CrossSectionParser parser) { + String description = parser.getDescription(); + Integer year = parser.getYear(); + ImportTimeInterval ti = year != null + ? new ImportTimeInterval(yearToDate(year)) + : null; + + Map<Double, List<XY>> data = parser.getData(); + + List<ImportCrossSectionLine> lines = + new ArrayList<ImportCrossSectionLine>(data.size()); + + for (Map.Entry<Double, List<XY>> entry: data.entrySet()) { + Double km = entry.getKey(); + List<XY> points = entry.getValue(); + lines.add(new ImportCrossSectionLine(km, points)); + } + + crossSections.add(new ImportCrossSection( + ImportRiver.this, description, ti, lines)); + } + + /** Create a W80 Parser and parse w80 files found. */ + public void parseW80s() { + if (Config.INSTANCE.skipW80s()) { + log.info("skip parsing W80s"); + return; + } + W80Parser parser = new W80Parser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + ImportRiverCrossSectionParserCallback w80Callback = + new ImportRiverCrossSectionParserCallback("w80"); + parser.parseW80s(riverDir, w80Callback); + } + + /** Create a W80 Parser and parse w80 files found. */ + public void parseW80CSVs() { + if (Config.INSTANCE.skipW80CSVs()) { + log.info("skip parsing W80 csvs"); + return; + } + W80CSVParser parser = new W80CSVParser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + // Construct the Cross-Section-Data path. + File csDir = new File(riverDir.getPath() + + File.separator + "Geodaesie" + + File.separator + "Querprofile" + + File.separator + "QP-Daten"); + + ImportRiverCrossSectionParserCallback w80CSVCallback = + new ImportRiverCrossSectionParserCallback("w80-csv"); + parser.parseW80CSVs(csDir, w80CSVCallback); + } + + + /** + * Create and use a DA50Parser, parse the files found, add the + * ross-sections found. + */ + public void parseDA50s() { + if (Config.INSTANCE.skipDA50s()) { + log.info("skip parsing DA50s"); + return; + } + DA50Parser parser = new DA50Parser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + ImportRiverCrossSectionParserCallback da50Callback = + new ImportRiverCrossSectionParserCallback("da50"); + parser.parseDA50s(riverDir, da50Callback); + } + + + /** Create a DA66 Parser and parse the da66 files found. */ + // TODO this is a copy of parsePRFs, extract interfaces (e.g. CrossSectionParser). + public void parseDA66s() { + if (Config.INSTANCE.skipDA66s()) { + log.info("skip parsing DA66s"); + return; + } + + log.info("looking for DA66 files"); + DA66Parser parser = new DA66Parser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + ImportRiverCrossSectionParserCallback da66Callback = + new ImportRiverCrossSectionParserCallback("da66"); + parser.parseDA66s(riverDir, da66Callback); + } + + /** Create a PRFParser and let it parse the prf files found. */ + public void parsePRFs() { + if (Config.INSTANCE.skipPRFs()) { + log.info("skip parsing PRFs"); + return; + } + + log.info("looking for PRF files"); + PRFParser parser = new PRFParser(); + File riverDir = wstFile + .getParentFile() // Basisdaten + .getParentFile() // Hydrologie + .getParentFile(); // <river> + + ImportRiverCrossSectionParserCallback prfCallback = + new ImportRiverCrossSectionParserCallback("prf"); + parser.parsePRFs(riverDir, prfCallback); + } + + public static Date yearToDate(int year) { + Calendar cal = Calendar.getInstance(); + cal.set(year, 5, 15, 12, 0, 0); + long ms = cal.getTimeInMillis(); + cal.setTimeInMillis(ms - ms%1000); + return cal.getTime(); + } + + public void storeDependencies() { + storeWstUnit(); + storeAnnotations(); + storeHYKs(); + storeCrossSections(); + storeGauges(); + storeWst(); + storeExtraWsts(); + storeFixations(); + storeOfficialLines(); + storeFloodWater(); + storeFloodProtection(); + storeBedHeight(); + storeSedimentDensity(); + storeMorphologicalWidth(); + storeFlowVelocity(); + storeSedimentYield(); + storeWaterlevels(); + storeWaterlevelDifferences(); + storeMeasurementStations(); + storeSQRelations(); + storeOfficialNumber(); + } + + public void storeWstUnit() { + if (wst == null) { + wstUnit = new ImportUnit("NN + m"); + } + else { + wstUnit = wst.getUnit(); + } + } + + public void storeHYKs() { + if (!Config.INSTANCE.skipHYKs()) { + log.info("store HYKs"); + getPeer(); + for (ImportHYK hyk: hyks) { + hyk.storeDependencies(); + } + } + } + + public void storeCrossSections() { + if (!Config.INSTANCE.skipPRFs() + || !Config.INSTANCE.skipDA66s() + || !Config.INSTANCE.skipDA50s() + || !Config.INSTANCE.skipW80s() + || !Config.INSTANCE.skipW80CSVs()) { + log.info("store cross sections"); + getPeer(); + for (ImportCrossSection crossSection: crossSections) { + crossSection.storeDependencies(); + } + } + } + + public void storeWst() { + if (!Config.INSTANCE.skipWst()) { + River river = getPeer(); + wst.storeDependencies(river); + } + } + + public void storeFixations() { + if (!Config.INSTANCE.skipFixations()) { + log.info("store fixation wsts"); + River river = getPeer(); + for (ImportWst fWst: fixations) { + log.debug("Fixation name: " + fWst.getDescription()); + fWst.storeDependencies(river); + } + } + } + + + /** Store wsts from waterlevel-csv files. */ + public void storeWaterlevels() { + if (!Config.INSTANCE.skipWaterlevels()) + + log.info("store waterlevel wsts from csv"); + River river = getPeer(); + for (ImportWst wWst: waterlevels) { + log.debug("Waterlevel name: " + wWst.getDescription()); + wWst.storeDependencies(river); + } + } + + + /** Store wsts from waterleveldifference-csv files. */ + public void storeWaterlevelDifferences() { + if (!Config.INSTANCE.skipWaterlevelDifferences()) + + log.info("store waterleveldifferences wsts from csv"); + River river = getPeer(); + for (ImportWst dWst: waterlevelDifferences) { + log.debug("water.diff.: name " + dWst.getDescription()); + dWst.storeDependencies(river); + } + } + + + public void storeExtraWsts() { + if (!Config.INSTANCE.skipExtraWsts()) { + log.info("store extra wsts"); + River river = getPeer(); + for (ImportWst wst: extraWsts) { + log.debug("name: " + wst.getDescription()); + wst.storeDependencies(river); + } + } + } + + public void storeOfficialLines() { + if (!Config.INSTANCE.skipOfficialLines()) { + log.info("store official lines wsts"); + River river = getPeer(); + for (ImportWst wst: officialLines) { + log.debug("name: " + wst.getDescription()); + wst.storeDependencies(river); + } + } + } + + public void storeFloodWater() { + if (!Config.INSTANCE.skipFloodWater()) { + log.info("store flood water wsts"); + River river = getPeer(); + for (ImportWst wst: floodWater) { + log.debug("name: " + wst.getDescription()); + wst.storeDependencies(river); + } + } + } + + + public void storeFloodProtection() { + if (!Config.INSTANCE.skipFloodProtection()) { + log.info("store flood protection wsts"); + River river = getPeer(); + for (ImportWst wst: floodProtection) { + log.debug("name: " + wst.getDescription()); + wst.storeDependencies(river); + } + } + } + + + public void storeBedHeight() { + if (!Config.INSTANCE.skipBedHeightSingle()) { + log.info("store bed heights single"); + storeBedHeightSingle(); + } + + if (!Config.INSTANCE.skipBedHeightEpoch()) { + log.info("store bed height epoch."); + storeBedHeightEpoch(); + } + } + + + private void storeBedHeightSingle() { + River river = getPeer(); + + if (bedHeightSingles != null) { + for (ImportBedHeight tmp: bedHeightSingles) { + ImportBedHeightSingle single = (ImportBedHeightSingle) tmp; + + String desc = single.getDescription(); + + log.debug("name: " + desc); + + single.storeDependencies(river); + + } + } + else { + log.info("No single bed heights to store."); + } + } + + + private void storeBedHeightEpoch() { + River river = getPeer(); + + if (bedHeightEpochs != null) { + for (ImportBedHeight tmp: bedHeightEpochs) { + ImportBedHeightEpoch epoch = (ImportBedHeightEpoch) tmp; + + String desc = epoch.getDescription(); + + log.debug("name: " + desc); + + epoch.storeDependencies(river); + + } + } + else { + log.info("No epoch bed heights to store."); + } + } + + public void storeSedimentDensity() { + if (!Config.INSTANCE.skipSedimentDensity()) { + log.info("store sediment density"); + + River river = getPeer(); + + for (ImportSedimentDensity density: sedimentDensities) { + String desc = density.getDescription(); + + log.debug("name: " + desc); + + density.storeDependencies(river); + + } + } + } + + public void storeMorphologicalWidth() { + if (!Config.INSTANCE.skipMorphologicalWidth()) { + log.info("store morphological width"); + + River river = getPeer(); + + for (ImportMorphWidth width: morphologicalWidths) { + + width.storeDependencies(river); + + } + } + } + + public void storeFlowVelocity() { + if (!Config.INSTANCE.skipFlowVelocity()) { + log.info("store flow velocity"); + + River river = getPeer(); + + for (ImportFlowVelocityModel flowVelocityModel: flowVelocityModels){ + + flowVelocityModel.storeDependencies(river); + + } + + for (ImportFlowVelocityMeasurement m: flowVelocityMeasurements) { + + m.storeDependencies(river); + + } + } + } + + + public void storeSedimentYield() { + if (!Config.INSTANCE.skipSedimentYield()) { + log.info("store sediment yield data"); + + River river = getPeer(); + + for (ImportSedimentYield sedimentYield: sedimentYields) { + + sedimentYield.storeDependencies(river); + + } + } + } + + + public void storeMeasurementStations() { + if (!Config.INSTANCE.skipMeasurementStations()) { + log.info("store measurement stations"); + + River river = getPeer(); + + int count = 0; + + for (ImportMeasurementStation station: measurementStations) { + + boolean success = station.storeDependencies(river); + if (success) { + count++; + } + + } + + log.info("stored " + count + " measurement stations."); + } + } + + + public void storeSQRelations() { + if (!Config.INSTANCE.skipSQRelation()) { + log.info("store sq relations"); + + River river = getPeer(); + + int count = 0; + + for (ImportSQRelation sqRelation: sqRelations) { + + sqRelation.storeDependencies(river); + count++; + + } + + log.info("stored " + count + " sq relations."); + } + } + + + public void storeAnnotations() { + if (!Config.INSTANCE.skipAnnotations()) { + River river = getPeer(); + for (ImportAnnotation annotation: annotations) { + annotation.getPeer(river); + } + } + } + + public void storeGauges() { + if (!Config.INSTANCE.skipGauges()) { + log.info("store gauges:"); + River river = getPeer(); + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + for (ImportGauge gauge: gauges) { + log.info("\tgauge: " + gauge.getName()); + gauge.storeDependencies(river); + ImporterSession.getInstance().getDatabaseSession(); + session.flush(); + } + } + } + + public River getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from River where name=:name"); + + Unit u = null; + if (wstUnit != null) { + u = wstUnit.getPeer(); + } + + query.setString("name", name); + List<River> rivers = query.list(); + if (rivers.isEmpty()) { + log.info("Store new river '" + name + "'"); + peer = new River(name, u); + if (!Config.INSTANCE.skipBWASTR()) { + peer.setOfficialNumber(officialNumber); + } + session.save(peer); + } + else { + peer = rivers.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSQRelation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,109 @@ +package de.intevation.flys.importer; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.exception.ConstraintViolationException; + +import de.intevation.flys.model.River; +import de.intevation.flys.model.SQRelation; +import de.intevation.flys.model.TimeInterval; + + +public class ImportSQRelation { + + private static Logger log = Logger.getLogger(ImportSQRelation.class); + + private ImportTimeInterval timeInterval; + + private String description; + + private List<ImportSQRelationValue> values; + + private SQRelation peer; + + public ImportSQRelation() { + this.values = new ArrayList<ImportSQRelationValue>(); + } + + public void storeDependencies(River river) { + log.info("store dependencies"); + + SQRelation peer = getPeer(river); + + if (peer != null) { + int count = 0; + + for (ImportSQRelationValue value : values) { + try { + value.storeDependencies(peer); + count++; + } + catch (SQLException sqle) { + log.warn("ISQ: Unable to store sq relation value.", sqle); + } + catch (ConstraintViolationException cve) { + log.warn("ISQ: Unable to store sq relation value.", cve); + } + } + + log.info("stored " + count + " sq relation values."); + } + } + + public SQRelation getPeer(River river) { + log.debug("getPeer()"); + + if (peer == null) { + TimeInterval timeInter = timeInterval.getPeer(); + + if (timeInter == null) { + log.warn("ISQ: Cannot determine sq relation without time interval"); + return null; + } + + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + Query query = session + .createQuery("FROM SQRelation WHERE river=:river AND timeInterval=:timeInter"); + + query.setParameter("river", river); + query.setParameter("timeInter", timeInter); + + List<SQRelation> sq = query.list(); + + if (sq.isEmpty()) { + log.info("create new SQ relation '" + description + "'"); + + peer = new SQRelation(river, timeInter, description); + session.save(peer); + } + else { + peer = sq.get(0); + } + } + + return peer; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + public void addValue(ImportSQRelationValue value) { + if (value != null) { + this.values.add(value); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSQRelationValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,140 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; +import java.sql.SQLException; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.exception.ConstraintViolationException; + +import de.intevation.flys.model.MeasurementStation; +import de.intevation.flys.model.SQRelation; +import de.intevation.flys.model.SQRelationValue; + + +public class ImportSQRelationValue { + + private static Logger log = Logger.getLogger(ImportSQRelationValue.class); + + + private SQRelationValue peer; + + private String parameter; + + private Double km; + private Double a; + private Double b; + private Double qMax; + private Double rSQ; + private Integer nTot; + private Integer nOutlier; + private Double cFerguson; + private Double cDuan; + + + public ImportSQRelationValue( + String parameter, + Double km, + Double a, + Double b, + Double qMax, + Double rSQ, + Integer nTot, + Integer nOutlier, + Double cFerguson, + Double cDuan + ) { + this.parameter = parameter; + this.km = km; + this.a = a; + this.b = b; + this.qMax = qMax; + this.rSQ = rSQ; + this.nTot = nTot; + this.nOutlier = nOutlier; + this.cFerguson = cFerguson; + this.cDuan = cDuan; + } + + + public void storeDependencies(SQRelation owner) + throws SQLException, ConstraintViolationException + { + getPeer(owner); + } + + + public SQRelationValue getPeer(SQRelation owner) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from MeasurementStation " + + " where station between :kml and :kmh"); + query.setDouble("kml", km - 1e-4); + query.setDouble("kmh", km + 1e-4); + + List<MeasurementStation> result = query.list(); + + if (result.isEmpty()) { + log.error("No measurement stations found at km " + km); + return null; + } + + Query query2 = session.createQuery( + "from SQRelationValue " + + " where sqRelation=:owner " + + " and parameter=:parameter" + + " and measurementStation=:measurementStation" + + " and a=:a" + + " and b=:b" + + " and qMax=:qMax" + + " and rSQ=:rSQ" + + " and cFerguson=:cFerguson" + + " and cDuan=:cDuan"); + + query2.setParameter("owner", owner); + query2.setString("parameter", parameter); + query2.setParameter("measurementStation", result.get(0)); + query2.setBigDecimal("a", toBigDecimal(a)); + query2.setBigDecimal("b", toBigDecimal(b)); + query2.setBigDecimal("qMax", toBigDecimal(qMax)); + query2.setBigDecimal("rSQ", toBigDecimal(rSQ)); + query2.setBigDecimal("cFerguson", toBigDecimal(cFerguson)); + query2.setBigDecimal("cDuan", toBigDecimal(cDuan)); + + List<SQRelationValue> values = query2.list(); + + if (values.isEmpty()) { + peer = new SQRelationValue( + owner, + parameter, + result.get(0), + a, + b, + qMax, + rSQ, + nTot, + nOutlier, + cFerguson, + cDuan + ); + + session.save(peer); + } + else { + peer = values.get(0); + } + } + return peer; + } + + private static final BigDecimal toBigDecimal(Double x) { + if (x == null) return null; + return new BigDecimal(x); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSedimentDensity.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,97 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.hibernate.Query; +import org.hibernate.Session; + +import de.intevation.flys.model.River; +import de.intevation.flys.model.SedimentDensity; + + +public class ImportSedimentDensity { + + private static Logger log = Logger.getLogger(ImportSedimentDensity.class); + + protected SedimentDensity peer; + + protected ImportDepth depth; + + protected String description; + + protected List<ImportSedimentDensityValue> values; + + public ImportSedimentDensity(String description) { + this.description = description; + this.values = new ArrayList<ImportSedimentDensityValue>(); + } + + public String getDescription() { + return description; + } + + public void setDepth(ImportDepth depth) { + this.depth = depth; + } + + public void addValue(ImportSedimentDensityValue value) { + values.add(value); + } + + public void storeDependencies(River river) { + log.info("store dependencies"); + + if (depth != null) { + depth.storeDependencies(); + } + + SedimentDensity peer = getPeer(river); + + if (peer != null) { + log.info("store sediment density values."); + for (ImportSedimentDensityValue value : values) { + value.storeDependencies(peer); + } + } + } + + public SedimentDensity getPeer(River river) { + log.info("get peer"); + + if (depth == null) { + log.warn("cannot store sediment density '" + description + + "': no depth"); + return null; + } + + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + + Query query = session.createQuery("from SedimentDensity where " + + " river=:river and " + " depth=:depth"); + + query.setParameter("river", river); + query.setParameter("depth", depth.getPeer()); + + List<SedimentDensity> density = query.list(); + + if (density.isEmpty()) { + log.debug("Create new SedimentDensity DB instance."); + + peer = new SedimentDensity(river, depth.getPeer(), + description); + + session.save(peer); + } + else { + peer = density.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSedimentDensityValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,101 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.SedimentDensity; +import de.intevation.flys.model.SedimentDensityValue; + + +public class ImportSedimentDensityValue { + + private static final Logger log = + Logger.getLogger(ImportSedimentDensityValue.class); + + + protected SedimentDensityValue peer; + + protected BigDecimal station; + + protected BigDecimal shoreOffset; + + protected BigDecimal density; + + private BigDecimal year; + + protected String description; + + + public ImportSedimentDensityValue( + BigDecimal station, + BigDecimal shoreOffset, + BigDecimal density, + BigDecimal year, + String description + ) { + this.station = station; + this.shoreOffset = shoreOffset; + this.density = density; + this.year = year; + this.description = description; + } + + + public void storeDependencies(SedimentDensity sedimentDensity) { + log.info("store dependencies"); + + getPeer(sedimentDensity); + } + + + public SedimentDensityValue getPeer(SedimentDensity sedimentDensity) { + log.info("get peer"); + + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + + Query query = session.createQuery( + "from SedimentDensityValue where " + + " sedimentDensity=:sedimentDensity and " + + " station=:station and " + + " shoreOffset=:shoreOffset and " + + " density=:density and " + + " year=:year and " + + " description=:description"); + + query.setParameter("sedimentDensity", sedimentDensity); + query.setParameter("station", station); + query.setParameter("shoreOffset", shoreOffset); + query.setParameter("density", density); + query.setParameter("year", year); + query.setParameter("description", description); + + List<SedimentDensityValue> values = query.list(); + if (values.isEmpty()) { + log.debug("Create new SedimentDensityValue DB instance."); + + peer = new SedimentDensityValue( + sedimentDensity, + station, + shoreOffset, + density, + year, + description); + + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSedimentYield.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,121 @@ +package de.intevation.flys.importer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.GrainFraction; +import de.intevation.flys.model.River; +import de.intevation.flys.model.SedimentYield; +import de.intevation.flys.model.TimeInterval; +import de.intevation.flys.model.Unit; + + +public class ImportSedimentYield { + + private static Logger log = Logger.getLogger(ImportSedimentYield.class); + + private ImportGrainFraction grainFraction; + + private ImportUnit unit; + + private ImportTimeInterval timeInterval; + + private String description; + + private List<ImportSedimentYieldValue> values; + + private SedimentYield peer; + + public ImportSedimentYield(String description) { + this.values = new ArrayList<ImportSedimentYieldValue>(); + this.description = description; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + public void setUnit(ImportUnit unit) { + this.unit = unit; + } + + public void setGrainFraction(ImportGrainFraction grainFraction) { + this.grainFraction = grainFraction; + } + + public void addValue(ImportSedimentYieldValue value) { + this.values.add(value); + } + + public void storeDependencies(River river) { + log.debug("store dependencies"); + + if (grainFraction != null) { + grainFraction.storeDependencies(); + } + + SedimentYield peer = getPeer(river); + + if (peer != null) { + int i = 0; + + for (ImportSedimentYieldValue value : values) { + value.storeDependencies(peer); + i++; + } + + log.info("stored " + i + " sediment yield values."); + } + } + + public SedimentYield getPeer(River river) { + log.debug("get peer"); + + GrainFraction gf = grainFraction != null ? grainFraction.getPeer() + : null; + + Unit u = unit != null ? unit.getPeer() : null; + + TimeInterval ti = timeInterval != null ? timeInterval.getPeer() : null; + + if (ti == null || u == null) { + log.warn("Skip invalid SedimentYield: time interval or unit null!"); + return null; + } + + if (peer == null) { + Session session = ImporterSession.getInstance() + .getDatabaseSession(); + Query query = session.createQuery("from SedimentYield where " + + " river=:river and " + + " grainFraction=:grainFraction and " + " unit=:unit and " + + " timeInterval=:timeInterval and " + + " description=:description"); + + query.setParameter("river", river); + query.setParameter("grainFraction", gf); + query.setParameter("unit", u); + query.setParameter("timeInterval", ti); + query.setParameter("description", description); + + List<SedimentYield> yields = query.list(); + if (yields.isEmpty()) { + log.debug("create new SedimentYield"); + + peer = new SedimentYield(river, u, ti, gf, description); + session.save(peer); + } + else { + peer = yields.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportSedimentYieldValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,58 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.SedimentYield; +import de.intevation.flys.model.SedimentYieldValue; + + +public class ImportSedimentYieldValue { + + private Double station; + private Double value; + + private SedimentYieldValue peer; + + + public ImportSedimentYieldValue(Double station, Double value) { + this.station = station; + this.value = value; + } + + + public void storeDependencies(SedimentYield sedimentYield) { + getPeer(sedimentYield); + } + + + public SedimentYieldValue getPeer(SedimentYield sedimentYield) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from SedimentYieldValue where " + + " sedimentYield=:sedimentYield and " + + " station=:station and " + + " value=:value" + ); + + query.setParameter("sedimentYield", sedimentYield); + query.setParameter("station", station); + query.setParameter("value", value); + + List<SedimentYieldValue> values = query.list(); + if (values.isEmpty()) { + peer = new SedimentYieldValue(sedimentYield, station, value); + session.save(peer); + } + else { + peer = values.get(0); + } + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportTimeInterval.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,98 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.TimeInterval; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; +import java.util.Date; + +import org.apache.log4j.Logger; + +public class ImportTimeInterval +{ + private static Logger log = Logger.getLogger(ImportTimeInterval.class); + + protected Date startTime; + protected Date stopTime; + + protected TimeInterval peer; + + public ImportTimeInterval() { + } + + public ImportTimeInterval(Date startTime) { + this.startTime = startTime; + this.stopTime = null; + } + + public ImportTimeInterval(Date startTime, Date stopTime) { + Date start; + Date stop; + if (startTime == null) { + start = stopTime; + stop = null; + } + else { + start = startTime; + stop = stopTime; + } + + if (stop != null && start.after(stop)) { + this.stopTime = start; + this.startTime = stop; + } + else { + this.startTime = start; + this.stopTime = stop; + } + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getStopTime() { + return stopTime; + } + + public void setStopTime(Date stopTime) { + this.stopTime = stopTime; + } + + public TimeInterval getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + if (startTime == null) { + log.error("Null Start time will be ignored."); + } + Query query; + if (stopTime == null) { + query = session.createQuery( + "from TimeInterval where startTime=:a and stopTime is null"); + } + else { + query = session.createQuery( + "from TimeInterval where startTime=:a and stopTime=:b"); + query.setParameter("b", stopTime); + } + query.setParameter("a", startTime); + + List<TimeInterval> intervals = query.list(); + if (intervals.isEmpty()) { + peer = new TimeInterval(startTime, stopTime); + session.save(peer); + } + else { + peer = intervals.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportUnit.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,52 @@ +package de.intevation.flys.importer; + +import java.util.List; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.model.Unit; + + +public class ImportUnit +{ + private static final Logger log = Logger.getLogger(ImportUnit.class); + + protected String name; + + protected Unit peer; + + + public ImportUnit(String name) { + this.name = name; + } + + + public String getName() { + return name; + } + + + public Unit getPeer() { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery("from Unit where name=:name"); + query.setParameter("name", name); + + List<Unit> units = query.list(); + if (units.isEmpty()) { + log.info("Store new unit '" + name + "'"); + + peer = new Unit(name); + session.save(peer); + } + else { + peer = units.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportWst.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,130 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Wst; +import de.intevation.flys.model.River; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.ArrayList; +import java.util.List; + +public class ImportWst +{ + private static Logger log = Logger.getLogger(ImportWst.class); + + protected String description; + + protected Integer kind; + + protected List<ImportWstColumn> columns; + + protected ImportUnit unit; + + /** Wst as in db. */ + protected Wst peer; + + public ImportWst() { + kind = 0; + columns = new ArrayList<ImportWstColumn>(); + } + + public ImportWst(String description) { + this(); + this.description = description; + } + + public String getDescription() { + return description; + } + + public Integer getKind() { + return kind; + } + + public void setKind(Integer kind) { + this.kind = kind; + } + + + public void setDescription(String description) { + this.description = description; + } + + /** Create columns that can be accessed with getColumn. */ + public void setNumberColumns(int numColumns) { + for (int i = 0; i < numColumns; ++i) { + columns.add(new ImportWstColumn(this, null, null, i)); + } + } + + public int getNumberColumns() { + return columns.size(); + } + + public ImportWstColumn getColumn(int index) { + return columns.get(index); + } + + public List<ImportWstColumn> getColumns() { + return columns; + } + + /** Adds a column. Assumes that columns wst is this instance. */ + public void addColumn(ImportWstColumn column) { + columns.add(column); + } + + public ImportUnit getUnit() { + return unit; + } + + public void setUnit(ImportUnit unit) { + this.unit = unit; + } + + public void storeDependencies(River river) { + + log.info("store '" + description + "'"); + Wst wst = getPeer(river); + + for (ImportWstColumn column: columns) { + column.storeDependencies(river); + } + + Session session = ImporterSession.getInstance().getDatabaseSession(); + session.flush(); + } + + public void fixRangesOrder() { + for (ImportWstColumn column: columns) { + column.fixRangesOrder(); + } + } + + /** Get corresponding mapped wst (from database). */ + public Wst getPeer(River river) { + if (peer == null) { + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from Wst where " + + "river=:river and description=:description and kind=:kind"); + query.setParameter("river", river); + query.setParameter("description", description); + query.setParameter("kind", kind); + List<Wst> wsts = query.list(); + if (wsts.isEmpty()) { + peer = new Wst(river, description, kind); + session.save(peer); + } + else { + peer = wsts.get(0); + } + + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportWstColumn.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,160 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.Wst; +import de.intevation.flys.model.WstColumn; +import de.intevation.flys.model.River; +import de.intevation.flys.model.TimeInterval; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; +import java.util.ArrayList; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + + +/** Unmapped column of a WST. */ +public class ImportWstColumn +{ + private static Logger log = Logger.getLogger(ImportWstColumn.class); + + protected ImportWst wst; + protected String name; + protected String description; + protected Integer position; + + protected ImportTimeInterval timeInterval; + + protected List<ImportWstColumnQRange> columnQRanges; + protected List<ImportWstColumnValue> columnValues; + + protected WstColumn peer; + + public ImportWstColumn() { + columnQRanges = new ArrayList<ImportWstColumnQRange>(); + columnValues = new ArrayList<ImportWstColumnValue>(); + } + + public ImportWstColumn( + ImportWst wst, + String name, + String description, + Integer position + ) { + this(); + this.wst = wst; + this.name = name; + this.description = description; + this.position = position; + } + + public ImportWst getWst() { + return wst; + } + + public void setWst(ImportWst wst) { + this.wst = wst; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getPosition() { + return position; + } + + public void setPosition(Integer position) { + this.position = position; + } + + public void addColumnValue(BigDecimal position, BigDecimal w) { + columnValues.add( + new ImportWstColumnValue(this, position, w)); + } + + public void addColumnQRange(ImportWstQRange columnQRange) { + columnQRanges.add( + new ImportWstColumnQRange(this, columnQRange)); + } + + + /** Get the Column Values stored in this column. */ + public List<ImportWstColumnValue> getColumnValues() { + return columnValues; + } + + + public void storeDependencies(River river) { + log.info("store column '" + name + "'"); + WstColumn column = getPeer(river); + + for (ImportWstColumnQRange columnQRange: columnQRanges) { + columnQRange.getPeer(river); + } + + for (ImportWstColumnValue columnValue: columnValues) { + columnValue.getPeer(river); + } + } + + public ImportTimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(ImportTimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + /** Get corresponding mapped wst-column (from database). */ + public WstColumn getPeer(River river) { + if (peer == null) { + Wst w = wst.getPeer(river); + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from WstColumn where " + + "wst=:wst and name=:name and description=:description" + + " and position=:position"); + query.setParameter("wst", w); + query.setParameter("name", name); + query.setParameter("description", description); + query.setParameter("position", position); + + TimeInterval ti = timeInterval != null + ? timeInterval.getPeer() + : null; + + List<WstColumn> columns = query.list(); + if (columns.isEmpty()) { + peer = new WstColumn(w, name, description, position, ti); + session.save(peer); + } + else { + peer = columns.get(0); + } + } + return peer; + } + + public void fixRangesOrder() { + for (ImportWstColumnQRange wcqr: columnQRanges) { + wcqr.fixRangesOrder(); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportWstColumnQRange.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,73 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.WstColumnQRange; +import de.intevation.flys.model.WstQRange; +import de.intevation.flys.model.WstColumn; +import de.intevation.flys.model.River; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportWstColumnQRange +{ + protected ImportWstColumn wstColumn; + protected ImportWstQRange qRange; + + protected WstColumnQRange peer; + + public ImportWstColumnQRange() { + } + + public ImportWstColumnQRange( + ImportWstColumn wstColumn, + ImportWstQRange qRange + ) { + this.wstColumn = wstColumn; + this.qRange = qRange; + } + + public ImportWstColumn getWstColumn() { + return wstColumn; + } + + public void setWstColumn(ImportWstColumn wstColumn) { + this.wstColumn = wstColumn; + } + + public ImportWstQRange getQRange() { + return qRange; + } + + public void setQRange(ImportWstQRange qRange) { + this.qRange = qRange; + } + + public void fixRangesOrder() { + qRange.fixRangesOrder(); + } + + public WstColumnQRange getPeer(River river) { + if (peer == null) { + WstColumn c = wstColumn.getPeer(river); + WstQRange q = qRange.getPeer(river); + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from WstColumnQRange where " + + "wstColumn=:c and wstQRange=:q"); + query.setParameter("c", c); + query.setParameter("q", q); + List<WstColumnQRange> cols = query.list(); + if (cols.isEmpty()) { + peer = new WstColumnQRange(c, q); + session.save(peer); + } + else { + peer = cols.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportWstColumnValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,68 @@ +package de.intevation.flys.importer; + +import de.intevation.flys.model.WstColumnValue; +import de.intevation.flys.model.WstColumn; +import de.intevation.flys.model.River; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +public class ImportWstColumnValue +{ + protected Logger logger = Logger.getLogger(ImportWstColumnValue.class); + + protected BigDecimal position; + protected BigDecimal w; + protected ImportWstColumn wstColumn; + + protected WstColumnValue peer; + + public ImportWstColumnValue() { + } + + public ImportWstColumnValue( + ImportWstColumn wstColumn, + BigDecimal position, + BigDecimal w + ) { + this.wstColumn = wstColumn; + this.position = position; + this.w = w; + } + + public BigDecimal getPosition() { + return position; + } + + public void setPosition(BigDecimal position) { + this.position = position; + } + + public BigDecimal getW() { + return w; + } + + public void setW(BigDecimal w) { + this.w = w; + } + + public ImportWstColumn getWstColumn() { + return wstColumn; + } + + public void setWstColumn(ImportWstColumn wstColumn) { + this.wstColumn = wstColumn; + } + + public WstColumnValue getPeer(River river) { + if (peer == null) { + WstColumn c = wstColumn.getPeer(river); + peer = ImporterSession.getInstance().getWstColumnValue( + c, position, w); + } + + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImportWstQRange.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,73 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import de.intevation.flys.model.WstQRange; +import de.intevation.flys.model.River; +import de.intevation.flys.model.Range; + +import org.hibernate.Session; +import org.hibernate.Query; + +import java.util.List; + +public class ImportWstQRange +{ + protected ImportRange range; + protected BigDecimal q; + + protected WstQRange peer; + + public ImportWstQRange() { + } + + public ImportWstQRange( + ImportRange range, + BigDecimal q + ) { + this.range = range; + this.q = q; + } + + public ImportRange getRange() { + return range; + } + + public void setRange(ImportRange range) { + this.range = range; + } + + public BigDecimal getQ() { + return q; + } + + public void setQ(BigDecimal q) { + this.q = q; + } + + public void fixRangesOrder() { + range.fixRangesOrder(); + } + + public WstQRange getPeer(River river) { + if (peer == null) { + Range r = range.getPeer(river); + Session session = ImporterSession.getInstance().getDatabaseSession(); + Query query = session.createQuery( + "from WstQRange where " + + "range=:range and q=:q"); + query.setParameter("range", r); + query.setParameter("q", q); + List<WstQRange> wstQRanges = query.list(); + if (wstQRanges.isEmpty()) { + peer = new WstQRange(r, q); + session.save(peer); + } + else { + peer = wstQRanges.get(0); + } + } + return peer; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/Importer.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,200 @@ +package de.intevation.flys.importer; + +import de.intevation.artifacts.common.utils.XMLUtils; + +import de.intevation.flys.importer.parsers.AnnotationClassifier; +import de.intevation.flys.importer.parsers.BundesWasserStrassenParser; +import de.intevation.flys.importer.parsers.InfoGewParser; + +import java.io.File; +import java.io.IOException; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.sql.SQLException; + +import org.apache.log4j.Logger; + +import org.hibernate.Transaction; +import org.hibernate.HibernateException; + +import org.w3c.dom.Document; + +import de.intevation.flys.utils.StringUtil; + +/** Data Importer. Further processing happens per-river. */ +public class Importer +{ + /** Private logger. */ + private static Logger log = Logger.getLogger(Importer.class); + + private static String BWASTR_ID_CSV_FILE = "BWASTR_ID.csv"; + + protected List<ImportRiver> rivers; + + public Importer() { + } + + public Importer(List<ImportRiver> rivers) { + this.rivers = rivers; + } + + public List<ImportRiver> getRivers() { + return rivers; + } + + public void setRivers(List<ImportRiver> rivers) { + this.rivers = rivers; + } + + /** Write rivers and their dependencies/dependants to db. */ + public void writeRivers() { + log.debug("write rivers started"); + + for (ImportRiver river: rivers) { + log.debug("writing river '" + river.getName() + "'"); + river.storeDependencies(); + ImporterSession.getInstance().getDatabaseSession().flush(); + } + + log.debug("write rivers finished"); + } + + public void writeToDatabase() { + + Transaction tx = null; + + try { + tx = ImporterSession.getInstance() + .getDatabaseSession().beginTransaction(); + + try { + writeRivers(); + } + catch (HibernateException he) { + Throwable t = he.getCause(); + while (t instanceof SQLException) { + SQLException sqle = (SQLException) t; + log.error("SQL exeception chain:", sqle); + t = sqle.getNextException(); + } + throw he; + } + + tx.commit(); + } + catch (RuntimeException re) { + if (tx != null) { + tx.rollback(); + } + throw re; + } + } + + public static AnnotationClassifier getAnnotationClassifier() { + String annotationTypes = Config.INSTANCE.getAnnotationTypes(); + + if (annotationTypes == null) { + log.info("no annotation types file configured."); + return null; + } + + File file = new File(annotationTypes); + + log.info("use annotation types file '" + file + "'"); + + if (!(file.isFile() && file.canRead())) { + log.warn("annotation type file '" + file + "' is not readable."); + return null; + } + + Document rules = XMLUtils.parseDocument(file); + + if (rules == null) { + log.warn("cannot parse annotation types file."); + return null; + } + + return new AnnotationClassifier(rules); + } + + + /** Starting point for importing river data. */ + public static void main(String [] args) { + + InfoGewParser infoGewParser = new InfoGewParser( + getAnnotationClassifier()); + + log.info("Start parsing rivers..."); + + File bwastrFile = null; + + for (String gew: args) { + log.info("parsing info gew file: " + gew); + File gewFile = new File(gew); + if (bwastrFile == null) { + bwastrFile = new File(gewFile.getParentFile(), BWASTR_ID_CSV_FILE); + } + try { + infoGewParser.parse(gewFile); + } + catch (IOException ioe) { + log.error("error while parsing gew: " + gew, ioe); + System.exit(1); + } + } + + String gew = Config.INSTANCE.getInfoGewFile(); + if (gew != null && gew.length() > 0) { + log.info("parsing info gew file: " + gew); + File gewFile = new File(gew); + if (bwastrFile == null) { + bwastrFile = new File(gewFile.getParentFile(), BWASTR_ID_CSV_FILE); + } + try { + infoGewParser.parse(gewFile); + } + catch (IOException ioe) { + log.error("error while parsing gew: " + gew, ioe); + System.exit(1); + } + } + + // Look for official numbers. + BundesWasserStrassenParser bwastrIdParser = + new BundesWasserStrassenParser(); + + // Read bwastFile (river-dir + BWASTR_ID_CSV_FILE). + if (!Config.INSTANCE.skipBWASTR()) { + try{ + bwastrIdParser.parse(bwastrFile); + HashMap<String,Long> map = bwastrIdParser.getMap(); + + // Now link rivers with official numbers. + for(ImportRiver river: infoGewParser.getRivers()) { + for(Map.Entry<String, Long> entry: map.entrySet()) { + if (StringUtil.containsIgnoreCase(entry.getKey(), river.getName())) { + river.setOfficialNumber(entry.getValue()); + log.debug(river.getName() + " is mapped to bwastr " + entry.getValue()); + } + } + } + } catch (IOException ioe) { + log.warn("BWASTR-file could not be loaded."); + } + } + else { + log.debug("skip reading BWASTR_ID.csv"); + } + + if (!Config.INSTANCE.dryRun()) { + new Importer(infoGewParser.getRivers()).writeToDatabase(); + } + else { + log.info("Dry run, not writing to database."); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ImporterSession.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,187 @@ +package de.intevation.flys.importer; + +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +import java.math.BigDecimal; + +import org.hibernate.SessionFactory; +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.FlushMode; + +import de.intevation.flys.backend.SessionFactoryProvider; + +import de.intevation.flys.model.WstColumnValue; +import de.intevation.flys.model.WstColumn; +import de.intevation.flys.model.DischargeTableValue; +import de.intevation.flys.model.DischargeTable; +import de.intevation.flys.model.Range; +import de.intevation.flys.model.River; + +import org.apache.log4j.Logger; + +import de.intevation.artifacts.common.utils.LRUCache; + +public class ImporterSession +{ + private static Logger log = Logger.getLogger(ImporterSession.class); + + private static final ThreadLocal<ImporterSession> SESSION = + new ThreadLocal<ImporterSession>() { + @Override + protected ImporterSession initialValue() { + return new ImporterSession(); + } + }; + + protected Session databaseSession; + + protected LRUCache<Integer, Map<ValueKey, WstColumnValue>> + wstColumnValues; + + protected LRUCache<Integer, Map<ValueKey, DischargeTableValue>> + dischargeTableValues; + + protected LRUCache<Integer, Map<ValueKey, Range>> + ranges; + + public static ImporterSession getInstance() { + return SESSION.get(); + } + + public ImporterSession() { + SessionFactory sessionFactory = + SessionFactoryProvider.createSessionFactory(); + databaseSession = sessionFactory.openSession(); + //databaseSession.setFlushMode(FlushMode.MANUAL); + + wstColumnValues = + new LRUCache<Integer, Map<ValueKey, WstColumnValue>>(); + + dischargeTableValues = + new LRUCache<Integer, Map<ValueKey, DischargeTableValue>>(); + + ranges = new LRUCache<Integer, Map<ValueKey, Range>>(); + } + + public Session getDatabaseSession() { + return databaseSession; + } + + public WstColumnValue getWstColumnValue( + WstColumn column, + BigDecimal position, + BigDecimal w + ) { + Integer c = column.getId(); + + Map<ValueKey, WstColumnValue> map = wstColumnValues.get(c); + + if (map == null) { + map = new TreeMap<ValueKey, WstColumnValue>( + ValueKey.EPSILON_COMPARATOR); + wstColumnValues.put(c, map); + Query query = databaseSession.createQuery( + "from WstColumnValue where wstColumn.id=:cid"); + query.setParameter("cid", c); + for (Iterator iter = query.iterate(); iter.hasNext();) { + WstColumnValue wcv = (WstColumnValue)iter.next(); + map.put(new ValueKey(wcv.getPosition(), wcv.getW()), wcv); + } + } + + ValueKey key = new ValueKey(position, w); + + WstColumnValue wcv = map.get(key); + + if (wcv != null) { + return wcv; + } + + wcv = new WstColumnValue(column, position, w); + + databaseSession.save(wcv); + + map.put(key, wcv); + + return wcv; + } + + public DischargeTableValue getDischargeTableValue( + DischargeTable table, + BigDecimal q, + BigDecimal w + ) { + Integer t = table.getId(); + + Map<ValueKey, DischargeTableValue> map = + dischargeTableValues.get(t); + + if (map == null) { + map = new TreeMap<ValueKey, DischargeTableValue>( + ValueKey.EPSILON_COMPARATOR); + dischargeTableValues.put(t, map); + Query query = databaseSession.createQuery( + "from DischargeTableValue where dischargeTable.id=:tid"); + query.setParameter("tid", t); + for (Iterator iter = query.iterate(); iter.hasNext();) { + DischargeTableValue dctv = (DischargeTableValue)iter.next(); + map.put(new ValueKey(dctv.getQ(), dctv.getW()), dctv); + } + } + + ValueKey key = new ValueKey(q, w); + + DischargeTableValue dctv = map.get(key); + + if (dctv != null) { + return dctv; + } + + dctv = new DischargeTableValue(table, q, w); + + databaseSession.save(dctv); + + map.put(key, dctv); + + return dctv; + } + + public Range getRange(River river, BigDecimal a, BigDecimal b) { + Integer r = river.getId(); + + Map<ValueKey, Range> map = ranges.get(r); + + if (map == null) { + map = new TreeMap<ValueKey, Range>( + ValueKey.EPSILON_COMPARATOR); + ranges.put(r, map); + Query query = databaseSession.createQuery( + "from Range where river.id=:rid"); + query.setParameter("rid", r); + for (Iterator iter = query.iterate(); iter.hasNext();) { + Range range = (Range)iter.next(); + map.put(new ValueKey(range.getA(), range.getB()), range); + } + } + + ValueKey key = new ValueKey(a, b); + + Range range = map.get(key); + + if (range != null) { + return range; + } + + range = new Range(a, b, river); + + databaseSession.save(range); + + map.put(key, range); + + return range; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/ValueKey.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,63 @@ +package de.intevation.flys.importer; + +import java.math.BigDecimal; + +import java.util.Comparator; + +public class ValueKey +{ + public static final double EPSILON = 1e-6; + + public static final Comparator<ValueKey> EPSILON_COMPARATOR = + new Comparator<ValueKey>() + { + public int compare(ValueKey x, ValueKey y) { + int cmp = ValueKey.compare(x.a, y.a); + if (cmp != 0) return cmp; + return ValueKey.compare(x.b, y.b); + } + }; + + public static int compare(BigDecimal a, BigDecimal b) { + if (a == null && b == null) return 0; + if (a != null && b == null) return +1; + if (a == null && b != null) return -1; + + double diff = a.doubleValue() - b.doubleValue(); + if (diff < -EPSILON) return -1; + return diff > EPSILON ? +1 : 0; + } + + protected BigDecimal a; + protected BigDecimal b; + + public ValueKey() { + } + + public ValueKey(BigDecimal a, BigDecimal b) { + this.a = a; + this.b = b; + } + + @Override + public int hashCode() { + return ((a != null ? a.hashCode() : 0) << 16) + | (b != null ? b.hashCode() : 0); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof ValueKey)) { + return false; + } + ValueKey o = (ValueKey)other; + return !( + (a == null && o.a != null) + || (a != null && o.a == null) + || (a != null && !a.equals(o.a)) + || (b == null && o.b != null) + || (b != null && o.b == null) + || (b != null && !b.equals(o.b))); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/XY.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,56 @@ +package de.intevation.flys.importer; + + +/** Two doubles and an int index. */ +public class XY +implements Comparable<XY> +{ + public static final double X_EPSILON = 1e-4; + + protected double x; + protected double y; + protected int index; + + public XY() { + } + + public XY(double x, double y, int index) { + this.x = x; + this.y = y; + this.index = index; + } + + @Override + public int compareTo(XY other) { + if (x + X_EPSILON < other.x) return -1; + if (x > other.x + X_EPSILON) return +1; + if (index < other.index) return -1; + if (index > other.index) return +1; + return 0; + } + + public double getX() { + return x; + } + + public void setX(double x) { + this.x = x; + } + + public double getY() { + return y; + } + + public void setY(double y) { + this.y = y; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/AnnotationClassifier.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,232 @@ +package de.intevation.flys.importer.parsers; + +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.w3c.dom.Element; + +import javax.xml.xpath.XPathConstants; + +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import org.apache.log4j.Logger; + +import de.intevation.artifacts.common.utils.XMLUtils; + +import de.intevation.flys.importer.ImportAnnotationType; +import de.intevation.flys.importer.Importer; + +public class AnnotationClassifier +{ + private static Logger log = Logger.getLogger(Importer.class); + + public static final String TYPES_XPATH = + "/annotation/types/type"; + + public static final String FILE_PATTERNS_XPATH = + "/annotation/patterns/file"; + + public static final String DESCRIPTION_PATTERNS_XPATH = + "/annotation/patterns/line"; + + + public static class Pair { + + protected Pattern pattern; + protected ImportAnnotationType annType; + + public Pair(Pattern pattern, ImportAnnotationType annType) { + this.pattern = pattern; + this.annType = annType; + } + + public ImportAnnotationType match(String s) { + Matcher m = pattern.matcher(s); + return m.matches() ? annType : null; + } + } // class Pair + + + protected Map<String, ImportAnnotationType> types; + protected List<Pair> filePatterns; + protected List<Pair> descPatterns; + + protected ImportAnnotationType defaultType; + + public AnnotationClassifier() { + } + + public AnnotationClassifier(Document rules) { + types = new HashMap<String, ImportAnnotationType>(); + filePatterns = new ArrayList<Pair>(); + descPatterns = new ArrayList<Pair>(); + + buildRules(rules); + } + + protected void buildRules(Document rules) { + buildTypes(rules); + buildFilePatterns(rules); + buildDescriptionPatterns(rules); + } + + protected void buildTypes(Document rules) { + + NodeList typeList = (NodeList)XMLUtils.xpath( + rules, + TYPES_XPATH, + XPathConstants.NODESET, + null); + + if (typeList == null) { + log.info("no rules found."); + return; + } + + for (int i = 0, N = typeList.getLength(); i < N; ++i) { + Element typeElement = (Element)typeList.item(i); + String name = typeElement.getAttribute("name"); + if (name.length() == 0) { + log.warn("ANNCLASS: rule has no name"); + continue; + } + + ImportAnnotationType aic = new ImportAnnotationType(name); + + types.put(name, aic); + + if (typeElement.getAttribute("default").equals("true")) { + defaultType = aic; + } + } + } + + protected void buildFilePatterns(Document rules) { + + NodeList patternList = (NodeList)XMLUtils.xpath( + rules, + FILE_PATTERNS_XPATH, + XPathConstants.NODESET, + null); + + if (patternList == null) { + log.info("no file patterns found."); + return; + } + + for (int i = 0, N = patternList.getLength(); i < N; ++i) { + Element element = (Element)patternList.item(i); + Pair pair = buildPair(element); + if (pair != null) { + filePatterns.add(pair); + } + } + } + + protected void buildDescriptionPatterns(Document rules) { + + NodeList patternList = (NodeList)XMLUtils.xpath( + rules, + DESCRIPTION_PATTERNS_XPATH, + XPathConstants.NODESET, + null); + + if (patternList == null) { + log.info("no line patterns found."); + return; + } + + for (int i = 0, N = patternList.getLength(); i < N; ++i) { + Element element = (Element)patternList.item(i); + Pair pair = buildPair(element); + if (pair != null) { + descPatterns.add(pair); + } + } + } + + protected Pair buildPair(Element element) { + String pattern = element.getAttribute("pattern"); + String type = element.getAttribute("type"); + + if (pattern.length() == 0) { + log.warn("ANNCLASS: pattern has no 'pattern' attribute."); + return null; + } + + if (type.length() == 0) { + log.warn("ANNCLASS: pattern has no 'type' attribute."); + return null; + } + + ImportAnnotationType annType = types.get(type); + + if (annType == null) { + log.warn("ANNCLASS: pattern has unknown type '" + type + "'"); + return null; + } + + Pattern p; + + try { + p = Pattern.compile(pattern, + Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); + } + catch (IllegalArgumentException iae) { + log.warn("ANNCLASS: pattern '" + pattern + "' is invalid.", iae); + return null; + } + + return new Pair(p, annType); + } + + public ImportAnnotationType getDefaultType() { + return defaultType; + } + + public ImportAnnotationType classifyFile(String filename) { + return classifyFile(filename, null); + } + + public ImportAnnotationType classifyFile( + String filename, + ImportAnnotationType def + ) { + if (filename.toLowerCase().endsWith(".km")) { + filename = filename.substring(0, filename.length()-3); + } + + for (Pair pair: filePatterns) { + ImportAnnotationType annType = pair.match(filename); + if (annType != null) { + return annType; + } + } + + return def; + } + + public ImportAnnotationType classifyDescription(String description) { + return classifyDescription(description, null); + } + + public ImportAnnotationType classifyDescription( + String description, + ImportAnnotationType def + ) { + for (Pair pair: descPatterns) { + ImportAnnotationType annType = pair.match(description); + if (annType != null) { + return annType; + } + } + + return def; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/AnnotationsParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,198 @@ +package de.intevation.flys.importer.parsers; + +import java.util.HashMap; +import java.util.TreeSet; +import java.util.List; +import java.util.ArrayList; + +import java.io.IOException; +import java.io.File; +import java.io.LineNumberReader; +import java.io.InputStreamReader; +import java.io.FileInputStream; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.ImportAnnotation; +import de.intevation.flys.importer.ImportRange; +import de.intevation.flys.importer.ImportEdge; +import de.intevation.flys.importer.ImportAnnotationType; +import de.intevation.flys.importer.ImportAttribute; +import de.intevation.flys.importer.ImportPosition; + +public class AnnotationsParser +{ + private static Logger log = Logger.getLogger(AnnotationsParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final String [] TO_SCAN = { + "Basisdaten", + "Streckendaten", + ".." + File.separator + + "Morphologie" + File.separator + "Streckendaten" + }; + + protected HashMap<String, ImportAttribute> attributes; + protected HashMap<String, ImportPosition> positions; + protected TreeSet<ImportAnnotation> annotations; + protected AnnotationClassifier classifier; + + public AnnotationsParser() { + this(null); + } + + public AnnotationsParser(AnnotationClassifier classifier) { + attributes = new HashMap<String, ImportAttribute>(); + positions = new HashMap<String, ImportPosition>(); + annotations = new TreeSet<ImportAnnotation>(); + this.classifier = classifier; + } + + public void parseFile(File file) throws IOException { + log.info("parsing km file: '" + file + "'"); + + ImportAnnotationType defaultIAT = null; + + if (classifier != null) { + defaultIAT = classifier.classifyFile( + file.getName(), + classifier.getDefaultType()); + } + + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = null; + while ((line = in.readLine()) != null) { + if ((line = line.trim()).length() == 0 + || line.startsWith("*")) { + continue; + } + + String [] parts = line.split("\\s*;\\s*"); + + if (parts.length < 3) { + log.warn("ANN: not enough columns in line " + + in.getLineNumber()); + continue; + } + + ImportPosition position = positions.get(parts[0]); + if (position == null) { + position = new ImportPosition(parts[0]); + positions.put(parts[0], position); + } + + ImportAttribute attribute = attributes.get(parts[1]); + if (attribute == null) { + attribute = new ImportAttribute(parts[1]); + attributes.put(parts[1], attribute); + } + + String [] r = parts[2].replace(",", ".").split("\\s*#\\s*"); + + BigDecimal from, to; + + try { + from = new BigDecimal(r[0]); + to = r.length < 2 ? null : new BigDecimal(r[1]); + if (to != null && from.compareTo(to) > 0) { + BigDecimal t = from; from = to; to = t; + } + } + catch (NumberFormatException nfe) { + log.warn("ANN: invalid number in line " + in.getLineNumber()); + continue; + } + + ImportEdge edge = null; + + if (parts.length == 4) { // Only 'Unterkante' + try { + edge = new ImportEdge( + null, + new BigDecimal(parts[3].trim().replace(',', '.'))); + } + catch (NumberFormatException nfe) { + log.warn("ANN: cannot parse 'Unterkante' in line " + + in.getLineNumber()); + } + } + else if (parts.length > 4) { // 'Unterkante' and 'Oberkante' + String bottom = parts[3].trim().replace(',', '.'); + String top = parts[4].trim().replace(',', '.'); + try { + BigDecimal b = bottom.length() == 0 + ? null + : new BigDecimal(bottom); + BigDecimal t = top.length() == 0 + ? null + : new BigDecimal(top); + edge = new ImportEdge(t, b); + } + catch (NumberFormatException nfe) { + log.warn( + "ANN: cannot parse 'Unterkante' or 'Oberkante' in line " + + in.getLineNumber()); + } + } + + ImportRange range = new ImportRange(from, to); + + ImportAnnotationType type = classifier != null + ? classifier.classifyDescription(line, defaultIAT) + : null; + + ImportAnnotation annotation = new ImportAnnotation( + attribute, position, range, edge, type); + + if (!annotations.add(annotation)) { + log.info("ANN: duplicated annotation '" + parts[0] + + "' in line " + in.getLineNumber()); + } + } + } + finally { + if (in != null) { + in.close(); + } + } + } + + public void parse(File root) throws IOException { + + for (String toScan: TO_SCAN) { + File directory = FileTools.repair(new File(root, toScan)); + if (!directory.isDirectory()) { + log.warn("ANN: '" + directory + "' is not a directory."); + continue; + } + File [] files = directory.listFiles(); + if (files == null) { + log.warn("ANN: cannot list directory '" + directory + "'"); + continue; + } + + for (File file: files) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".km")) { + parseFile(file); + } + } + } // for all directories to scan + } + + public List<ImportAnnotation> getAnnotations() { + return new ArrayList<ImportAnnotation>(annotations); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/AtFileParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,222 @@ +package de.intevation.flys.importer.parsers; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportDischargeTable; +import de.intevation.flys.importer.ImportDischargeTableValue; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.util.Date; +import java.util.Calendar; + +import de.intevation.flys.importer.ImportTimeInterval; + +/** Parse *.at (Abflusstafeln?) files. */ +public class AtFileParser { + + public static final String ENCODING = "ISO-8859-1"; + + private static Logger logger = Logger.getLogger(AtFileParser.class); + + // regular expression from hell to find out time range + public static final Pattern DATE_LINE = Pattern.compile( + "^\\*\\s*Abflu[^t]+tafel?\\s*([^\\d]+)" + + "(\\d{1,2})?\\.?(\\d{1,2})?\\.?(\\d{2,4})\\s*(?:(?:bis)|-)?\\s*" + + "(?:(\\d{1,2})?\\.?(\\d{1,2})?\\.?(\\d{2,4}))?\\s*.*$"); + + public AtFileParser() { + } + + + public ImportDischargeTable parse(File file) throws IOException { + return parse(file, "", 0); + } + + public ImportDischargeTable parse( + File file, + String prefix, + int kind + ) + throws IOException { + + logger.info("parsing AT file: " + file); + + BufferedReader br = null; + + String line = null; + + boolean beginning = true; + + ImportDischargeTable dischargeTable = + new ImportDischargeTable(kind, prefix + file.getName()); + + Date from = null; + Date to = null; + + try { + br = new BufferedReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + while ((line = br.readLine()) != null) { + + String tmp = line.trim(); + + if (tmp.length() == 0) { + continue; + } + + Matcher m = DATE_LINE.matcher(tmp); + if (m.matches()) { + from = guessDate(m.group(2), m.group(3), m.group(4)); + to = guessDate(m.group(5), m.group(6), m.group(7)); + if (from == null) { + Date t = from; from = to; to = t; + } + continue; + } + + if (tmp.startsWith("#! name=")) { + // XXX Skip the name, because we don't know where to save + // it at the moment + + //String name = tmp.substring(8); + continue; + } + + if (tmp.startsWith("#") || tmp.startsWith("*")) { + continue; + } + + String[] splits = tmp.replace(',', '.').split("\\s+"); + + if ((splits.length < 2) || (splits.length > 11)) { + logger.warn("Found an invalid row in the AT file."); + continue; + } + + String strW = splits[0].trim(); + double W = Double.parseDouble(strW); + + /* shift is used to differenciate between lines with + * exactly 10 Qs and lines with less than 10 Qs. The shift + * is only modified when it is the first line. + */ + int shift = -1; + + if (splits.length != 11 && beginning) { + shift = 10 - splits.length; + } + + + for (int i = 1; i < splits.length; i++) { + double iW = W + shift + i; + double iQ = Double.parseDouble(splits[i].trim()); + + dischargeTable.addDischargeTableValue( + new ImportDischargeTableValue( + new BigDecimal(iQ/100.0), + new BigDecimal(iW/100.0))); + } + + beginning = false; + } + } + catch (NumberFormatException pe) { + logger.warn("AT: invalid number " + pe.getMessage()); + } + finally { + if (br != null) { + br.close(); + } + } + + if (from != null) { + if (to != null && from.compareTo(to) > 0) { + Date t = from; from = to; to = t; + } + logger.info("from: " + from + " to: " + to); + ImportTimeInterval interval = new ImportTimeInterval(from, to); + dischargeTable.setTimeInterval(interval); + } + + logger.info("Finished parsing AT file: " + file); + + return dischargeTable; + } + + public static Date guessDate(String day, String month, String year) { + // TODO evaluate whether DateGuesser class can do that. + if (day == null && month == null && year == null) { + return null; + } + + logger.debug("day: " + day + " month: " + month + " year: " + year); + + int dayI = 15; + if (day != null) { + try { + dayI = Integer.parseInt(day.trim()); + } + catch (NumberFormatException nfe) { + } + } + + int monthI = 6; + if (month != null) { + try { + monthI = Integer.parseInt(month.trim()); + } + catch (NumberFormatException nfe) { + } + } + + int yearI = 1900; + if (year != null) { + try { + yearI = Integer.parseInt(year.trim()); + if (yearI < 100) { + if (yearI < 20) { + yearI += 2000; + } + else { + yearI += 1900; + } + } + } + catch (NumberFormatException nfe) { + } + } + + Calendar cal = Calendar.getInstance(); + cal.set(yearI, monthI-1, dayI, 12, 0, 0); + long ms = cal.getTimeInMillis(); + cal.setTimeInMillis(ms - ms%1000); + return cal.getTime(); + } + + + /** Parse one or more files, (useful for debugging), */ + public static void main(String [] args) { + + AtFileParser parser = new AtFileParser(); + + try { + for (String arg: args) { + parser.parse(new File(arg)); + } + } catch(Exception e) { + logger.error("Exception caught " + e); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/BedHeightEpochParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,77 @@ +package de.intevation.flys.importer.parsers; + +import java.math.BigDecimal; + +import java.text.ParseException; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportBedHeight; +import de.intevation.flys.importer.ImportBedHeightEpoch; +import de.intevation.flys.importer.ImportBedHeightEpochValue; + + +/** Parses BedHeightEpochs from csv file. */ +public class BedHeightEpochParser extends BedHeightParser { + + /** Our own logger. */ + private static final Logger log = + Logger.getLogger(BedHeightEpochParser.class); + + + @Override + protected ImportBedHeight newImportBedHeight(String description) { + return new ImportBedHeightEpoch(description); + } + + + /** + * Handle a non-comment, none-Metadata line of csv file, adding + * ImportBedHeightEpochValues to the given ImportBedHeight object. + */ + @Override + protected void handleDataLine(ImportBedHeight obj, String line) { + String[] values = line.split(SEPERATOR_CHAR); + + if (values == null || values.length == 0 || values[0].length() == 0) { + // There might be quite some ";" found. + //log.warn("Skip invalid data line: " + line); + return; + } + + BigDecimal km; + + try { + km = new BigDecimal(nf.parse(values[0]).doubleValue()); + } + catch (ParseException e) { + log.warn("Unparseable number in data row: " + line); + return; + } + + + // Handle "gap" lines like '255,0;' + if (values.length < 2) { + ImportBedHeightEpochValue value = new ImportBedHeightEpochValue( + km, + null + ); + + obj.addValue(value); + return; + } + + try { + ImportBedHeightEpochValue value = new ImportBedHeightEpochValue( + km, + new BigDecimal(nf.parse(values[1]).doubleValue()) + ); + + obj.addValue(value); + } + catch (ParseException e) { + log.warn("Unparseable number in data row: " + line); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/BedHeightParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,411 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; + +import java.math.BigDecimal; + +import java.text.NumberFormat; +import java.text.ParseException; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportBedHeight; +import de.intevation.flys.importer.ImportBedHeightType; +import de.intevation.flys.importer.ImportElevationModel; +import de.intevation.flys.importer.ImportLocationSystem; +import de.intevation.flys.importer.ImportRange; +import de.intevation.flys.importer.ImportTimeInterval; +import de.intevation.flys.importer.ImportUnit; +import de.intevation.flys.model.BedHeightType; +import de.intevation.flys.importer.ImporterSession; + +public abstract class BedHeightParser { + + private static final Logger log = + Logger.getLogger(BedHeightParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final Locale DEFAULT_LOCALE = Locale.GERMAN; + + public static final String START_META_CHAR = "#"; + public static final String SEPERATOR_CHAR = ";"; + + public static final Pattern META_YEAR = + Pattern.compile("^Jahr: [^0-9]*(\\d*).*"); + + public static final Pattern META_TIMEINTERVAL = + Pattern.compile("^Zeitraum: Epoche (\\d*)-(\\d*).*"); + + public static final Pattern META_TYPE = + Pattern.compile("^Aufnahmeart: (.*).*"); + + public static final Pattern META_LOCATION_SYSTEM = + Pattern.compile("^Lagesystem: (.*).*"); + + public static final Pattern META_CUR_ELEVATION_SYSTEM = + Pattern.compile("^H.hensystem:\\s(\\w++) (.* )??\\[(.*)\\].*"); + + public static final Pattern META_OLD_ELEVATION_SYSTEM = + Pattern.compile("^urspr.ngliches H.hensystem:\\s(\\w++) (.* )??\\[(.*)\\].*"); + + public static final Pattern META_SOUNDING_WIDTH = + Pattern.compile("^ausgewertete Peilbreite: (\\d*).*"); + + public static final Pattern META_RANGE = + Pattern.compile("^Strecke:\\D*(\\d++.?\\d*) ?- ?(\\d++.?\\d*).*"); + + public static final Pattern META_EVALUATION_BY = + Pattern.compile("^Auswerter: (.*).*"); + + public static final Pattern META_COMMENTS = + Pattern.compile("^Weitere Bemerkungen: (.*).*"); + + + protected static NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); + + + protected List<ImportBedHeight> bedHeights; + + + protected abstract ImportBedHeight newImportBedHeight(String description); + + /** Handle a line of file that contains data (in contrast to comments, meta). */ + protected abstract void handleDataLine( + ImportBedHeight importBedHeight, + String line + ); + + + + public BedHeightParser() { + this.bedHeights = new ArrayList<ImportBedHeight>(); + } + + + public List<ImportBedHeight> getBedHeights() { + return bedHeights; + } + + + public void parse(File file) throws IOException { + log.info("Parsing bed height single file '" + file + "'"); + + ImportBedHeight obj = newImportBedHeight(file.getName()); + + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = null; + while ((line = in.readLine()) != null) { + if ((line = line.trim()).length() == 0) { + continue; + } + + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(obj, line); + } + else { + handleDataLine(obj, line); + } + } + + log.info("File contained " + obj.getValueCount() + " values."); + bedHeights.add(obj); + } + finally { + if (in != null) { + in.close(); + } + } + } + + + protected static String stripMetaLine(String line) { + String tmp = line.substring(1, line.length()); + + if (tmp.startsWith(" ")) { + return tmp.substring(1, tmp.length()); + } + else { + return tmp; + } + } + + + public static Date getDateFromYear(int year) { + Calendar cal = Calendar.getInstance(); + cal.set(year, 0, 1); + + return cal.getTime(); + } + + + protected void handleMetaLine(ImportBedHeight obj, String line) { + String meta = stripMetaLine(line); + + if (handleMetaYear(obj, meta)) { + return; + } + else if (handleMetaTimeInterval(obj, meta)) { + return; + } + else if (handleMetaSoundingWidth(obj, meta)) { + return; + } + else if (handleMetaComment(obj, meta)) { + return; + } + else if (handleMetaEvaluationBy(obj, meta)) { + return; + } + else if (handleMetaRange(obj, meta)) { + return; + } + else if (handleMetaType(obj, meta)) { + return; + } + else if (handleMetaLocationSystem(obj, meta)) { + return; + } + else if (handleMetaCurElevationModel(obj, meta)) { + return; + } + else if (handleMetaOldElevationModel(obj, meta)) { + return; + } + else { + log.warn("BHP: Meta line did not match any known type: " + line); + } + } + + + protected boolean handleMetaYear(ImportBedHeight obj, String line) { + Matcher m = META_YEAR.matcher(line); + + if (m.matches()) { + String tmp = m.group(1); + if (tmp.length() > 0) { + obj.setYear(Integer.parseInt(tmp)); + } + else { + log.warn("BHP: No year given."); + } + return true; + } + + return false; + } + + + protected boolean handleMetaTimeInterval(ImportBedHeight obj, String line) { + Matcher m = META_TIMEINTERVAL.matcher(line); + + if (m.matches()) { + String lo = m.group(1); + String up = m.group(2); + + log.debug("Found time interval: " + lo + " - " + up); + + try { + int lower = Integer.valueOf(lo); + int upper = Integer.valueOf(up); + + Date fromYear = getDateFromYear(lower); + Date toYear = getDateFromYear(upper); + + obj.setTimeInterval(new ImportTimeInterval(fromYear, toYear)); + } + catch (NumberFormatException e) { + log.warn("BHP: could not parse timeinterval", e); + } + + return true; + } + + return false; + } + + + protected boolean handleMetaSoundingWidth(ImportBedHeight obj, String line) { + Matcher m = META_SOUNDING_WIDTH.matcher(line); + + if (m.matches()) { + String tmp = m.group(1); + + try { + obj.setSoundingWidth(Integer.valueOf(tmp)); + return true; + } + catch (NumberFormatException e) { + log.warn("BHP: Could not parse sounding width: " + line, e); + log.warn("-> Set default value '0'"); + } + obj.setSoundingWidth(0); + } + + return false; + } + + + protected boolean handleMetaComment(ImportBedHeight obj, String line) { + Matcher m = META_COMMENTS.matcher(line); + + if (m.matches()) { + String tmp = m.group(1); + + obj.setDescription(tmp); + + return true; + } + + return false; + } + + + protected boolean handleMetaEvaluationBy( + ImportBedHeight obj, + String line + ) { + Matcher m = META_EVALUATION_BY.matcher(line); + + if (m.matches()) { + String tmp = m.group(1); + tmp = tmp.replace(";", ""); + + obj.setEvaluationBy(tmp); + + return true; + } + + return false; + } + + + protected boolean handleMetaRange(ImportBedHeight obj, String line) { + Matcher m = META_RANGE.matcher(line); + + if (m.matches() && m.groupCount() >= 2) { + String a = m.group(1).replace(";", ""); + String b = m.group(2).replace(";", ""); + + try { + BigDecimal lower = new BigDecimal(nf.parse(a).doubleValue()); + BigDecimal upper = new BigDecimal(nf.parse(b).doubleValue()); + + obj.setRange(new ImportRange(lower, upper)); + + return true; + } + catch (ParseException e) { + log.warn("BHP: could not parse range", e); + } + } + + return false; + } + + + protected boolean handleMetaType(ImportBedHeight obj, String line) { + Matcher m = META_TYPE.matcher(line); + + if (m.matches()) { + String tmp = m.group(1).replace(";", ""); + + BedHeightType bht = BedHeightType.fetchBedHeightTypeForType( + tmp, ImporterSession.getInstance().getDatabaseSession()); + + if (bht != null) { + obj.setType(new ImportBedHeightType(bht)); + return true; + } + + log.warn("Unknown bed height type: '" + tmp + "'"); + } + + return false; + } + + + protected boolean handleMetaLocationSystem( + ImportBedHeight obj, + String line + ) { + Matcher m = META_LOCATION_SYSTEM.matcher(line); + + if (m.matches()) { + String tmp = m.group(1).replace(";", ""); + + obj.setLocationSystem(new ImportLocationSystem(tmp, tmp)); + + return true; + } + + return false; + } + + + protected boolean handleMetaCurElevationModel( + ImportBedHeight obj, + String line + ) { + Matcher m = META_CUR_ELEVATION_SYSTEM.matcher(line); + + if (m.matches()) { + String name = m.group(1); + String num = m.group(2); + String unit = m.group(3); + + obj.setCurElevationModel(new ImportElevationModel( + name + " " + num, + new ImportUnit(unit) + )); + + return true; + } + + return false; + } + + + protected boolean handleMetaOldElevationModel( + ImportBedHeight obj, + String line + ) { + Matcher m = META_OLD_ELEVATION_SYSTEM.matcher(line); + + if (m.matches()) { + String name = m.group(1); + String num = m.group(2); + String unit = m.group(3); + + obj.setOldElevationModel(new ImportElevationModel( + name + " " + num, + new ImportUnit(unit) + )); + + return true; + } + + return false; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/BedHeightSingleParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,105 @@ +package de.intevation.flys.importer.parsers; + +import java.math.BigDecimal; + +import java.text.ParseException; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportBedHeight; +import de.intevation.flys.importer.ImportBedHeightSingle; +import de.intevation.flys.importer.ImportBedHeightSingleValue; + + +public class BedHeightSingleParser extends BedHeightParser { + + private static final Logger log = + Logger.getLogger(BedHeightSingleParser.class); + + + + @Override + protected ImportBedHeight newImportBedHeight(String description) { + return new ImportBedHeightSingle(description); + } + + + + /** + * Create ImportBedHeightSingleValue from a line of csv file, add + * it to the ImportBedHeight. + */ + @Override + protected void handleDataLine(ImportBedHeight obj, String line) { + String[] values = line.split(SEPERATOR_CHAR); + + if (values == null || (values.length != 1 && values.length < 6)) { + //log.warn("BSP: Error while parsing data line: '" + line + "'"); + return; + } + + BigDecimal km; + + try { + km = new BigDecimal(nf.parse(values[0]).doubleValue()); + } + catch (ParseException e) { + // We expect a lot of ";;;;;;" lines. + //log.warn("BSP: Error while parsing km of data row.", e); + return; + } + + // Handle gaps like "10,0;;;;;". + if (values.length == 1) { + ImportBedHeightSingleValue value = new ImportBedHeightSingleValue( + (ImportBedHeightSingle) obj, + km, + null, null, null, null, null); + obj.addValue(value); + return; + } + + // Because we cannot enforce consistency of values with complete data + // via null constraints in the database (as there are "gap" values), + // do this checks manually. + if (values[3].length() == 0 || values[4].length() == 0 + || values[5].length() == 0) { + //log.warn("BSP: Error while parsing data row (manual null constraint violated)."); + return; + } + + try { + ImportBedHeightSingleValue value = new ImportBedHeightSingleValue( + (ImportBedHeightSingle) obj, + km, + new BigDecimal(nf.parse(values[1]).doubleValue()), + new BigDecimal(nf.parse(values[2]).doubleValue()), + new BigDecimal(nf.parse(values[3]).doubleValue()), + parseBigDecimal(values[4], line), + new BigDecimal(nf.parse(values[5]).doubleValue()) + ); + + obj.addValue(value); + } + catch (ParseException e) { + log.warn("BSP: unparseable value in data row.", e); + } + } + + private BigDecimal parseBigDecimal(String value, String line) { + BigDecimal result = null; + try { + Double dValue = Double.valueOf(value.replace(",", ".")); + result = new BigDecimal(dValue.doubleValue()); + } + catch (NumberFormatException nfe) { + log.warn( + "Could not parse " + + value + + " in bed heigt single row: " + + line); + } + return result; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/BundesWasserStrassenParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,76 @@ +package de.intevation.flys.importer.parsers; + +import java.util.HashMap; + +import org.apache.log4j.Logger; + +/** Parse CSV file that contains official numbers for rivers. */ +public class BundesWasserStrassenParser extends LineParser { + + /** Private logger. */ + private static final Logger logger = + Logger.getLogger(BundesWasserStrassenParser.class); + + /** Map from rivernames to Official numbers. */ + private HashMap<String,Long> numberMap; + + + public BundesWasserStrassenParser() { + numberMap = new HashMap<String,Long>(); + } + + + /** No need to reset. */ + @Override + protected void reset() { + } + + + /** No action needed on eof. */ + @Override + protected void finish() { + } + + + /** Handle a line of the bwastr-id file. */ + @Override + protected void handleLine(int lineNum, String line) { + String[] vals = line.split(","); + // Try both "," and ";" as separator. + if (vals.length != 2) { + vals = line.split(";"); + if (vals.length != 2) { + logger.warn("Invalid bwastr-id line:\n" + line); + return; + } + } + try { + String name = unwrap(vals[0].toLowerCase()); + String numberStr = unwrap(vals[1]); + Long number = Long.valueOf(numberStr); + numberMap.put(name, number); + } + catch (NumberFormatException e) { + logger.warn("Invalid number in bwastr-id line:\n" + line); + } + } + + + /** Get river -> official number mapping. */ + public HashMap<String,Long> getMap() { + return numberMap; + } + + + /** Remove leading and trailing quotes. */ + protected String unwrap(String input) { + if (input.startsWith("\"")) { + input = input.substring(1); + } + if (input.endsWith("\"")) { + input = input.substring(0, input.length() - 1); + } + return input; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/CrossSectionParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,22 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.flys.importer.XY; + +import java.io.File; +import java.util.List; +import java.util.Map; + +public interface CrossSectionParser { + + public String getDescription(); + + public Integer getYear(); + + public Map<Double,List<XY>> getData(); + + public interface Callback { + boolean accept(File file); + void parsed(CrossSectionParser parser); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/DA50Parser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,145 @@ +package de.intevation.flys.importer.parsers; + +import java.util.ArrayList; +import java.util.Map; +import java.util.List; +import java.util.TreeMap; + +import java.io.File; +import java.io.IOException; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.XY; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.utils.EpsilonComparator; + + +/** + * To create cross-sections, generate: Map<double,list<xy>> from files + * in da50 format. + */ +public class DA50Parser extends LineParser implements CrossSectionParser +{ + /** Private logger. */ + private static Logger logger = Logger.getLogger(DA50Parser.class); + + /** The current line to which add points. */ + private List<XY> currentLine; + + /** Data collected so far, last element will be currentLine. */ + protected Map<Double, List<XY>> data; + + + /** Trivial constructor. */ + public DA50Parser() { + data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); + } + + + /** Get the description of the cross section parsed. */ + @Override + public String getDescription() { + return FileTools.removeExtension(getFileName()); + } + + + /** Get the year of this cross sections measurement. */ + @Override + public Integer getYear() { + return null; + } + + + /** + * Return the data parsed. + * @return map of stations (km) to list of points. + */ + @Override + public Map<Double, List<XY>> getData() { + return data; + } + + + /** Walk a directory tree and attempt parsing all *.d50 files. */ + public void parseDA50s(File root, final Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + // TODO check presence of TIM file. + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".d50") + && (callback == null || callback.accept(file))) { + reset(); + try { + parse(file); + logger.info("parsing done"); + if (callback != null) { + callback.parsed(DA50Parser.this); + } + } + catch (IOException ioe) { + logger.error("IOException while parsing file"); + return false; + } + } + return true; + } + }); + } + + + /** Called before consuming first line of file. */ + public void reset() { + data.clear(); + currentLine = new ArrayList<XY>(); + } + + + /** + * Called for each line. Try to extract info from a da50 line. + */ + @Override + protected void handleLine(int lineNum, String line) { + String pointId = line.substring(0,2); + String streetId = line.substring(2,9); + String station = line.substring(9,18); + String free = line.substring(18,20); + String gkLRight = line.substring(20,30); + String gkLHigh = line.substring(30,40); + String gkRRight = line.substring(40,50); + String gkRHigh = line.substring(50,60); + String distance = line.substring(60,70); + + // TODO Intersect/Correlate these with e.g. TIM files. + // TODO note that as-is these points are really useless. + currentLine = new ArrayList<XY>(); + currentLine.add(new XY(0, 10,0)); + currentLine.add(new XY(Double.parseDouble(distance), 10, 1)); + } + + + /** Called when file is fully consumed. */ + @Override + protected void finish() { + logger.info("Parsed " + data.size() + " lines"); + } + + + /** Parses files given as arguments. */ + public static void main(String [] args) { + + DA50Parser parser = new DA50Parser(); + + logger.warn("Start parsing files."); + for (String arg: args) { + parser.parseDA50s(new File(arg), null); + logger.warn("Parsing a file."); + } + logger.error("Finished parsing files."); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/DA66Parser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,459 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.XY; + +import de.intevation.flys.utils.EpsilonComparator; + +import java.io.File; +import java.io.IOException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + + +/** + * To create cross-sections, generate: Map<double,list<xy>> from files + * in da66 format. + */ +public class DA66Parser extends LineParser implements CrossSectionParser +{ + /** Private logger. */ + private static Logger logger = Logger.getLogger(DA66Parser.class); + + private static String HEAD_HEAD = "00"; + private static String HEAD_GEOM = "66"; // "Values" + private static String HEAD_ENDG = "88"; // Probably never used. + + /** Regex to match lines of files in da66 format. */ + private static final Pattern LINE_PATTERN = + Pattern.compile("^([0-9 -]{2})" + // Type (00|66|88) + "([0-9 -]{5})" + // unset + "([0-9 -]{2})" + // id + "([0-9 -]{9})" + // station + "([0-9 -]{2})" + // running number + "([0-9 -]{1})?" + // point id + /* + Would be great if we could express the pattern as this: + ([0-9 -]{1})([0-9 -JKMLMNOPQR]{7})([0-9 -]{7})+ + */ + "([0-9 -JKMLMNOPQR]{7})?" + // y + "([0-9 -]{7})?" + // z + "([0-9 -]{1})?" + // point id + "([0-9 -JKMLMNOPQR]{7})?" + // y + "([0-9 -]{7})?" + // z + "([0-9 -]{1})?" + // point id + "([0-9 -JKMLMNOPQR]{7})?" + // y + "([0-9 -]{7})?" + // z + "([0-9 -]{1})?" + // point id + "([0-9 -JKMLMNOPQR]{7})?" + // y + "([0-9 -]{7})?" // z + ); + + + /** Indices to match group of main regex. */ + private static enum FIELD { + HEAD ( 1), + UNSET ( 2), + ID ( 3), + STATION ( 4), + RUNNR ( 5), + POINT_1_ID( 6), + POINT_1_Y ( 7), + POINT_1_Z ( 8), + POINT_2_ID( 9), + POINT_2_Y (10), + POINT_2_Z (11), + POINT_3_ID(12), + POINT_3_Y (13), + POINT_3_Z (14), + POINT_4_ID(15), + POINT_4_Y (16), + POINT_4_Z (17); + + private int idx; + FIELD(int idx) { + this.idx = idx; + } + int getIdx() { + return idx; + } + } + + + /** Header lines of da66 can define a type. */ + private static enum Type { + DATE ( 0), + HEKTOSTONE_LEFT ( 1), //grm. "Standlinie" + HEKTOSTONE_RIGHT ( 2), + CHANNEL_LEFT ( 3), //grm. "Fahrrinne" + CHANNEL_RIGHT ( 4), + CHANNEL_2_LEFT ( 5), + CHANNEL_2_RIGHT ( 6), + GIW_1972 ( 7), + GROIN_DIST_LEFT ( 8), //grm. "Buhnenkopfabstand links" + GROIN_HEIGHT_LEFT ( 9), + GROIN_SLOPE_LEFT (10), + GROIN_DIST_RIGHT (11), + GROIN_HEIGHT_RIGHT (12), + GROIN_SLOPE_RIGHT (13), + STRIKE_LEFT (14), //grm. "Streichlinie links" + AXIS (15), + STRIKE_RIGHT (16), + GROIN_BACK_SLOPE_LEFT (17), //grm. "Buhnenrueckenneigung" + GROIN_BACK_SLOPE_RIGHT (18), + GIW_1932 (19), + GIW_1982 (20), + STAND_ISLAND_1 (21), + STAND_ISLAND_2 (22), + STAND_ISLAND_3 (23), + STAND_ISLAND_4 (24), + UNSPECIFIED_1 (25), + UNSPECIFIED_2 (26), + HHW (27), + OLD_PROFILE_NULL (28), + AW_1978 (29), + SIGN_LEFT (30), + SIGN_RIGHT (31), + DIST_SIGNAL_CHANNEL_LEFT (32), + DIST_SIGNAL_CHANNEL_RIGHT(33), + UNSPECIFIED_3 (34), + UNSPECIFIED_4 (35), + UNSPECIFIED_5 (36), + UNSPECIFIED_6 (37), + SHORE_LEFT (38), + SHORE_RIGHT (39), + UNSPECIFIED_7 (40); + + private final int id; + Type(int id) { + this.id = id; + } + public int getId() { + return id; + } + } + + + /** Available types. */ + private static HashMap<Integer, Type> typeMap; + + + /** Types we can deal with. */ + private static List<Type> implementedTypes; + + + static { + typeMap = new HashMap<Integer, Type>(); + for (Type t: Type.values()) { + typeMap.put(new Integer(t.getId()), t); + } + // TODO populate and respect header type. + implementedTypes = new ArrayList<Type>(); + //implementedTypes.add(..); + } + + + /** The current line to which add points. */ + private List<XY> currentLine; + + + /** Data collected so far, last element will be currentLine. */ + protected Map<Double, List<XY>> data; + + + /** Trivial constructor. */ + public DA66Parser() { + data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); + } + + + /** Get the description of the cross section parsed. */ + @Override + public String getDescription() { + return FileTools.removeExtension(getFileName()); + } + + + /** Get the year of this cross sections measurement. */ + @Override + public Integer getYear() { + return null; + } + + + /** + * Return the data parsed. + * @return map of stations (km) to list of points. + */ + @Override + public Map<Double, List<XY>> getData() { + return data; + } + + + /** + * Walk a directory tree, parse its *.da66 files and store the + * data found. + */ + public void parseDA66s(File root, final Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".d66") + && (callback == null || callback.accept(file))) { + reset(); + try { + parse(file); + logger.info("parsing done"); + if (callback != null) { + callback.parsed(DA66Parser.this); + } + } + catch (IOException ioe) { + logger.error("IOException while parsing file"); + return false; + } + } + return true; + } + }); + } + + + /** + * Get the Index of the last cross-section lines point. + * @return last points index, -1 if not available. + */ + private int lastPointIdx() { + if (currentLine == null || currentLine.isEmpty()) { + return -1; + } + XY lastPoint = this.currentLine.get(currentLine.size()-1); + return lastPoint.getIndex(); + } + + + /** Returns station, deciding if it could in cm, in which case convert. */ + private double stationInKm(double station) { + if (station > 10000) { + return station/100000d; + } + else { + return station; + } + } + + + /** Apply the convention how to deal with numbers < -99.999 .*/ + private String applyLetterConvention(String orig) { + if (orig.endsWith("-")) { + return "-" + orig.replace("-",""); + } + else if (orig.endsWith("J")) { + return "-" + orig.replace("J","1"); + } + else if (orig.endsWith("K")) { + return "-" + orig.replace("K","2"); + } + else if (orig.endsWith("L")) { + return "-" + orig.replace("L","3"); + } + else if (orig.endsWith("M")) { + return "-" + orig.replace("M","4"); + } + else if (orig.endsWith("N")) { + return "-" + orig.replace("N","5"); + } + else if (orig.endsWith("O")) { + return "-" + orig.replace("O","6"); + } + else if (orig.endsWith("P")) { + return "-" + orig.replace("P","7"); + } + else if (orig.endsWith("Q")) { + return "-" + orig.replace("Q","8"); + } + else if (orig.endsWith("R")) { + return "-" + orig.replace("R","9"); + } + else { + return orig; + } + } + + /** + * Add a Point (YZ,Index) to the current cross section line. + * @param y The y coordinate of new point. + * @param z The z coordinate of new point. + * @param idx Ignored, the parameter of new point. + * @return true if point could been added, false otherwise (e.g. not + * parsable y or z values. + */ + private boolean addPoint(String y, String z, String idx) { + if (z == null || y == null || idx == null) { + logger.error("Incomplete point definition"); + return false; + } + + double iy; + double iz; + // Handle letter convention. + y = applyLetterConvention(y); + try { + iy = Double.parseDouble(y) / 1000d; + iz = Double.parseDouble(z) / 1000d; + } + catch(java.lang.NumberFormatException nfe) { + logger.error("Could not parse Number: " + nfe.getMessage()); + return false; + } + + // We ignore idx, and increment instead. + int index; + int lastPointIdx = lastPointIdx(); + if (lastPointIdx <= 0) { + index = 1; + } else { + index = lastPointIdx + 1; + } + + currentLine.add(new XY(iy, iz, index)); + return true; + } + + + /** Called before consuming first line of file. */ + public void reset() { + data.clear(); + currentLine = new ArrayList<XY>(); + } + + + /** + * Called for each line. Try to extract info from a da66 line. + */ + @Override + protected void handleLine(int lineNum, String line) { + String head = line.substring(0,2); + if (HEAD_HEAD.equals(head)) { + //logger.debug("New station"); + Matcher m = LINE_PATTERN.matcher(line); + if (m.find()) { + // Actually matches! + // TODO 'move' last line to match river axis + // TODO find river axis intersection + currentLine = new ArrayList<XY>(); + double station = stationInKm(Double.parseDouble(m.group(FIELD.STATION.getIdx()))); + data.put(station, currentLine); + } + else { + logger.error("HEAD line bad."); + } + } + else if (HEAD_GEOM.equals(head)) { + Matcher m = LINE_PATTERN.matcher(line); + if (m.find()) { + //logger.info("Station: " + m.group(FIELD.STATION.getIdx())); + // TODO if last station differs, error and abort + if (m.group(FIELD.POINT_1_ID.getIdx()) != null) { + // Point 1 + if(addPoint( + m.group(FIELD.POINT_1_Y.getIdx()), + m.group(FIELD.POINT_1_Z.getIdx()), + m.group(FIELD.POINT_1_ID.getIdx()))) { + // Point added. + } + else { + // Problematic point. + logger.error("A point could not be added"); + } + } + if (m.group(FIELD.POINT_2_ID.getIdx()) != null) { + // Point 2 + if(addPoint( + m.group(FIELD.POINT_2_Y.getIdx()), + m.group(FIELD.POINT_2_Z.getIdx()), + m.group(FIELD.POINT_2_ID.getIdx()))) { + // Point added. + } + else { + // Problematic point. + logger.error("A point could not be added"); + } + } + if (m.group(FIELD.POINT_3_ID.getIdx()) != null) { + // Point 3 + if(addPoint( + m.group(FIELD.POINT_3_Y.getIdx()), + m.group(FIELD.POINT_3_Z.getIdx()), + m.group(FIELD.POINT_3_ID.getIdx()))) { + // Point added. + } + else { + // Problematic point. + logger.error("A point could not be added"); + } + } + if (m.group(FIELD.POINT_4_ID.getIdx()) != null) { + // Point 4 + if(addPoint( + m.group(FIELD.POINT_4_Y.getIdx()), + m.group(FIELD.POINT_4_Z.getIdx()), + m.group(FIELD.POINT_4_ID.getIdx()))) { + // Point added. + } + else { + // Problematic point. + logger.error("A point could not be added"); + } + } + } + else { + logger.warn("Line could not be parsed: "); + logger.warn(line); + } + } + else if (HEAD_GEOM.equals(head)) { + logger.debug("Hit a 88"); + } + else { + logger.error("Do not know how to treat da66 line:"); + logger.error(line); + } + } + + + /** Called when file is fully consumed. */ + @Override + protected void finish() { + // TODO 'move' last line to match river axis + logger.info("Parsed " + data.size() + " lines"); + } + + + /** Parses files given as arguments. */ + public static void main(String [] args) { + + DA66Parser parser = new DA66Parser(); + + logger.warn("Start parsing files."); + for (String arg: args) { + parser.parseDA66s(new File(arg), null); + logger.warn("Parsing a file."); + } + logger.error("Finished parsing files."); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/FlowVelocityMeasurementParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,102 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.flys.importer.ImportFlowVelocityMeasurement; +import de.intevation.flys.importer.ImportFlowVelocityMeasurementValue; + +import java.math.BigDecimal; + +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +public class FlowVelocityMeasurementParser extends LineParser { + + private static final Logger log = + Logger.getLogger(FlowVelocityMeasurementParser.class); + + private static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + private static final DateFormat df = + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + + + private List<ImportFlowVelocityMeasurement> measurements; + + private ImportFlowVelocityMeasurement current; + + + public FlowVelocityMeasurementParser() { + measurements = new ArrayList<ImportFlowVelocityMeasurement>(); + } + + + public List<ImportFlowVelocityMeasurement> getMeasurements() { + return measurements; + } + + @Override + protected void reset() { + current = new ImportFlowVelocityMeasurement(); + } + + + @Override + protected void finish() { + current.setDescription(fileName); + measurements.add(current); + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + public void handleMetaLine(String line) { + } + + + public void handleDataLine(String line) { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols.length < 8) { + log.warn("skip invalid data line: '" + line + "'"); + return; + } + + try { + double km = nf.parse(cols[1]).doubleValue(); + double w = nf.parse(cols[5]).doubleValue(); + double q = nf.parse(cols[6]).doubleValue(); + double v = nf.parse(cols[7]).doubleValue(); + + String timestr = cols[3] + " " + cols[4]; + String description = cols.length > 8 ? cols[8] : null; + + current.addValue(new ImportFlowVelocityMeasurementValue( + df.parse(timestr), + new BigDecimal(km), + new BigDecimal(w), + new BigDecimal(q), + new BigDecimal(v), + description + )); + } + catch (ParseException pe) { + log.warn("Unparseable flow velocity values:", pe); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/FlowVelocityModelParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,269 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; + +import java.math.BigDecimal; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportDischargeZone; +import de.intevation.flys.importer.ImportFlowVelocityModel; +import de.intevation.flys.importer.ImportFlowVelocityModelValue; +import de.intevation.flys.utils.EpsilonComparator; + + +public class FlowVelocityModelParser extends LineParser { + + private static final Logger log = + Logger.getLogger(FlowVelocityModelParser.class); + + private static final Pattern META_REGEX = + Pattern.compile(".*Rechnung (.*) \\(Pegel (.*)\\).*"); + + private static final Pattern META_GAUGE = + Pattern.compile("(.*) Q=(\\w*)m3/s"); + + private static final Pattern META_MAINVALUE_A = + Pattern.compile("([a-zA-Z]+)+(\\d+)*"); + + private static final Pattern META_MAINVALUE_B = + Pattern.compile("(([a-zA-Z]+)+(\\d+)*)\\s*-\\s*(([a-zA-Z]+)+(\\d+)*)"); + + private static final Pattern META_MAINVALUE_C = + Pattern.compile("([0-9]++)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*)"); + + private static final Pattern META_MAINVALUE_D = + Pattern.compile("(([0-9]*)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*)) bis (([0-9]*)\\s?(\\w*)|([0-9]++,[0-9]++)\\s?(\\w*))"); + + private static final Pattern META_MAINVALUE_E = + Pattern.compile("(([a-zA-Z]+)+(\\d+)*) bis (([a-zA-Z]+)+(\\d+)*)"); + + private static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + + private List<ImportFlowVelocityModel> models; + + private ImportFlowVelocityModel current; + + protected String description; + + protected TreeSet<Double> kmExists; + + + public FlowVelocityModelParser() { + models = new ArrayList<ImportFlowVelocityModel>(); + kmExists = new TreeSet<Double>(EpsilonComparator.CMP); + } + + + public List<ImportFlowVelocityModel> getModels() { + return models; + } + + @Override + public void parse(File file) throws IOException { + description = file.getName(); + + super.parse(file); + } + + @Override + protected void reset() { + current = new ImportFlowVelocityModel(description); + kmExists.clear(); + } + + + @Override + protected void finish() { + models.add(current); + + // description = null; + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + protected void handleMetaLine(String line) { + Matcher m = META_REGEX.matcher(line); + + if (m.matches()) { + String mainValueStr = m.group(1); + String gaugeStr = m.group(2); + + Object[] valueData = handleMainValueString(mainValueStr); + Object[] gaugeData = handleGaugeString(gaugeStr); + + if (valueData == null || valueData.length < 2) { + log.warn("skip invalid MainValue part: '" + line + "'"); + return; + } + + if (gaugeData == null || gaugeData.length < 2) { + log.warn("skip invalid gauge part: '" + line + "'"); + return; + } + + if (log.isDebugEnabled()) { + log.debug("Found meta information:"); + log.debug(" Gauge: " + gaugeData[0]); + log.debug(" Value: " + gaugeData[1]); + log.debug(" Lower: " + valueData[0]); + log.debug(" upper: " + valueData[1]); + } + + current.setDischargeZone(new ImportDischargeZone( + (String) gaugeData[0], + (BigDecimal) gaugeData[1], + (String) valueData[0], + (String) valueData[1] + )); + } + } + + + protected Object[] handleMainValueString(String mainValueStr) { + Matcher mA = META_MAINVALUE_A.matcher(mainValueStr); + if (mA.matches()) { + String name = mA.group(0); + + return new Object[] { name, name }; + } + + Matcher mB = META_MAINVALUE_B.matcher(mainValueStr); + if (mB.matches()) { + String lower = mB.group(1); + String upper = mB.group(4); + + return new Object[] { lower, upper }; + } + + Matcher mC = META_MAINVALUE_C.matcher(mainValueStr); + if (mC.matches()) { + String facA = mC.group(1); + String nameA = mC.group(2); + String facB = mC.group(3); + String nameB = mC.group(4); + + String fac = facA != null ? facA : facB; + String name = nameA != null ? nameA : nameB; + + String mainValue = fac + " " + name; + + return new Object[] { mainValue, mainValue }; + } + + Matcher mD = META_MAINVALUE_D.matcher(mainValueStr); + if (mD.matches()) { + String loFacA = mD.group(2); + String loNameA = mD.group(3); + String loFacB = mD.group(4); + String loNameB = mD.group(5); + + String upFacA = mD.group(7); + String upNameA = mD.group(8); + String upFacB = mD.group(9); + String upNameB = mD.group(10); + + String loFac = loFacA != null ? loFacA : loFacB; + String loName = loNameA != null ? loNameA : loNameB; + + String upFac = upFacA != null ? upFacA : upFacB; + String upName = upNameA != null ? upNameA : upNameB; + + String loMainValue = loFac + " " + loName; + String upMainValue = upFac + " " + upName; + + return new Object[] { loMainValue, upMainValue }; + } + + Matcher mE = META_MAINVALUE_E.matcher(mainValueStr); + if (mE.matches()) { + String lower = mE.group(1); + String upper = mE.group(4); + + return new Object[] { lower, upper }; + } + + return null; + } + + + protected Object[] handleGaugeString(String gaugeStr) { + Matcher m = META_GAUGE.matcher(gaugeStr); + + if (m.matches()) { + String name = m.group(1); + String qStr = m.group(2); + + try { + return new Object[] { + name, + new BigDecimal(nf.parse(qStr).doubleValue()) }; + } + catch (ParseException pe) { + log.warn("Could not parse Q value: '" + qStr + "'"); + } + } + + return null; + } + + + protected void handleDataLine(String line) { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols.length < 5) { + log.warn("skip invalid data line: '" + line + "'"); + return; + } + + try { + double km = nf.parse(cols[0]).doubleValue(); + + Double key = Double.valueOf(km); + + if (kmExists.contains(key)) { + log.warn("duplicate stattion '" + km + "': -> ignored"); + return; + } + + double q = nf.parse(cols[1]).doubleValue(); + double total = nf.parse(cols[2]).doubleValue(); + double main = nf.parse(cols[3]).doubleValue(); + double stress = nf.parse(cols[4]).doubleValue(); + + current.addValue(new ImportFlowVelocityModelValue( + new BigDecimal(km), + new BigDecimal(q), + new BigDecimal(total), + new BigDecimal(main), + new BigDecimal(stress) + )); + + kmExists.add(key); + } + catch (ParseException pe) { + log.warn("Unparseable flow velocity values:", pe); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/HYKParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,344 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.ImportHYK; +import de.intevation.flys.importer.ImportHYKEntry; +import de.intevation.flys.importer.ImportHYKFormation; +import de.intevation.flys.importer.ImportHYKFlowZone; +import de.intevation.flys.importer.ImportHYKFlowZoneType; + +import java.io.File; +import java.io.IOException; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + +import java.util.HashMap; +import java.util.Map; +import java.util.Date; +import java.util.Calendar; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +public class HYKParser +{ + private static Logger log = Logger.getLogger(HYKParser.class); + + public interface Callback { + boolean hykAccept(File file); + void hykParsed(HYKParser parser); + } // interface Callback + + public static enum State { + LINE_1, LINE_2, LINE_3, LINE_4, LINE_5, LINE_6 + }; + + private static final String ENCODING = "ISO-8859-1"; + + protected Map<String, ImportHYKFlowZoneType> flowZoneTypes; + + protected ImportHYK hyk; + + public HYKParser() { + flowZoneTypes = new HashMap<String, ImportHYKFlowZoneType>(); + } + + public ImportHYK getHYK() { + return hyk; + } + + private static Date yearToDate(Integer year) { + if (year == null) { + return null; + } + Calendar cal = Calendar.getInstance(); + cal.set(year, 0, 1, 12, 0, 0); + long ms = cal.getTimeInMillis(); + cal.setTimeInMillis(ms - ms%1000); + return cal.getTime(); + } + + public boolean parse(File file) { + + boolean debug = log.isDebugEnabled(); + + log.info("Parsing HYK file '" + file + "'"); + + LineNumberReader in = null; + + String description = + file.getParentFile().getName() + "/" + file.getName(); + + hyk = new ImportHYK(null, description); + + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line; + + State state = State.LINE_1; + + int numFormations = 0; + + BigDecimal km = null; + BigDecimal top = null; + BigDecimal bottom = null; + BigDecimal distanceVL = null; + BigDecimal distanceHF = null; + BigDecimal distanceVR = null; + + Integer year = null; + int numZones = 0; + + ImportHYKFlowZoneType [] fzts = null; + BigDecimal [] coords = null; + int coordPos = 0; + + ImportHYKEntry entry = null; + ImportHYKFormation formation = null; + + while ((line = in.readLine()) != null) { + + if (line.startsWith("*") || line.startsWith("----")) { + continue; + } + + line = line.trim(); + + if (state != State.LINE_5 && line.length() == 0) { + continue; + } + + String [] parts = line.split("\\s+"); + + if (debug) { + log.debug("'" + line + "': " + state); + } + + switch (state) { + case LINE_1: + if (parts.length < 2) { + log.error("HYK 1: not enough elements in line " + + in.getLineNumber()); + return false; + } + + if (parts.length == 2) { + // no year given + year = null; + } + else { + try { + year = Integer.valueOf(parts[1]); + } + catch (NumberFormatException nfe) { + log.error( + "year is not an integer in line " + + in.getLineNumber()); + return false; + } + } + try { + km = new BigDecimal(parts[0]); + numFormations = Integer.parseInt( + parts[parts.length > 2 ? 2 : 1]); + } + catch (NumberFormatException nfe) { + log.error( + "parsing number of formations " + + "or km failed in line " + in.getLineNumber()); + return false; + } + entry = new ImportHYKEntry(hyk, km, yearToDate(year)); + hyk.addEntry(entry); + + state = State.LINE_2; + break; + + case LINE_2: + if (parts.length < 3) { + log.error("HYK 2: not enough elements in line " + + in.getLineNumber()); + return false; + } + try { + numZones = Integer.parseInt(parts[0]); + bottom = new BigDecimal(parts[1]); + top = new BigDecimal(parts[2]); + } + catch (NumberFormatException nfe) { + log.error( + "HYK: parsing num zones, bottom or top height " + + "failed in line " + in.getLineNumber()); + return false; + } + formation = new ImportHYKFormation(); + formation.setBottom(bottom); + formation.setTop(top); + entry.addFormation(formation); + + state = State.LINE_3; + break; + + case LINE_3: + if (parts.length != numZones) { + log.error( + "HYK: number of flow zones mismatches " + + "in line " + in.getLineNumber()); + return false; + } + + fzts = new ImportHYKFlowZoneType[parts.length]; + for (int i = 0; i < fzts.length; ++i) { + fzts[i] = getFlowZoneType(parts[i]); + } + coords = new BigDecimal[numZones]; + state = State.LINE_4; + break; + + case LINE_4: + try { + int N = Math.min(parts.length, coords.length); + for (coordPos = 0; coordPos < N; ++coordPos) { + coords[coordPos] = + new BigDecimal(parts[coordPos]); + } + } + catch (NumberFormatException nfe) { + log.error("HYK: cannot parse number in line " + + in.getLineNumber()); + return false; + } + state = State.LINE_5; + break; + + case LINE_5: + if (parts.length + coordPos < coords.length) { + log.error("HYK 5: not enough elements in line " + + in.getLineNumber()); + return false; + } + try { + for (int i = 0; + i < parts.length && coordPos < coords.length; + ++i, ++coordPos + ) { + coords[coordPos] = new BigDecimal(parts[i]); + } + } + catch (NumberFormatException nfe) { + log.error("HYK: cannot parse number in line " + + in.getLineNumber()); + return false; + } + for (int i = 0; i < coords.length; ++i) { + BigDecimal a = coords[i]; + BigDecimal b = coords[i == coords.length-1 ? i : i+1]; + if (a.compareTo(b) > 0) { + log.warn("HYK: zone coordinates swapped in line " + + in.getLineNumber()); + BigDecimal c = a; a = b; b = c; + } + ImportHYKFlowZone zone = new ImportHYKFlowZone( + formation, fzts[i], a, b); + formation.addFlowZone(zone); + } + state = State.LINE_6; + break; + + case LINE_6: + if (parts.length < 3) { + log.error("HYK 6: not enough elements in line " + + in.getLineNumber()); + return false; + } + try { + distanceVL = new BigDecimal(parts[0]); + distanceHF = new BigDecimal(parts[1]); + distanceVR = new BigDecimal(parts[2]); + } + catch (NumberFormatException nfe) { + log.error("HYK: cannot parse number in line " + + in.getLineNumber()); + return false; + } + formation.setDistanceVL(distanceVL); + formation.setDistanceHF(distanceHF); + formation.setDistanceVR(distanceVR); + + // continue with next formation. + state = --numFormations > 0 // formations left? + ? State.LINE_2 + : State.LINE_1; + break; + } + } + } + catch (IOException ioe) { + log.error("HYK: Error reading file.", ioe); + return false; + } + finally { + if (in != null) { + try { + in.close(); + } + catch (IOException ioe) { + log.error("HYK: Error closing file.", ioe); + } + } + } + return true; + } + + protected ImportHYKFlowZoneType getFlowZoneType(String name) { + name = name.toUpperCase(); + ImportHYKFlowZoneType fzt = flowZoneTypes.get(name); + if (fzt == null) { + log.info("New flow zone type: " + name); + fzt = new ImportHYKFlowZoneType(name); + flowZoneTypes.put(name, fzt); + } + return fzt; + } + + protected void reset() { + hyk = null; + } + + public void parseHYKs(File root, final Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".hyk") + && (callback == null || callback.hykAccept(file))) { + reset(); + boolean success = parse(file); + log.info("parsing " + (success ? "succeeded" : "failed")); + if (success && callback != null) { + callback.hykParsed(HYKParser.this); + } + } + return true; + } + }); + } + + public static void main(String [] args) { + + HYKParser parser = new HYKParser(); + + for (String arg: args) { + parser.parseHYKs(new File(arg), null); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/InfoGewParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,138 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; + +import java.util.List; +import java.util.ArrayList; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import org.apache.log4j.Logger; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.ImportRiver; + + +/** Processes files mentioned in an info file for a river. */ +public class InfoGewParser +{ + private static Logger log = Logger.getLogger(InfoGewParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final Pattern GEWAESSER = + Pattern.compile("^\\s*Gew\u00e4sser\\s*:\\s*(.+)"); + + public static final Pattern WST_DATEI = + Pattern.compile("^\\s*WSTDatei\\s*:\\s*(.+)"); + + public static final Pattern BB_INFO = + Pattern.compile("^\\s*B\\+B-Info\\s*:\\s*(.+)"); + + protected ArrayList<ImportRiver> rivers; + + protected AnnotationClassifier annotationClassifier; + + public InfoGewParser() { + this(null); + } + + public InfoGewParser(AnnotationClassifier annotationClassifier) { + rivers = new ArrayList<ImportRiver>(); + this.annotationClassifier = annotationClassifier; + } + + public List<ImportRiver> getRivers() { + return rivers; + } + + public static final String normalize(String f) { + return f.replace("\\", "/").replace("/", File.separator); + } + + /** Handle a gew, wst, or bb_info file. */ + public void parse(File file) throws IOException { + + LineNumberReader in = null; + + File root = file.getParentFile(); + + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = null; + + String riverName = null; + File wstFile = null; + File bbInfoFile = null; + + while ((line = in.readLine()) != null) { + if ((line = line.trim()).length() == 0) { + continue; + } + Matcher m = GEWAESSER.matcher(line); + + if (m.matches()) { + String river = m.group(1); + log.info("Found river '" + river + "'"); + if (riverName != null) { + rivers.add(new ImportRiver( + riverName, + wstFile, + bbInfoFile, + annotationClassifier)); + } + riverName = river; + wstFile = null; + bbInfoFile = null; + } + else if ((m = WST_DATEI.matcher(line)).matches()) { + String wstFilename = m.group(1); + File wst = new File(wstFilename = normalize(wstFilename)); + if (!wst.isAbsolute()) { + wst = new File(root, wstFilename); + } + wst = FileTools.repair(wst); + log.info("Found wst file '" + wst + "'"); + if (!wst.isFile() || !wst.canRead()) { + log.warn("cannot access WST file '" + wstFilename + "'"); + continue; + } + wstFile = wst; + } + else if ((m = BB_INFO.matcher(line)).matches()) { + //TODO: Make it relative to the wst file. + String bbInfo = m.group(1); + bbInfoFile = new File(normalize(bbInfo)); + } + } + if (riverName != null) { + rivers.add(new ImportRiver( + riverName, + wstFile, + bbInfoFile, + annotationClassifier)); + } + } + finally { + if (in != null) { + in.close(); + } + } + + for (ImportRiver river: rivers) { + river.parseDependencies(); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/LineParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,139 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; + +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import org.apache.log4j.Logger; + + +/** + * Base-Class for prasers for line-based file formats. + * Calls reset(), then read line by line, calling handleLine() for each, + * then calls finish(). + */ +public abstract class LineParser { + + /** Private logger. */ + private static final Logger log = Logger.getLogger(LineParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final Locale DEFAULT_LOCALE = Locale.GERMAN; + + public static final String START_META_CHAR = "#"; + public static final String SEPERATOR_CHAR = ";"; + + + protected abstract void handleLine(int lineNum, String line); + + protected abstract void reset(); + + protected abstract void finish(); + + /** Name of file parsed. */ + protected String fileName; + + protected File inputFile; + + + /** + * This method reads each line of <i>file</i>. At the beginning, + * <i>reset()</i> is called; afterwards for each line <i>handleLine()</i> is + * called; at the end <i>finish</i> is called. + * + * @param file The file which should be parsed. + */ + public void parse(File file) throws IOException { + log.info("Parsing file '" + file + "'"); + + inputFile = file; + + fileName = file.getName(); + + reset(); + + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = null; + int lineNum = 1; + while ((line = in.readLine()) != null) { + if ((line = line.trim()).length() == 0) { + lineNum++; + continue; + } + + handleLine(lineNum++, line); + } + } + finally { + if (in != null) { + in.close(); + } + } + + finish(); + } + + + /** Returns the name of the file parsed. */ + protected String getFileName() { + return fileName; + } + + /** Returns the file currently parsed. */ + protected File getInputFile() { + return inputFile; + } + + + protected static String stripMetaLine(String line) { + String tmp = line.substring(1, line.length()); + + if (tmp.startsWith(" ")) { + return tmp.substring(1, tmp.length()); + } + else { + return tmp; + } + } + + public static double getDouble(String doubleString) throws ParseException { + NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); + Number value = nf.parse(doubleString); + + return value.doubleValue(); + } + + public static Date getDate(String dateString) throws ParseException { + DateFormat df = SimpleDateFormat.getDateInstance( + SimpleDateFormat.MEDIUM, DEFAULT_LOCALE); + + return df.parse(dateString); + } + + + public static Date getDateFromYear(int year) { + Calendar cal = Calendar.getInstance(); + cal.set(year, 0, 1); + + return cal.getTime(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/MeasurementStationsParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,187 @@ +package de.intevation.flys.importer.parsers; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportMeasurementStation; +import de.intevation.flys.importer.ImportRange; +import de.intevation.flys.importer.ImportTimeInterval; + + +public class MeasurementStationsParser extends LineParser { + + public static class MeasurementStationParserException extends Exception { + + private static final long serialVersionUID = 1L; + + public MeasurementStationParserException(String msg) { + super(msg); + } + } + + public static final int MIN_COLUMNS = 10; + + private static final Logger log = Logger + .getLogger(MeasurementStationsParser.class); + + private List<ImportMeasurementStation> measurementStations; + private ImportMeasurementStation current; + + @Override + protected void reset() { + this.measurementStations = new ArrayList<ImportMeasurementStation>(); + } + + @Override + protected void finish() { + } + + @Override + protected void handleLine(int lineNum, String line) { + if (line == null || line.startsWith(START_META_CHAR)) { + log.info("skip meta information at line " + lineNum); + return; + } + + try { + current = new ImportMeasurementStation(); + handleDataLine(line); + measurementStations.add(current); + } + catch (MeasurementStationParserException e) { + log.warn("Problem in line " + lineNum + ": " + e.getMessage()); + } + } + + public List<ImportMeasurementStation> getMeasurementStations() { + return measurementStations; + } + + protected void handleDataLine(String line) + throws MeasurementStationParserException { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols == null || cols.length < MIN_COLUMNS) { + int num = cols != null ? cols.length : 0; + throw new MeasurementStationParserException("Not enough columns: " + + num); + } + + current.name = getName(cols); + current.station = getStation(cols); + current.range = getRange(cols); + current.measurementType = getMeasurementType(cols); + current.riverside = getRiverside(cols); + current.gauge = getGauge(cols); + current.observationTimerange = getObservationTimerange(cols); + current.operator = getOperator(cols); + current.description = getDescription(cols); + + log.debug("Found new measurement station '" + current.name + "' at km " + + current.station); + } + + protected String getName(String[] cols) + throws MeasurementStationParserException { + if (cols[0] == null || cols[0].length() == 0) { + throw new MeasurementStationParserException("invalid name '" + + cols[0] + "'"); + } + + return cols[0]; + } + + protected double getStation(String[] cols) + throws MeasurementStationParserException { + if (cols[1] == null || cols[1].length() == 0) { + throw new MeasurementStationParserException("invalid station '" + + cols[1] + "'"); + } + + try { + return getDouble(cols[1]); + } + catch (ParseException e) { + throw new MeasurementStationParserException( + "unable to parse station: " + e.getMessage()); + } + } + + protected ImportRange getRange(String[] cols) { + if (cols[4] == null || cols[4].length() == 0) { + log.warn("No upper value for range found in '" + cols[4] + "'"); + return null; + } + + if (cols[5] == null || cols[5].length() == 0) { + log.warn("No upper value for range found in '" + cols[5] + "'"); + return null; + } + + try { + double lower = getDouble(cols[4]); + double upper = getDouble(cols[5]); + + return new ImportRange(new BigDecimal(lower), new BigDecimal(upper)); + } + catch (ParseException e) { + log.warn("unable to parse range: " + e.getMessage()); + return null; + } + } + + protected String getMeasurementType(String[] cols) + throws MeasurementStationParserException { + if (cols[2] == null || cols[2].length() == 0) { + throw new MeasurementStationParserException( + "invalid measurement type '" + cols[2] + "'"); + } + + return cols[2]; + } + + protected String getRiverside(String[] cols) { + return cols[3]; + } + + protected String getGauge(String[] cols) { + if (cols[6] == null || cols[6].length() == 0) { + log.warn("invalid gauge found: '" + cols[6] + "'"); + } + + return cols[6]; + } + + protected ImportTimeInterval getObservationTimerange(String[] cols) { + if (cols[8] == null || cols[8].length() == 0) { + log.warn("Found invalid observation time '" + cols[8] + "'"); + } + + try { + Date date = getDate(cols[8]); + + if (date != null) { + return new ImportTimeInterval(date); + } + log.warn("Observation time date invalid: '" + cols[8] + "'"); + } + catch (ParseException pe) { + log.warn("Observation time date not parseable: '" + cols[8] + "'"); + return null; + } + return null; + } + + protected String getOperator(String[] cols) { + return cols[9]; + } + + protected String getDescription(String[] cols) { + return cols.length > 10 ? cols[10] : null; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/MorphologicalWidthParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,120 @@ +package de.intevation.flys.importer.parsers; + +import java.math.BigDecimal; + +import java.text.NumberFormat; +import java.text.ParseException; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportMorphWidth; +import de.intevation.flys.importer.ImportMorphWidthValue; +import de.intevation.flys.importer.ImportUnit; + + +public class MorphologicalWidthParser extends LineParser { + + private static final Logger log = + Logger.getLogger(MorphologicalWidthParser.class); + + public static final NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); + + public static final Pattern META_UNIT = + Pattern.compile("^Einheit: \\[(.*)\\].*"); + + protected List<ImportMorphWidth> morphWidths; + + protected ImportMorphWidth current; + + + public MorphologicalWidthParser() { + morphWidths = new ArrayList<ImportMorphWidth>(); + } + + + @Override + protected void reset() { + current = new ImportMorphWidth(); + } + + + @Override + protected void finish() { + if (current != null) { + morphWidths.add(current); + } + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + protected void handleMetaLine(String line) { + if (handleMetaUnit(line)) { + return; + } + else { + log.warn("MWP: Unknown meta line: '" + line + "'"); + } + } + + + protected boolean handleMetaUnit(String line) { + Matcher m = META_UNIT.matcher(line); + + if (m.matches()) { + String unit = m.group(1); + + current.setUnit(new ImportUnit(unit)); + + return true; + } + + return false; + } + + + protected void handleDataLine(String line) { + String[] vals = line.split(SEPERATOR_CHAR); + + if (vals == null || vals.length < 2) { + log.warn("MWP: skip invalid data line: '" + line + "'"); + return; + } + + try { + BigDecimal km = new BigDecimal(nf.parse(vals[0]).doubleValue()); + BigDecimal width = new BigDecimal(nf.parse(vals[1]).doubleValue()); + + String desc = vals.length > 2 ? vals[2] : null; + + current.addValue(new ImportMorphWidthValue( + km, + width, + desc + )); + } + catch (ParseException pe) { + log.warn("MWP: unparseable number in data row: " + line); + } + } + + + public List<ImportMorphWidth> getMorphologicalWidths() { + return morphWidths; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/PRFParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,419 @@ +package de.intevation.flys.importer.parsers; + +import java.util.Map; +import java.util.TreeMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.io.File; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.XY; + +import de.intevation.artifacts.common.utils.FileTools; + + +/** + * Parse files in .prf format and generate a mapping of double + * (km) to List of Points (XY). + */ +public class PRFParser implements CrossSectionParser +{ + private static Logger log = Logger.getLogger(PRFParser.class); + + public static final String ENCODING = + System.getProperty("flys.backend.prf.encoding", "ISO-8859-1"); + + public static final Pattern DATA_PATTERN = + Pattern.compile( + "\\((\\d+)x\\s*,\\s*(\\d+)\\(" + + "\\s*f(\\d+)\\.(\\d+)\\s*,\\s*f(\\d+)\\.(\\d+)\\s*\\)?\\)?"); + + public static final Pattern KM_PATTERN = + Pattern.compile("\\((\\d+)x\\s*,\\s*f(\\d+)\\.(\\d+)\\s*\\)?"); + + public static final Pattern YEAR_PATTERN = + Pattern.compile("(\\d{4})"); + + public static final int MIN_YEAR = 1800; + public static final int MAX_YEAR = 2100; + + public static class DataFormat { + + protected int deleteChars; + protected int maxRepetitions; + protected int firstIntegerPlaces; + protected int firstFractionPlaces; + protected int secondIntegerPlaces; + protected int secondFractionPlaces; + + protected double firstShift; + protected double secondShift; + + public DataFormat() { + } + + public DataFormat(Matcher m) { + deleteChars = Integer.parseInt(m.group(1)); + maxRepetitions = Integer.parseInt(m.group(2)); + firstIntegerPlaces = Integer.parseInt(m.group(3)); + firstFractionPlaces = Integer.parseInt(m.group(4)); + secondIntegerPlaces = Integer.parseInt(m.group(5)); + secondFractionPlaces = Integer.parseInt(m.group(6)); + + firstShift = Math.pow(10, firstFractionPlaces); + secondShift = Math.pow(10, secondFractionPlaces); + } + + public int extractData(String line, List<XY> kmData) { + int L = line.length(); + if (L <= deleteChars) { + return -1; + } + + int pos = deleteChars; + + boolean debug = log.isDebugEnabled(); + + + int rep = 0; + for (;rep < maxRepetitions; ++rep) { + if (pos >= L || pos + firstIntegerPlaces >= L) { + break; + } + String first = line.substring( + pos, pos + firstIntegerPlaces); + + String second = line.substring( + pos + firstIntegerPlaces, + Math.min(L, pos+firstIntegerPlaces+secondIntegerPlaces)); + + double x, y; + try { + x = Double.parseDouble(first); + y = Double.parseDouble(second); + } + catch (NumberFormatException nfe) { + // broken line -> substract from dataset skip + return -1; + } + + if (first.indexOf('.') < 0) { + x /= firstShift; + } + + if (firstFractionPlaces > 0) { + x = (int)(x*firstShift)/firstShift; + } + + if (second.indexOf('.') < 0) { + y /= secondShift; + } + + if (secondFractionPlaces > 0) { + y = (int)(y*secondShift)/secondShift; + } + + kmData.add(new XY(x, y, kmData.size())); + + pos += firstIntegerPlaces + secondIntegerPlaces; + } + + return rep == maxRepetitions ? 1 : 0; + } + } // class DataFormat + + public static class KMFormat { + + protected int deleteChars; + protected int integerPlaces; + protected int fractionPlaces; + + protected double shift; + + public KMFormat() { + } + + public KMFormat(Matcher m) { + deleteChars = Integer.parseInt(m.group(1)); + integerPlaces = Integer.parseInt(m.group(2)); + fractionPlaces = Integer.parseInt(m.group(3)); + + shift = Math.pow(10, fractionPlaces); + } + + public double extractKm(String line) throws NumberFormatException { + + if (line.length() <= deleteChars) { + throw new NumberFormatException("line too short"); + } + + String kmS = + line.substring(deleteChars, deleteChars+integerPlaces); + + double km = Double.parseDouble(kmS.trim()); + + if (kmS.indexOf('.') < 0) { + km /= shift; + } + + return fractionPlaces > 0 + ? ((int)(km*shift))/shift + : km; + } + } // class KMFormat + + protected Map<Double, List<XY>> data; + + protected Integer year; + + protected String description; + + + public PRFParser() { + data = new TreeMap<Double, List<XY>>(); + } + + @Override + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + @Override + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public Map<Double, List<XY>> getData() { + return data; + } + + public void setData(Map<Double, List<XY>> data) { + this.data = data; + } + + protected void sortLists() { + for (List<XY> xy: data.values()) { + Collections.sort(xy); + } + } + + public static final Integer findYear(String s) { + Matcher m = YEAR_PATTERN.matcher(s); + while (m.find()) { + int year = Integer.parseInt(m.group(1)); + if (year >= MIN_YEAR && year <= MAX_YEAR) { + return Integer.valueOf(year); + } + } + return null; + } + + public boolean parse(File file) { + + if (!(file.isFile() && file.canRead())) { + log.warn("PRF: cannot open file '" + file + "'"); + return false; + } + + log.info("parsing PRF file: '" + file + "'"); + + description = FileTools.removeExtension(file.getName()); + + year = findYear(file.getName()); + + if (year == null) { + File parent = file.getParentFile(); + if (parent != null) { + description = parent.getName() + "/" + description; + year = findYear(parent.getName()); + } + } + + if (year != null) { + log.info("year of sounding: " + year); + } + + LineNumberReader in = null; + + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = in.readLine(); + + if (line == null || (line = line.trim()).length() == 0) { + log.warn("PRF: file is empty."); + return false; + } + + Matcher m = DATA_PATTERN.matcher(line); + + if (!m.matches()) { + log.warn("PRF: First line does not look like a PRF data pattern."); + return false; + } + + DataFormat dataFormat = new DataFormat(m); + + if ((line = in.readLine()) == null + || (line = line.trim()).length() == 0) { + log.warn("PRF: premature EOF. Expected integer in line 2"); + return false; + } + + try { + if (Integer.parseInt(line) != dataFormat.maxRepetitions) { + log.warn("PRF: Expected " + + dataFormat.maxRepetitions + " in line 2"); + return false; + } + } + catch (NumberFormatException nfe) { + log.warn("PRF: invalid integer in line 2", nfe); + return false; + } + + if ((line = in.readLine()) == null) { + log.warn( + "PRF: premature EOF. Expected pattern for km extraction"); + return false; + } + + m = KM_PATTERN.matcher(line); + + if (!m.matches()) { + log.warn( + "PRF: line 4 does not look like a PRF km extraction pattern."); + return false; + } + + KMFormat kmFormat = new KMFormat(m); + + if ((line = in.readLine()) == null + || (line = line.trim()).length() == 0) { + log.warn("PRF: premature EOF. Expected skip row count."); + return false; + } + + int lineSkipCount; + try { + if ((lineSkipCount = Integer.parseInt(line)) < 0) { + throw new IllegalArgumentException(lineSkipCount + " < 0"); + } + } + catch (NumberFormatException nfe) { + log.warn( + "PRF: line 5 is not an positive integer."); + return false; + } + + int skip = lineSkipCount; + + while ((line = in.readLine()) != null) { + if (skip > 0) { + --skip; + continue; + } + double km; + try { + km = kmFormat.extractKm(line); + } + catch (NumberFormatException iae) { + log.warn("PRF: cannot extract km in line " + in.getLineNumber()); + return false; + } + + Double station = Double.valueOf(km); + + List<XY> kmData = data.get(station); + + if (kmData == null) { + //log.debug("found new km: " + station); + kmData = new ArrayList<XY>(); + data.put(station, kmData); + } + + int c = dataFormat.extractData(line, kmData); + if (c < 1) { + skip = lineSkipCount + c; + } + } + + // sort all the lists by x and index + sortLists(); + } + catch (IOException ioe) { + log.error("Error reading PRF file.", ioe); + return false; + } + finally { + if (in != null) { + try { + in.close(); + } + catch (IOException ioe) { + log.error("Error closing PRF file.", ioe); + } + } + } + + return true; + } + + public void reset() { + data.clear(); + year = null; + description = null; + } + + public void parsePRFs(File root, final CrossSectionParser.Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".prf") + && (callback == null || callback.accept(file))) { + reset(); + boolean success = parse(file); + log.info("parsing " + (success ? "succeeded" : "failed")); + if (success && callback != null) { + callback.parsed(PRFParser.this); + } + } + return true; + } + }); + } + + public static void main(String [] args) { + + PRFParser parser = new PRFParser(); + + for (String arg: args) { + parser.parsePRFs(new File(arg), null); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/PegelGltParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,102 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; + +import java.util.List; +import java.util.ArrayList; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import java.math.BigDecimal; + +import org.apache.log4j.Logger; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.ImportGauge; +import de.intevation.flys.importer.ImportRange; + +public class PegelGltParser +{ + private static Logger log = Logger.getLogger(PegelGltParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final String KM = "km:"; + + protected List<ImportGauge> gauges; + + public PegelGltParser() { + gauges = new ArrayList<ImportGauge>(); + } + + public List<ImportGauge> getGauges() { + return gauges; + } + + public void parse(File file) throws IOException { + + File parent = file.getParentFile(); + + log.info("parsing GLT file '" + file + "'"); + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = null; + while ((line = in.readLine()) != null) { + if ((line = line.trim()).length() == 0) { + continue; + } + + int kmPos = line.indexOf(KM); + if (kmPos < 0) { + log.warn("GLT: no gauge found in line " + in.getLineNumber()); + continue; + } + + String gaugeName = line.substring(0, kmPos).trim(); + log.info("Found gauge '" + gaugeName + "'"); + + line = line.substring(kmPos + KM.length()).trim(); + + String [] parts = line.split("\\s+"); + if (parts.length < 4) { + log.warn("GLT: line " + in.getLineNumber() + + " has not enough columns."); + continue; + } + + BigDecimal from = new BigDecimal(parts[0].replace(",", ".")); + BigDecimal to = new BigDecimal(parts[1].replace(",", ".")); + if (from.compareTo(from) > 0) { + BigDecimal t = from; from = to; to = t; + } + ImportRange range = new ImportRange(from, to); + File staFile = FileTools.repair(new File(parent, parts[2])); + File atFile = FileTools.repair(new File(parent, parts[3])); + + if (log.isDebugEnabled()) { + log.debug("\tfrom: " + from); + log.debug("\tto: " + to); + log.debug("\tsta: " + staFile); + log.debug("\tat: " + atFile); + } + + gauges.add(new ImportGauge(range, staFile, atFile)); + } + } + finally { + if (in != null) { + in.close(); + } + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/SQRelationParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,170 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportSQRelation; +import de.intevation.flys.importer.ImportSQRelationValue; +import de.intevation.flys.importer.ImportTimeInterval; + + +public class SQRelationParser extends LineParser { + + private static final Logger log = + Logger.getLogger(SQRelationParser.class); + + private static final Pattern TIMERANGE_REGEX = + Pattern.compile(".*Zeitraum.*\\s(\\w*)-(\\w*).*"); + + private static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + + private List<ImportSQRelation> relations; + + private ImportSQRelation current; + + private String currentDescription; + + + public SQRelationParser() { + relations = new ArrayList<ImportSQRelation>(); + } + + + public List<ImportSQRelation> getSQRelations() { + return relations; + } + + @Override + public void parse(File file) throws IOException { + this.currentDescription = file.getName(); + super.parse(file); + } + + + @Override + protected void reset() { + current = new ImportSQRelation(); + } + + + @Override + protected void finish() { + if (current != null) { + current.setDescription(currentDescription); + relations.add(current); + } + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + protected void handleMetaLine(String line) { + Matcher m = TIMERANGE_REGEX.matcher(line); + + if (m.matches()) { + String lo = m.group(1); + String hi = m.group(2); + + log.debug("Found timerange " + lo + " - " + hi); + + try { + int low = nf.parse(lo).intValue(); + int high = nf.parse(hi).intValue(); + + current.setTimeInterval(new ImportTimeInterval( + getDateFromYear(low), + getDateFromYear(high) + )); + } + catch (ParseException nfe) { + log.warn("Cannot parse time range.", nfe); + } + } + } + + + protected void handleDataLine(String line) { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols.length < 14) { + log.warn("skip invalid data line: '" + line + "'"); + return; + } + + Double km = parseDouble(cols[3], line); + Double a = parseDouble(cols[6], line); + Double b = parseDouble(cols[7], line); + Double qMax = parseDouble(cols[8], line); + Double rSq = parseDouble(cols[9], line); + Integer nTot = parseInteger(cols[10], line); + Integer nOutlier = parseInteger(cols[11], line); + Double cFer = parseDouble(cols[12], line); + Double cDuan = parseDouble(cols[13], line); + if (km == null || a == null || b == null || + qMax == null || cols[1].length() == 0) { + if (km == null) { + log.error("No km for measurement station: Can not reference measurement station: " + + line); + } + if ( a == null || b == null || + qMax == null || cols[1].length() == 0) { + log.error("Incomplete SQ-relation row (missing a, b, Qmax or parameter): " + + line); + } + return; + } + current.addValue(new ImportSQRelationValue( + cols[1], + km, + a, + b, + qMax, + rSq, + nTot, + nOutlier, + cFer, + cDuan)); + } + + private Double parseDouble(String value, String line) { + Double result = null; + try { + result = Double.valueOf(value.replace(",", ".")); + } + catch (NumberFormatException nfe) { + log.warn("Unparseable " + value + " in sq relation row: " + line); + } + return result; + } + + private Integer parseInteger(String value, String line) { + Integer result = null; + try { + result = Integer.valueOf(value); + } + catch (NumberFormatException nfe) { + log.warn("Unparseable " + value + " in sq relation row: " + line); + } + return result; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/SedimentDensityParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,162 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.flys.importer.ImportDepth; +import de.intevation.flys.importer.ImportSedimentDensity; +import de.intevation.flys.importer.ImportSedimentDensityValue; + +import java.io.File; +import java.io.IOException; + +import java.math.BigDecimal; + +import java.text.NumberFormat; +import java.text.ParseException; + +import java.util.ArrayList; +import java.util.List; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +public class SedimentDensityParser extends LineParser { + + private static final Logger log = + Logger.getLogger(SedimentDensityParser.class); + + public static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + public static final Pattern META_DEPTH = + Pattern.compile("^Tiefe: (\\w++)-(\\w++)( (\\w++))?.*"); + + protected List<ImportSedimentDensity> sedimentDensities; + + protected ImportSedimentDensity current; + + protected String currentDescription; + + + public SedimentDensityParser() { + sedimentDensities = new ArrayList<ImportSedimentDensity>(); + } + + + @Override + public void parse(File file) throws IOException { + currentDescription = file.getName(); + + super.parse(file); + } + + + @Override + protected void reset() { + current = new ImportSedimentDensity(currentDescription); + } + + + @Override + protected void finish() { + if (current != null) { + sedimentDensities.add(current); + } + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + protected void handleMetaLine(String line) { + if (handleMetaDepth(line)) { + return; + } + else { + log.warn("Unknown meta line: '" + line + "'"); + } + } + + + protected boolean handleMetaDepth(String line) { + Matcher m = META_DEPTH.matcher(line); + + if (m.matches()) { + String lo = m.group(1); + String up = m.group(2); + + log.info("Found sediment density depth: " + lo + " - " + up + " cm"); + + try { + ImportDepth depth = new ImportDepth( + new BigDecimal(nf.parse(lo).doubleValue()), + new BigDecimal(nf.parse(up).doubleValue()) + ); + + current.setDepth(depth); + + return true; + } + catch (ParseException pe) { + log.warn("Unparseable numbers in: '" + line + "'"); + } + } + else { + log.debug("Meta line doesn't contain depth information: " + line); + } + + return false; + } + + + protected void handleDataLine(String line) { + String[] vals = line.split(SEPERATOR_CHAR); + + if (vals == null || vals.length < 3) { + log.warn("skip invalid data line: '" + line + "'"); + return; + } + + BigDecimal km = null; + BigDecimal shoreOffset = null; + BigDecimal density = null; + try { + km = new BigDecimal(nf.parse(vals[0]).doubleValue()); + density = new BigDecimal(nf.parse(vals[2]).doubleValue()); + if (!vals[1].isEmpty()) { + shoreOffset = new BigDecimal(nf.parse(vals[1]).doubleValue()); + } + } + catch (ParseException pe) { + log.warn("Unparseable numbers in '" + line + "'"); + } + + if (km == null || density == null) { + log.warn("SDP: No km nor density given. Skip line"); + return; + } + + BigDecimal year = null; + + current.addValue(new ImportSedimentDensityValue( + km, + shoreOffset, + density, + year, + currentDescription)); + } + + + public List<ImportSedimentDensity> getSedimentDensities() { + return sedimentDensities; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/SedimentYieldParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,393 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; + +import java.text.NumberFormat; +import java.text.ParseException; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportGrainFraction; +import de.intevation.flys.importer.ImportSedimentYield; +import de.intevation.flys.importer.ImportSedimentYieldValue; +import de.intevation.flys.importer.ImportTimeInterval; +import de.intevation.flys.importer.ImportUnit; +import de.intevation.flys.model.GrainFraction; + + +public class SedimentYieldParser extends LineParser { + + private static final Logger log = + Logger.getLogger(SedimentYieldParser.class); + + + public static final NumberFormat nf = NumberFormat.getInstance(DEFAULT_LOCALE); + + + public static final String FRAKTION_START = "Fraktion:"; + + public static final String FRACTION_COARSE_STR = + ".*Grobkorn.*"; + + public static final String FRACTION_FINE_MIDDLE_STR = + ".*Fein-Mittel-Kies.*"; + + public static final String FRACTION_SAND = + ".*Sand.*"; + + public static final String FRACTION_SUSP_SAND = + ".*susp_Sand.*"; + + public static final String FRACTION_SUSP_SAND_BED = + ".*bettbild_Anteil_susp_Sand.*"; + + public static final String FRACTION_SUSP_SAND_BED_EPOCH = + ".*susp_Sand_bettbildAnteil.*"; + + public static final String FRACTION_SUSPENDED_SEDIMENT = + ".*Schwebstoff.*"; + + public static final String FRACTION_TOTAL = + ".*gesamt.*"; + + + public static final Pattern TIMEINTERVAL_SINGLE = + Pattern.compile("\\D*([0-9]+?)\\D*"); + + public static final Pattern TIMEINTERVAL_EPOCH = + Pattern.compile("\\D*([0-9]+?)\\s*-\\s*([0-9]+?)\\D*"); + + public static final Pattern META_FRACTION = + Pattern.compile("^Fraktion: (.*)"); + + public static final Pattern META_UNIT = + Pattern.compile("^Einheit: \\[(.*)\\].*"); + + public static final Pattern META_COLUMN_NAMES = + Pattern.compile("^Fluss-km.*"); + + public static final Pattern META_GRAIN_FRACTION_A = + Pattern.compile("\\D*(([0-9]+?,[0-9]+?)\\s*-|([0-9]++)\\s*-)(([0-9]+?,[0-9]+?)|([0-9]++))\\s*([a-zA-Z]+?)\\W*\\D*"); + + public static final Pattern META_GRAIN_FRACTION_B = + Pattern.compile("(<|>){1}\\s*(\\w++)\\s*(([0-9]+?,[0-9]+?)\\s*-|([0-9]++)\\s*-)(([0-9]+?,[0-9]+?)|([0-9]++))\\s*([a-zA-Z]+?)"); + + public static final Pattern META_GRAIN_FRACTION_C = + Pattern.compile("(<|>){1}\\s*((([0-9]+?,[0-9]+?)|([0-9]++))\\s*(\\w+))"); + + + protected List<ImportSedimentYield> sedimentYields; + + protected ImportSedimentYield[] current; + + protected ImportGrainFraction grainFraction; + + protected ImportUnit unit; + + protected String description; + + protected String[] columnNames; + + + public SedimentYieldParser() { + sedimentYields = new ArrayList<ImportSedimentYield>(); + } + + + @Override + public void parse(File file) throws IOException { + description = file.getName(); + + super.parse(file); + } + + + @Override + protected void reset() { + current = null; + grainFraction = null; + unit = null; + } + + + @Override + protected void finish() { + if (current != null) { + for (ImportSedimentYield isy: current) { + sedimentYields.add(isy); + } + } + + description = null; + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + protected void handleMetaLine(String line) { + if (handleMetaUnit(line)) { + return; + } + else if (handleMetaFraction(line)) { + return; + } + else if (handleColumnNames(line)) { + return; + } + else { + log.warn("SYP: Unknown meta line: '" + line + "'"); + } + } + + + protected boolean handleMetaUnit(String line) { + Matcher m = META_UNIT.matcher(line); + + if (m.matches()) { + unit = new ImportUnit(m.group(1)); + return true; + } + + return false; + } + + + public boolean handleMetaFraction(String line) { + Matcher m = META_FRACTION.matcher(line); + + if (m.matches()) { + String tmp = m.group(1); + + this.grainFraction = buildGrainFraction(tmp); + + return true; + } + else if (line.startsWith(FRAKTION_START)) { + String newLine = line.replace(FRAKTION_START, "").trim(); + if (newLine.length() == 0) { + log.debug("Found total grain fraction."); + this.grainFraction = new ImportGrainFraction(GrainFraction.TOTAL); + + return true; + } + } + + return false; + } + + + public boolean handleColumnNames(String line) { + Matcher m = META_COLUMN_NAMES.matcher(line); + + if (m.matches()) { + columnNames = line.split(SEPERATOR_CHAR); + + initializeSedimentYields(); + + return true; + } + + return false; + } + + + protected void handleDataLine(String line) { + String[] vals = line.split(SEPERATOR_CHAR); + + if (vals == null || vals.length < columnNames.length-1) { + log.warn("SYP: skip invalid data line: '" + line + "'"); + return; + } + + try { + Double km = nf.parse(vals[0]).doubleValue(); + + for (int i = 1, n = columnNames.length-1; i < n; i++) { + String curVal = vals[i]; + + if (curVal != null && curVal.length() > 0) { + current[i-1].addValue(new ImportSedimentYieldValue( + km, nf.parse(vals[i]).doubleValue() + )); + } + } + } + catch (ParseException pe) { + log.warn("SYP: unparseable number in data row '" + line + "':", pe); + } + } + + + private void initializeSedimentYields() { + // skip first column (Fluss-km) and last column (Hinweise) + current = new ImportSedimentYield[columnNames.length-2]; + + for (int i = 0, n = columnNames.length; i < n-2; i++) { + current[i] = new ImportSedimentYield(this.description); + current[i].setTimeInterval(getTimeInterval(columnNames[i+1])); + current[i].setUnit(unit); + current[i].setGrainFraction(grainFraction); + } + } + + + private ImportTimeInterval getTimeInterval(String column) { + try { + Matcher a = TIMEINTERVAL_EPOCH.matcher(column); + if (a.matches()) { + int yearA = nf.parse(a.group(1)).intValue(); + int yearB = nf.parse(a.group(2)).intValue(); + + return new ImportTimeInterval( + getDateFromYear(yearA), + getDateFromYear(yearB) + ); + } + + Matcher b = TIMEINTERVAL_SINGLE.matcher(column); + if (b.matches()) { + int year = nf.parse(b.group(1)).intValue(); + + return new ImportTimeInterval(getDateFromYear(year)); + } + + log.warn("SYP: Unknown time interval string: '" + column + "'"); + } + catch (ParseException pe) { + log.warn("SYP: Could not parse years: " + column, pe); + } + + return null; + } + + + private ImportGrainFraction buildGrainFraction(String gfStr) { + Matcher a = META_GRAIN_FRACTION_A.matcher(gfStr); + if (a.matches()) { + String lowerA = a.group(2); + String lowerB = a.group(3); + + String upperA = a.group(4); + String upperB = a.group(5); + + String lower = lowerA != null ? lowerA : lowerB; + String upper = upperA != null ? upperA : upperB; + + try { + return new ImportGrainFraction( + getGrainFractionTypeName(this.description), + nf.parse(lower).doubleValue(), + nf.parse(upper).doubleValue() + ); + } + catch (ParseException pe) { + log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); + } + } + + Matcher b = META_GRAIN_FRACTION_B.matcher(gfStr); + if (b.matches()) { + String lowerA = b.group(4); + String lowerB = b.group(5); + String upperA = b.group(6); + String upperB = b.group(7); + + String lower = lowerA != null ? lowerA : lowerB; + String upper = upperA != null ? upperA : upperB; + + try { + return new ImportGrainFraction( + getGrainFractionTypeName(this.description), + nf.parse(lower).doubleValue(), + nf.parse(upper).doubleValue() + ); + } + catch (ParseException pe) { + log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); + } + } + + Matcher c = META_GRAIN_FRACTION_C.matcher(gfStr); + if (c.matches()) { + String oper = c.group(1); + String valueStr = c.group(3); + + try { + Double value = nf.parse(valueStr).doubleValue(); + + if (oper.equals(">")) { + return new ImportGrainFraction( + getGrainFractionTypeName(this.description), + value, + null + ); + } + else { + return new ImportGrainFraction( + getGrainFractionTypeName(this.description), + null, + value + ); + } + } + catch (ParseException pe) { + log.warn("SYP: Could not parse ranges of: '" + gfStr + "'"); + } + } + + log.warn("SYP: Unknown grain fraction: '" + gfStr + "'"); + + return null; + } + + + public static String getGrainFractionTypeName(String filename) { + if (Pattern.matches(FRACTION_COARSE_STR, filename)) { + return GrainFraction.COARSE; + } + else if (Pattern.matches(FRACTION_FINE_MIDDLE_STR, filename)) { + return GrainFraction.FINE_MIDDLE; + } + else if (Pattern.matches(FRACTION_SUSP_SAND_BED, filename) || + Pattern.matches(FRACTION_SUSP_SAND_BED_EPOCH, filename)) { + return GrainFraction.SUSP_SAND_BED; + } + else if (Pattern.matches(FRACTION_SUSP_SAND, filename)) { + return GrainFraction.SUSP_SAND; + } + else if (Pattern.matches(FRACTION_SAND, filename)) { + return GrainFraction.SAND; + } + else if (Pattern.matches(FRACTION_SUSPENDED_SEDIMENT, filename)) { + return GrainFraction.SUSPENDED_SEDIMENT; + } + else if (Pattern.matches(FRACTION_TOTAL, filename)) { + return GrainFraction.TOTAL; + } + else { + log.warn("SYP: Unknown grain fraction '" + filename + "'"); + return "unknown"; + } + } + + + public List<ImportSedimentYield> getSedimentYields() { + return sedimentYields; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/StaFileParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,338 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import java.math.BigDecimal; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.util.Date; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportMainValueType; +import de.intevation.flys.importer.ImportMainValue; +import de.intevation.flys.importer.ImportNamedMainValue; +import de.intevation.flys.importer.ImportGauge; +import de.intevation.flys.importer.ImportTimeInterval; +import de.intevation.flys.utils.DateGuesser; + +public class StaFileParser +{ + private static Logger log = Logger.getLogger(StaFileParser.class); + + public static final String ENCODING = "ISO-8859-1"; + + public static final String TYPES = + System.getProperty("flys.backend.main.value.types", "QWTD"); + + public static final boolean NOT_PARSE_GAUGE_NUMBERS = + Boolean.getBoolean("flys.backend.sta.not.parse.gauge.numbers"); + + public static final Pattern QWTD_ = + Pattern.compile("\\s*([^\\s]+)\\s+([^\\s]+)\\s+([" + + Pattern.quote(TYPES) + "]).*"); + + public static final class NameAndTimeInterval { + private String name; + private ImportTimeInterval timeInterval; + + public NameAndTimeInterval(String name) { + this(name, null); + } + + public NameAndTimeInterval(String name, ImportTimeInterval timeInterval) { + this.name = name; + this.timeInterval = timeInterval; + } + + public String getName() { + return name; + } + + public ImportTimeInterval getTimeInterval() { + return timeInterval; + } + } // class NameAndTimeInterval + + public StaFileParser() { + } + + public boolean parse(ImportGauge gauge) throws IOException { + + File file = gauge.getStaFile(); + + log.info("parsing STA file: " + file); + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String line = in.readLine(); + + if (line == null) { + log.warn("STA file is empty."); + return false; + } + + if (line.length() < 37) { + log.warn("First line in STA file is too short."); + return false; + } + + String gaugeName = line.substring(16, 28).trim(); + + Long gaugeNumber = null; + + if (!NOT_PARSE_GAUGE_NUMBERS) { + String gaugeNumberString = line.substring(8, 16).trim(); + + try { + gaugeNumber = Long.parseLong(gaugeNumberString); + } + catch (NumberFormatException nfe) { + log.warn("STA: '" + gaugeNumberString + + "' is not a valid long number."); + } + } + + gauge.setName(gaugeName); + gauge.setOfficialNumber(gaugeNumber); + + if (log.isDebugEnabled()) { + log.debug( + "name/number: '" + gaugeName + "' '" + gaugeNumber + "'"); + } + + String [] values = line.substring(38).trim().split("\\s+", 2); + + if (values.length < 2) { + log.warn("STA: Not enough columns for aeo and datum."); + } + try { + gauge.setAeo(new BigDecimal(values[0].replace(",", "."))); + gauge.setDatum(new BigDecimal(values[1].replace(",", "."))); + } + catch (NumberFormatException nfe) { + log.warn("STA: cannot parse aeo or datum."); + return false; + } + + line = in.readLine(); + + if (line == null) { + log.warn("STA file has not enough lines"); + return false; + } + + if (line.length() < 36) { + log.warn("STA: second line is too short"); + return false; + } + + try { + gauge.setStation( + new BigDecimal(line.substring(29, 36).trim())); + } + catch (NumberFormatException nfe) { + log.warn("STA: parsing of the datum of the gauge failed"); + return false; + } + + // overread the next six lines + for (int i = 0; i < 6; ++i) { + if ((line = in.readLine()) == null) { + log.warn("STA file is too short"); + return false; + } + } + + HashMap<String, ImportMainValueType> types = + new HashMap<String, ImportMainValueType>(); + + ArrayList<ImportNamedMainValue> namedMainValues = + new ArrayList<ImportNamedMainValue>(); + + ArrayList<ImportMainValue> mainValues = + new ArrayList<ImportMainValue>(); + + while ((line = in.readLine()) != null) { + Matcher m = QWTD_.matcher(line); + if (m.matches()) { + BigDecimal value; + try { + value = new BigDecimal(m.group(2).replace(",", ".")); + } + catch (NumberFormatException nfe) { + log.warn("STA: value not parseable in line " + + in.getLineNumber()); + continue; + } + String typeString = m.group(3); + log.debug("\t type: " + typeString); + ImportMainValueType type = types.get(typeString); + if (type == null) { + type = new ImportMainValueType(typeString); + types.put(typeString, type); + } + String name = m.group(1); + NameAndTimeInterval nat = parseName(name); + ImportNamedMainValue namedMainValue = + new ImportNamedMainValue(type, nat.getName()); + namedMainValues.add(namedMainValue); + + ImportMainValue mainValue = new ImportMainValue( + gauge, + namedMainValue, + value, + nat.getTimeInterval()); + + mainValues.add(mainValue); + } + else { + // TODO: treat as a comment + } + } + gauge.setMainValueTypes( + new ArrayList<ImportMainValueType>(types.values())); + gauge.setNamedMainValues(namedMainValues); + gauge.setMainValues(mainValues); + } + finally { + if (in != null) { + in.close(); + } + } + log.info("finished parsing STA file: " + file); + return true; + } + + protected NameAndTimeInterval parseName(String name) { + List<String> result = new ArrayList<String>(); + + unbracket(name, 0, result); + + int length = result.size(); + + if (length < 1) { // Should not happen. + return new NameAndTimeInterval(name); + } + + if (length == 1) { // No date at all -> use first part. + return new NameAndTimeInterval(result.get(0).trim()); + } + + if (length == 2) { // e.g. W(1994) or W(1994 - 1999) + String type = result.get(0).trim(); + + ImportTimeInterval timeInterval = getTimeInterval( + result.get(1).trim()); + + if (timeInterval == null) { // No date at all. + type = name; + } + + return new NameAndTimeInterval(type, timeInterval); + } + + if (length == 3) { // e.g W(Q(1994)) or W(Q(1994 - 1999)) + + String type = + result.get(0).trim() + "(" + + result.get(1).trim() + ")"; + + ImportTimeInterval timeInterval = getTimeInterval( + result.get(2).trim()); + + if (timeInterval == null) { // No date at all. + type = name; + } + + return new NameAndTimeInterval(type, timeInterval); + } + + // more than 3 elements return unmodified. + + return new NameAndTimeInterval(name); + } + + private static ImportTimeInterval getTimeInterval(String datePart) { + + int minus = datePart.indexOf('-'); + + if (minus < 0) { // '-' not found + + Date date = null; + try { + date = DateGuesser.guessDate(datePart); + } + catch (IllegalArgumentException iae) { + log.warn("STA: Invalid date '" + datePart + "'"); + return null; + } + + return new ImportTimeInterval(date); + } + + // Found '-' so we have <from> - <to> + String startPart = datePart.substring(0, minus).trim(); + String endPart = datePart.substring(minus).trim(); + + Date startDate = null; + Date endDate = null; + + try { + startDate = DateGuesser.guessDate(startPart); + } + catch (IllegalArgumentException iae) { + log.warn("STA: Invalid start date '" + startPart + "'"); + } + + try { + endDate = DateGuesser.guessDate(endPart); + } + catch (IllegalArgumentException iae) { + log.warn("STA: Invalid end date '" + endPart + "'"); + } + + if (startDate == null) { + log.warn("STA: Need start date."); + return null; + } + + return new ImportTimeInterval(startDate, endDate); + } + + private static int unbracket(String s, int index, List<String> result) { + StringBuilder sb = new StringBuilder(); + int length = s.length(); + while (index < length) { + char c = s.charAt(index); + switch (c) { + case '(': + index = unbracket(s, index+1, result); + break; + case ')': + result.add(0, sb.toString()); + return index+1; + default: + sb.append(c); + ++index; + } + } + result.add(0, sb.toString()); + + return index; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/W80CSVParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,291 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.XY; + +import de.intevation.flys.importer.parsers.tim.Coordinate; + +import de.intevation.flys.utils.DateGuesser; +import de.intevation.flys.utils.EpsilonComparator; + +import java.io.File; +import java.io.IOException; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.log4j.Logger; + + +/** + * To create cross-sections, generate: Map<double,list<xy>> from files + * in w80/csv format. + */ +public class W80CSVParser extends LineParser implements CrossSectionParser +{ + /** Private logger. */ + private static Logger logger = Logger.getLogger(W80CSVParser.class); + + + /** The current line to which add points. */ + private List<XY> currentLine; + + + /** Data collected so far, last element will be currentLine. */ + protected Map<Double, List<XY>> data; + + + /** Anchor to project to. */ + private static class Anchor extends Coordinate { + + private static final double EPSILON = 1e-5; + + private double station; + + public Anchor(double x, double y, double z, double station) { + super(x, y, z); + this.station = station; + } + + public boolean sameStation(double station) { + return Math.abs(this.station - station) < EPSILON; + } + } + + + /** Reference point for simple projection. */ + private Anchor anchor; + + + /** + * Reference point for distance calculations, introduced to + * deal with bends in the lines. + * Array has two entrys: first is GK-Right, second GK-High. + */ + private double[] lastPointGK; + + + /** Measurement date of anchor as listed in w80 file. */ + private Date anchorDate; + + + private double distanceToLastPoint(double gkr, double gkh) { + double dx = gkr - lastPointGK[0]; + double dy = gkh - lastPointGK[1]; + double d = dx*dx + dy*dy; + + return Math.sqrt(d); + } + + + /** Trivial constructor. */ + public W80CSVParser() { + data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); + } + + + /** + * Get the description of the cross section parsed - + * directory name of current file. + */ + @Override + public String getDescription() { + return getInputFile().getParentFile().getName(); + } + + + /** Get the year of this cross sections measurement. */ + @Override + public Integer getYear() { + if (anchorDate == null) { + return null; + } + Calendar dateCalendar = Calendar.getInstance(); + dateCalendar.setTime(anchorDate); + return dateCalendar.get(Calendar.YEAR); + } + + + /** + * Return the data parsed. + * @return map of stations (km) to list of points. + */ + @Override + public Map<Double, List<XY>> getData() { + return data; + } + + + /** Recursively descend root, ask the callback for every file + * found and parse it if callback acks. When done, notify callback. */ + public void parseW80CSVs(File root, final Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".csv") + && (callback == null || callback.accept(file))) { + reset(); + try { + parse(file); + logger.info("parsing done"); + if (callback != null) { + callback.parsed(W80CSVParser.this); + } + } + catch (IOException ioe) { + logger.error("IOException while parsing file"); + return false; + } + } + return true; + } + }); + } + + + /** Called before consuming first line of file. */ + public void reset() { + data.clear(); + currentLine = new ArrayList<XY>(); + anchor = null; + anchorDate = null; + lastPointGK = new double[] {0d,0d}; + } + + + /** + * Get the Index of the last cross-section lines point. + * @return last points index, -1 if not available. + */ + private int getLastPointIdx() { + if (currentLine == null || currentLine.isEmpty()) { + return -1; + } + XY lastPoint = this.currentLine.get(currentLine.size()-1); + return lastPoint.getIndex(); + } + + + private double getLastPointX() { + if (currentLine == null || currentLine.isEmpty()) { + return 0d; + } + XY lastPoint = this.currentLine.get(currentLine.size()-1); + return lastPoint.getX(); + } + + + /** + * Add a Point (YZ,Index) to the current cross section line. + * @param y The y coordinate of new point. + * @param z The z coordinate of new point. + * @param idx Ignored, the parameter of new point. + * @return true if point could been added, false otherwise (e.g. not + * parsable y or z values. + */ + private boolean addPoint(double gkr, double gkh, double height, String idx) { + // Calculate distance between this and lst point (add distances). + double d = distanceToLastPoint(gkr, gkh); + double totalX = getLastPointX() + d; + + // We ignore idx, and increment instead. + int index; + int lastPointIdx = getLastPointIdx(); + if (lastPointIdx <= 0) { + index = 1; + } else { + index = lastPointIdx + 1; + } + + this.lastPointGK[0] = gkr; + this.lastPointGK[1] = gkh; + currentLine.add(new XY(totalX, height/1000d, index)); + return true; + } + + // As per documentation: + // BW;WPA;ST;UF;PN;LS;BL-LS;Y;X;Z;DL;LZK;SY;SX;SZ;BML;HS;BL-HS;H;DH;HZK;SH;WVA;BMH;BMP;DST;DB;LDS;LKZ; + + + /** + * Called for each line. Try to extract info from a w80 line. + * @param lineNum Number of line (starting with 1). + */ + @Override + protected void handleLine(int lineNum, String line) { + // First two lines are 'comment'-like. + if (lineNum == 1 || lineNum == 2) { + return; + } + // The 'shore' field shows which side of the river the shore is measured. + // Therefore, the points have to be added in the correct order (also + // because later distances are calculated which cannot be + // negative. + String[] fields = line.split(";"); + String station = fields[2]; + String shore = fields[3]; + // TODO: There is 'station' and a 'shore'-code behind. + // 1 = left, 2 = right. none = middle + String pointIndex = line.substring(16,21); + // For GK, first seven digits are of interest. + String gkRight = fields[7]; + String gkHigh = fields[8]; + String date = fields[10]; + String height = fields[18]; + String dateH = line.substring(54,60); + String dateDec = line.substring(64,70); + + double stationKm = Double.parseDouble(station) / 1000d; + double gkRightKm = Double.parseDouble(gkRight.replace(",","."));//.substring(0,7)); + double gkHighKm = Double.parseDouble(gkHigh.replace(",","."));//.substring(0,7)); + double heightM = Double.parseDouble(height.replace(",",".")); + + // New (or first) line. + if (anchor == null || !anchor.sameStation(stationKm)) { + anchor = new Anchor(gkRightKm, gkHighKm, heightM, stationKm); + lastPointGK[0] = gkRightKm; + lastPointGK[1] = gkHighKm; + currentLine = new ArrayList<XY>(); + data.put(stationKm, currentLine); + currentLine.add(new XY(0d, heightM, 0)); + try { + anchorDate = DateGuesser.guessDate(date); + } + catch (IllegalArgumentException iae) { + logger.warn("W80CSV: Invalid date '" + date + "'."); + } + } + else { + addPoint(gkRightKm, gkHighKm, heightM, pointIndex); + } + } + + + /** Called when file is fully consumed. */ + @Override + protected void finish() { + logger.info("Parsed " + data.size() + " lines"); + } + + + /** Parses files given as arguments. */ + public static void main(String [] args) { + + W80CSVParser parser = new W80CSVParser(); + + logger.warn("Start parsing files."); + for (String arg: args) { + logger.warn("Parsing a file."); + parser.parseW80CSVs(new File(arg), null); + } + logger.error("Finished parsing files."); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/W80Parser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,289 @@ +package de.intevation.flys.importer.parsers; + +import de.intevation.artifacts.common.utils.FileTools; + +import de.intevation.flys.importer.XY; + +import de.intevation.flys.importer.parsers.tim.Coordinate; + +import de.intevation.flys.utils.DateGuesser; +import de.intevation.flys.utils.EpsilonComparator; + +import java.io.File; +import java.io.IOException; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.log4j.Logger; + + +/** + * To create cross-sections, generate: Map<double,list<xy>> from files + * in w80 format. + */ +public class W80Parser extends LineParser implements CrossSectionParser +{ + /** Private logger. */ + private static Logger logger = Logger.getLogger(W80Parser.class); + + + /** The current line to which add points. */ + private List<XY> currentLine; + + + /** Data collected so far, last element will be currentLine. */ + protected Map<Double, List<XY>> data; + + + /** Anchor to project to. */ + private static class Anchor extends Coordinate { + + private static final double EPSILON = 1e-5; + + private double station; + + public Anchor(double x, double y, double z, double station) { + super(x, y, z); + this.station = station; + } + + public boolean sameStation(double station) { + return Math.abs(this.station - station) < EPSILON; + } + } + + + /** Reference point for simple projection. */ + private Anchor anchor; + + + /** + * Reference point for distance calculations, introduced to + * deal with bends in the lines. + * Array has two entrys: first is GK-Right, second GK-High. + */ + private double[] lastPointGK; + + + /** Measurement date of anchor as listed in w80 file. */ + private Date anchorDate; + + + private double distanceToLastPoint(double gkr, double gkh) { + double dx = gkr - lastPointGK[0]; + double dy = gkh - lastPointGK[1]; + double d = dx*dx + dy*dy; + + return Math.sqrt(d); + } + + + /** Trivial constructor. */ + public W80Parser() { + data = new TreeMap<Double, List<XY>>(EpsilonComparator.CMP); + } + + + /** Get the description of the cross section parsed. */ + @Override + public String getDescription() { + return FileTools.removeExtension(getFileName()); + } + + + /** Get the year of this cross sections measurement. */ + @Override + public Integer getYear() { + if (anchorDate == null) { + return null; + } + Calendar dateCalendar = Calendar.getInstance(); + dateCalendar.setTime(anchorDate); + return dateCalendar.get(Calendar.YEAR); + } + + + /** + * Return the data parsed. + * @return map of stations (km) to list of points. + */ + @Override + public Map<Double, List<XY>> getData() { + return data; + } + + + public void parseW80s(File root, final Callback callback) { + + FileTools.walkTree(root, new FileTools.FileVisitor() { + @Override + public boolean visit(File file) { + if (file.isFile() && file.canRead() + && file.getName().toLowerCase().endsWith(".w80") + && (callback == null || callback.accept(file))) { + reset(); + try { + parse(file); + logger.info("parsing done"); + if (callback != null) { + callback.parsed(W80Parser.this); + } + } + catch (IOException ioe) { + logger.error("IOException while parsing file"); + return false; + } + } + return true; + } + }); + } + + + /** Called before consuming first line of file. */ + public void reset() { + data.clear(); + currentLine = new ArrayList<XY>(); + anchor = null; + anchorDate = null; + lastPointGK = new double[] {0d,0d}; + } + + + /** + * Get the Index of the last cross-section lines point. + * @return last points index, -1 if not available. + */ + private int getLastPointIdx() { + if (currentLine == null || currentLine.isEmpty()) { + return -1; + } + XY lastPoint = this.currentLine.get(currentLine.size()-1); + return lastPoint.getIndex(); + } + + + private double getLastPointX() { + if (currentLine == null || currentLine.isEmpty()) { + return 0d; + } + XY lastPoint = this.currentLine.get(currentLine.size()-1); + return lastPoint.getX(); + } + + + /** + * Add a Point (YZ,Index) to the current cross section line. + * @param y The y coordinate of new point. + * @param z The z coordinate of new point. + * @param idx Ignored, the parameter of new point. + * @return true if point could been added, false otherwise (e.g. not + * parsable y or z values. + */ + private boolean addPoint(double gkr, double gkh, double height, String idx) { + // Calculate distance between this and lst point (add distances). + double d = distanceToLastPoint(gkr, gkh); + double totalX = getLastPointX() + d; + + // We ignore idx, and increment instead. + int index; + int lastPointIdx = getLastPointIdx(); + if (lastPointIdx <= 0) { + index = 1; + } else { + index = lastPointIdx + 1; + } + + this.lastPointGK[0] = gkr; + this.lastPointGK[1] = gkh; + currentLine.add(new XY(totalX, height/1000d, index)); + return true; + } + + + /** + * Called for each line. Try to extract info from a w80 line. + */ + @Override + protected void handleLine(int lineNum, String line) { + // The 'shore' field shows which side of the river the shore is measured. + // Therefore, the points have to be added in the correct order (also + // because later distances are calculated which cannot be + // negative. + String pointId = line.substring(0,20); + String station = line.substring(9,15); + String shore = line.substring(15,16); + // TODO: There is 'station' and a 'shore'-code behind. + // 1 = left, 2 = right. none = middle + String pointIndex = line.substring(16,21); + // For GK, first seven digits are of interest. + String gkRight = line.substring(20,30); + String gkHigh = line.substring(30,40); + String date = line.substring(40,46); + /* Fields not (yet?) of interest for FLYS + String locType = line.substring(46,47); + */ + String height = line.substring(47,54); + String dateH = line.substring(54,60); + /* Fields not (yet?) of interest for FLYS + String typeH = line.substring(60,61); + String kindH = line.substring(61,64); + */ + String dateDec = line.substring(64,70); + /* Fields not (yet?) of interest for FLYS + String note = line.substring(70,78); + String actual = line.substring(78); + */ + + double stationKm = Double.parseDouble(station) / 1000d; + double gkRightKm = Double.parseDouble(gkRight.substring(0,7)); + double gkHighKm = Double.parseDouble(gkHigh.substring(0,7)); + double heightM = Double.parseDouble(height); + + // New (or first) line. + if (anchor == null || !anchor.sameStation(stationKm)) { + anchor = new Anchor(gkRightKm, gkHighKm, heightM, stationKm); + lastPointGK[0] = gkRightKm; + lastPointGK[1] = gkHighKm; + currentLine = new ArrayList<XY>(); + data.put(stationKm, currentLine); + currentLine.add(new XY(0d, heightM, 0)); + try { + anchorDate = DateGuesser.guessDate(date); + } + catch (IllegalArgumentException iae) { + logger.warn("W80: Invalid date '" + date + "'."); + } + } + else { + addPoint(gkRightKm, gkHighKm, heightM, pointIndex); + } + } + + + /** Called when file is fully consumed. */ + @Override + protected void finish() { + logger.info("Parsed " + data.size() + " lines"); + } + + + /** Parses files given as arguments. */ + public static void main(String [] args) { + + W80Parser parser = new W80Parser(); + + logger.warn("Start parsing files."); + for (String arg: args) { + logger.warn("Parsing a file."); + parser.parseW80s(new File(arg), null); + } + logger.error("Finished parsing files."); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/WaterlevelDifferencesParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,197 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportUnit; + +import de.intevation.flys.importer.ImportWst; +import de.intevation.flys.importer.ImportWstColumn; + + +/** + * Parse WaterlevelDifferences CSV file. + */ +public class WaterlevelDifferencesParser extends LineParser { + + private static final Logger log = + Logger.getLogger(WaterlevelDifferencesParser.class); + + private static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + public static final Pattern META_UNIT = + Pattern.compile("^Einheit: \\[(.*)\\].*"); + + /** List of parsed differences as ImportWst s. */ + private List<ImportWst> differences; + + private ImportWstColumn[] columns; + + /** The currently processed dataset. */ + private ImportWst current; + + + public WaterlevelDifferencesParser() { + differences = new ArrayList<ImportWst>(); + } + + + /** Get the differences as wst parsed so far. */ + public List<ImportWst> getDifferences() { + return differences; + } + + + /** + * Parse a csv waterleveldifferenceparser and create a ImportWst object + * from it. + */ + @Override + public void parse(File file) throws IOException { + current = new ImportWst(file.getName()); + current.setKind(7); + + super.parse(file); + } + + + /** No rewind implemented. */ + @Override + protected void reset() { + } + + + @Override + protected void finish() { + if (columns != null && current != null) { + // TODO figure out if its needed, as the columns + // are registered at their construction time. + for (ImportWstColumn col: columns) { + // TODO place a current.addColumn(col); here? + } + + differences.add(current); + } + + current = null; + columns = null; + } + + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + } + else { + handleDataLine(line); + } + } + + + private void handleMetaLine(String meta) { + if (handleMetaUnit(meta)) { + return; + } + else { + handleMetaColumnNames(meta); + } + } + + + private boolean handleMetaUnit(String meta) { + Matcher m = META_UNIT.matcher(meta); + + if (m.matches()) { + String unit = m.group(1); + log.debug("Found unit: '" + unit + "'"); + + current.setUnit(new ImportUnit(unit)); + + return true; + } + + return false; + } + + + private boolean handleMetaColumnNames(String meta) { + Pattern META_COLUMN_NAMES = Pattern.compile("Fluss-km;(.*)"); + Matcher m = META_COLUMN_NAMES.matcher(meta); + + if (m.matches()) { + String colStr = m.group(1); + String[] cols = colStr.split(SEPERATOR_CHAR); + + log.debug("Found " + cols.length + " columns."); + + initColumns(cols); + + return true; + } + + return false; + } + + + private void initColumns(String[] cols) { + current.setNumberColumns(cols.length); + columns = current.getColumns().toArray(new ImportWstColumn[cols.length]); + + for (int i = 0; i < cols.length; i++) { + String name = cols[i].replace("\"", ""); + + log.debug("Create new column '" + name + "'"); + current.getColumn(i).setName(name); + current.getColumn(i).setDescription(name); + } + } + + + private void handleDataLine(String line) { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols == null || cols.length < 2) { + log.warn("skip invalid waterlevel-diff line: '" + line + "'"); + return; + } + + try { + Double station = nf.parse(cols[0]).doubleValue(); + + for (int i = 0; i < columns.length; i++) { + int idx = i+1; + + if (idx >= cols.length) { + log.warn("Insufficient column numbers: " + line); + continue; + } + + String value = cols[idx]; + + try { + columns[i].addColumnValue( + new BigDecimal(station), + new BigDecimal(nf.parse(value).doubleValue())); + } + catch (ParseException pe) { + log.warn("Could not parse value: '" + value + "'"); + } + } + } + catch (ParseException pe) { + log.warn("Could not parse station: '" + line + "'"); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/WaterlevelParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,191 @@ +package de.intevation.flys.importer.parsers; + +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import de.intevation.flys.importer.ImportUnit; + +import de.intevation.flys.importer.ImportRange; +import de.intevation.flys.importer.ImportWst; +import de.intevation.flys.importer.ImportWstColumn; +import de.intevation.flys.importer.ImportWstColumnValue; +import de.intevation.flys.importer.ImportWstQRange; + + +/** + * Parse CSV Waterlevel files. + * As these waterlevels are probably used in fixation analysis + * only, functionality to export them to "fixation"-wsts + * has been added (the ImportWaterlevel*- stuff is actually + * not needed to do so.) + */ +public class WaterlevelParser extends LineParser { + + private static final Logger log = Logger.getLogger(WaterlevelParser.class); + + private static final NumberFormat nf = + NumberFormat.getInstance(DEFAULT_LOCALE); + + private static final Pattern META_Q_RANGE = + Pattern.compile("Abfluss\\s\\[(.*)\\];(.*)"); + + public static final Pattern META_UNIT = + Pattern.compile("^Einheit: \\[(.*)\\].*"); + + private List<ImportWst> waterlevels; + + private ImportWst current; + + /** The Waterlevel-Wst s will always have but one column. */ + private ImportWstColumn column; + + /** The current (incomplete) Q Range. */ + private ImportWstQRange currentQRange; + + /** The current (incomplete) km range for Q Range. */ + private ImportRange currentRange; + + private String currentDescription; + + + public WaterlevelParser() { + waterlevels = new ArrayList<ImportWst>(); + } + + + public List<ImportWst> getWaterlevels() { + return waterlevels; + } + + + @Override + public void parse(File file) throws IOException { + currentDescription = file.getName(); + + super.parse(file); + } + + + @Override + protected void reset() { + currentQRange = null; + current = new ImportWst(currentDescription); + current.setNumberColumns(1); + column = current.getColumn(0); + column.setName(currentDescription); + column.setDescription(currentDescription); + current.setKind(6); + } + + + @Override + protected void finish() { + if (current != null) { + if (currentQRange != null) { + List<ImportWstColumnValue> cValues = column.getColumnValues(); + // Set end of range to last station. + currentRange.setB(cValues.get(cValues.size() -1).getPosition()); + currentQRange.setRange(currentRange); + column.addColumnQRange(currentQRange); + } + + waterlevels.add(current); + } + } + + @Override + protected void handleLine(int lineNum, String line) { + if (line.startsWith(START_META_CHAR)) { + handleMetaLine(stripMetaLine(line)); + return; + } + else if (handleQRange(line)) { + return; + } + else { + handleDataLine(line); + return; + } + } + + + private void handleMetaLine(String meta) { + Matcher m = META_UNIT.matcher(meta); + + if (m.matches()) { + String unit = m.group(1); + log.debug("Found unit: '" + unit + "'"); + + current.setUnit(new ImportUnit(unit)); + } + } + + + private boolean handleQRange(String line) { + Matcher m = META_Q_RANGE.matcher(line); + + if (m.matches()) { + String unitStr = m.group(1); + String valueStr = m.group(2); + try { + if (currentQRange != null) { + // Finish off the last one. + List<ImportWstColumnValue> cValues = column.getColumnValues(); + // Set end of range to last station. + currentRange.setB(cValues.get(cValues.size() -1).getPosition()); + currentQRange.setRange(currentRange); + column.addColumnQRange(currentQRange); + } + currentQRange = new ImportWstQRange(null, + new BigDecimal(nf.parse(valueStr).doubleValue())); + currentRange = new ImportRange(); + + log.debug("Found new Q range: Q=" + valueStr); + + return true; + } + catch (ParseException pe) { + log.warn("Unparseable Q range: '" + line + "'"); + } + } + + return false; + } + + + private void handleDataLine(String line) { + String[] cols = line.split(SEPERATOR_CHAR); + + if (cols == null || cols.length < 2) { + log.warn("skip invalid waterlevel line: '" + line + "'"); + return; + } + + try { + // Store the value and remember the position for QRange, if needed. + Double station = nf.parse(cols[0]).doubleValue(); + Double value = nf.parse(cols[1]).doubleValue(); + + BigDecimal stationBD = new BigDecimal(station); + + column.addColumnValue(stationBD, new BigDecimal(value)); + + if (currentRange.getA() == null) { + currentRange.setA(stationBD); + } + } + catch (ParseException pe) { + log.warn("Unparseable number in data row: " + line); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/WstParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,464 @@ +package de.intevation.flys.importer.parsers; + +import java.util.ArrayList; +import java.util.HashSet; + +import java.io.File; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.InputStreamReader; +import java.io.FileInputStream; + +import java.text.NumberFormat; + +import org.apache.log4j.Logger; + +import de.intevation.flys.utils.StringUtil; +import de.intevation.flys.utils.DateGuesser; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import java.math.BigDecimal; + +import de.intevation.flys.importer.ImportWstQRange; +import de.intevation.flys.importer.ImportWstColumn; +import de.intevation.flys.importer.ImportTimeInterval; +import de.intevation.flys.importer.ImportRange; +import de.intevation.flys.importer.ImportUnit; +import de.intevation.flys.importer.ImportWst; + +public class WstParser +{ + private static Logger log = Logger.getLogger(WstParser.class); + + public static final String COLUMN_BEZ_TEXT = "column-bez-text"; + public static final String COLUMN_BEZ_BREITE = "column-bez-breite"; + public static final String COLUMN_QUELLE = "column-quelle"; + public static final String COLUMN_DATUM = "column-datum"; + + public static final BigDecimal UNDEFINED_ZERO = + new BigDecimal(0.0); + public static final BigDecimal MIN_RANGE = + new BigDecimal(-Double.MAX_VALUE); + public static final BigDecimal MAX_RANGE = + new BigDecimal(Double.MAX_VALUE); + + public static final String ENCODING = "ISO-8859-1"; + + public static final Pattern UNIT_COMMENT = + Pattern.compile("\\*\\s*[kK][mM]\\s+(.+)"); + + public static final Pattern UNIT = + Pattern.compile("[^\\[]*\\[([^]]+)\\].*"); + + public static final double INTERVAL_GAP = 0.00001d; + + protected ImportWst wst; + + protected ImportRange lastRange; + + public WstParser() { + } + + public ImportWst getWst() { + return wst; + } + + public void setWst(ImportWst wst) { + this.wst = wst; + } + + public ImportTimeInterval guessDate(String string) { + try { + return new ImportTimeInterval( + DateGuesser.guessDate(string)); + } + catch (IllegalArgumentException iae) { + } + return null; + } + + public void parse(File file) throws IOException { + + log.info("Parsing WST file '" + file + "'"); + + wst = new ImportWst(file.getName()); + + LineNumberReader in = null; + try { + in = + new LineNumberReader( + new InputStreamReader( + new FileInputStream(file), ENCODING)); + + String input; + boolean first = true; + int columnCount = 0; + + String [] lsBezeichner = null; + String [] langBezeichner = null; + int [] colNaWidths = null; + String [] quellen = null; + String [] daten = null; + + BigDecimal [] aktAbfluesse = null; + BigDecimal [] firstAbfluesse = null; + + BigDecimal minKm = MAX_RANGE; + BigDecimal maxKm = MIN_RANGE; + BigDecimal kmHist1 = null; + BigDecimal kmHist2 = null; + + boolean columnHeaderChecked = false; + + String einheit = "Wasserstand [NN + m]"; + + HashSet<BigDecimal> kms = new HashSet<BigDecimal>(); + + while ((input = in.readLine()) != null) { + String line = input; + if (first) { // fetch number of columns + if ((line = line.trim()).length() == 0) { + continue; + } + try { + columnCount = Integer.parseInt(line); + if (columnCount <= 0) { + throw new NumberFormatException( + "number columns <= 0"); + } + log.debug("Number of columns: " + columnCount); + wst.setNumberColumns(columnCount); + lsBezeichner = new String[columnCount]; + } + catch (NumberFormatException nfe) { + log.warn("WST: invalid number.", nfe); + continue; + } + first = false; + continue; + } + + line = line.replace(',', '.'); + + if (line.startsWith("*\u001f")) { + BigDecimal [] data = + parseLineAsDouble(line, columnCount, false, true); + + if (aktAbfluesse != null) { + if (kmHist1 != null && kmHist2 != null + && kmHist1.compareTo(kmHist2) < 0) { + BigDecimal t = minKm; minKm = maxKm; maxKm = t; + } + addInterval(minKm, maxKm, aktAbfluesse); + minKm = MAX_RANGE; + maxKm = MIN_RANGE; + } + + aktAbfluesse = new BigDecimal[columnCount]; + log.debug("new q range: " + columnCount); + for (int i = 0; i < Math.min(columnCount, data.length); ++i) { + if (data[i] != null) { + log.debug(" column: " + data[i]); + aktAbfluesse[i] = data[i]; + } + } + + if (firstAbfluesse == null) { + firstAbfluesse = (BigDecimal [])aktAbfluesse.clone(); + } + continue; + } + + if (line.startsWith("*!")) { + String spezial = line.substring(2).trim(); + + if (spezial.length() == 0) { + continue; + } + + if (spezial.startsWith(COLUMN_BEZ_TEXT)) { + spezial = spezial.substring(COLUMN_BEZ_TEXT.length()).trim(); + if (spezial.length() == 0) { + continue; + } + langBezeichner = StringUtil.splitQuoted(spezial, '"'); + } + else if (spezial.startsWith(COLUMN_BEZ_BREITE)) { + spezial = spezial.substring(COLUMN_BEZ_BREITE.length()).trim(); + + if (spezial.length() == 0) { + continue; + } + + String[] split = spezial.split("\\s+"); + + colNaWidths = new int[split.length]; + for (int i=0; i < split.length; i++) { + colNaWidths[i] = Integer.parseInt(split[i]); + } + } + else if (spezial.startsWith(COLUMN_QUELLE)) { + if (spezial.length() == 0) { + continue; + } + quellen = StringUtil.splitQuoted(spezial, '"'); + } + else if (spezial.startsWith(COLUMN_DATUM)) { + spezial = spezial.substring(COLUMN_DATUM.length()).trim(); + if (spezial.length() == 0) { + continue; + } + daten = StringUtil.splitQuoted(spezial, '"'); + } + continue; + } + + if (line.length() < 11) { + continue; + } + + if (line.startsWith("*")) { + Matcher m = UNIT_COMMENT.matcher(line); + if (m.matches()) { + log.debug("unit comment found"); + // XXX: This hack is needed because desktop + // FLYS is broken figuring out the unit + String [] units = m.group(1).split("\\s{2,}"); + m = UNIT.matcher(units[0]); + einheit = m.matches() ? m.group(1) : units[0]; + log.debug("unit: " + einheit); + } + continue; + } + + if (firstAbfluesse != null) { + if (!columnHeaderChecked) { + int unknownCount = 0; + HashSet<String> uniqueColumnNames = + new HashSet<String>(); + for (int i = 0; i < lsBezeichner.length; ++i) { + if (lsBezeichner[i] == null + || lsBezeichner[i].length() == 0) { + double q = firstAbfluesse[i].doubleValue(); + if (q < 0.001) { + lsBezeichner[i] = + "<unbekannt #" + unknownCount + ">"; + ++unknownCount; + } + else { + lsBezeichner[i] = "Q="+format(q); + } + } + String candidate = lsBezeichner[i]; + int collision = 1; + while (!uniqueColumnNames.add(candidate)) { + candidate = lsBezeichner[i] + + " (" + collision + ")"; + ++collision; + } + ImportWstColumn iwc = wst.getColumn(i); + iwc.setName(candidate); + String potentialDate = daten != null && i < daten.length + ? daten[i] + : candidate; + iwc.setTimeInterval(guessDate(potentialDate)); + } + columnHeaderChecked = true; + } + + BigDecimal [] data = + parseLineAsDouble(line, columnCount, true, false); + + BigDecimal kaem = data[0]; + + if (!kms.add(kaem)) { + log.warn( + "WST: km " + kaem + + " (line " + in.getLineNumber() + + ") found more than once. -> ignored"); + continue; + } + + kmHist2 = kmHist1; + kmHist1 = kaem; + + if (kaem.compareTo(minKm) < 0) { + minKm = kaem; + } + if (kaem.compareTo(maxKm) > 0) { + maxKm = kaem; + } + + // extract values + for (int i = 0; i < columnCount; ++i) { + addValue(kaem, data[i+1], i); + } + + } + else { // firstAbfluesse == null + if (langBezeichner != null) { + lsBezeichner = StringUtil.fitArray( + langBezeichner, lsBezeichner); + } + else if (colNaWidths != null) { + for (int j = 0, i = 0, N = input.length(); + j < colNaWidths.length && i < N; + i += colNaWidths[j++] + ) { + lsBezeichner[j] = input.substring( + i, i+colNaWidths[j]).trim(); + } + } + else { + // first column begins at position 8 in line + for (int i = 8, col = 0; i < input.length(); i += 9) { + if ((i + 9) > input.length()) { + i = input.length() - 10; + } + // one column header is 9 chars wide + lsBezeichner[col++] = + input.substring(i, i + 9).trim(); + + if (col == lsBezeichner.length) { + break; + } + } + } + } + + } // for all lines in WST file + + wst.setUnit(new ImportUnit(einheit)); + + if (kmHist1 != null && kmHist2 != null + && kmHist1.compareTo(kmHist2) < 0) { + BigDecimal t = minKm; minKm = maxKm; maxKm = t; + } + addInterval(minKm, maxKm, aktAbfluesse); + + fixRangesOrder(); + } + finally { + if (in != null) { + in.close(); + } + } + } + + protected void fixRangesOrder() { + wst.fixRangesOrder(); + } + + protected void addValue(BigDecimal km, BigDecimal w, int index) { + if (w != null) { + ImportWstColumn column = wst.getColumn(index); + column.addColumnValue(km, w); + } + } + + private static final NumberFormat NF = getNumberFormat(); + + private static final NumberFormat getNumberFormat() { + NumberFormat nf = NumberFormat.getInstance(); + nf.setMinimumFractionDigits(2); + nf.setMaximumFractionDigits(2); + return nf; + } + + protected static String format(double value) { + return NF.format(value); + } + + protected void addInterval( + BigDecimal from, + BigDecimal to, + BigDecimal [] values + ) { + log.debug("addInterval: " + from + " " + to); + + if (values == null || from == MAX_RANGE || from == MIN_RANGE) { + return; + } + + ImportRange range = new ImportRange(from, to); + + // little workaround to make the q ranges tightly fit. + // Leave a very small gap to ensure that the range queries + // still work. + + if (lastRange != null) { + double a1 = lastRange.getA().doubleValue(); + double b1 = lastRange.getB().doubleValue(); + double a2 = range.getA().doubleValue(); + + if (a1 < b1) { + lastRange.setB(new BigDecimal(a2 - INTERVAL_GAP)); + } + else { // a1 >= b1 + lastRange.setB(new BigDecimal(a2 + INTERVAL_GAP)); + } + } + + for (int i = 0; i < values.length; ++i) { + ImportWstColumn column = wst.getColumn(i); + ImportWstQRange wstQRange = new ImportWstQRange(range, values[i]); + column.addColumnQRange(wstQRange); + } + + lastRange = range; + } + + private static final BigDecimal [] parseLineAsDouble( + String line, + int count, + boolean bStation, + boolean bParseEmptyAsZero + ) { + String [] tokens = parseLine(line, count, bStation); + + BigDecimal [] doubles = new BigDecimal[tokens.length]; + + for (int i = 0; i < doubles.length; ++i) { + String token = tokens[i].trim(); + if (token.length() != 0) { + doubles[i] = new BigDecimal(token); + } + else if (bParseEmptyAsZero) { + doubles[i] = UNDEFINED_ZERO; + } + } + + return doubles; + } + + private static String [] parseLine( + String line, + int tokenCount, + boolean bParseStation + ) { + ArrayList<String> strings = new ArrayList<String>(); + + if (bParseStation) { + if (line.length() < 8) { + throw new IllegalArgumentException("station too short"); + } + strings.add(line.substring(0, 8)); + } + + int pos = 9; + for (int i = 0; i < tokenCount; ++i) { + if (line.length() >= pos + 8) { + strings.add(line.substring(pos, pos + 8)); + } + else { + strings.add(""); + } + pos += 9; + } + + return strings.toArray(new String[strings.size()]); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/tim/Coordinate.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.importer.parsers.tim; + +/** X,Y,Z- triple. */ +public class Coordinate +{ + public double x; + public double y; + public double z; + + public Coordinate() { + } + + public Coordinate(Coordinate c) { + this(c.x, c.y, c.z); + } + + public Coordinate(double x, double y) { + this(x, y, 0d); + } + + public Coordinate(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public final double distanceSqr(double ox, double oy) { + double dx = x - ox; + double dy = y - oy; + return dx*dx + dy*dy; + } + + public final double distance(double xo, double yo) { + return Math.sqrt(distanceSqr(xo, yo)); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/tim/LexiComparator.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,18 @@ +package de.intevation.flys.importer.parsers.tim; + +import java.util.Comparator; + +public class LexiComparator implements Comparator<Coordinate> { + + public static final LexiComparator CMP = new LexiComparator(); + + @Override + public int compare(Coordinate a, Coordinate b) { + if (a.x < b.x) return -1; + if (a.x > b.x) return +1; + if (a.y < b.y) return -1; + if (a.y > b.y) return +1; + return 0; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/tim/Line.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,34 @@ +package de.intevation.flys.importer.parsers.tim; + +/** Two coordinates and a helper. */ +public class Line { + + public Coordinate a; + public Coordinate b; + + public Line() { + } + + public Line(Coordinate a, Coordinate b) { + this.a = a; + this.b = b; + } + + /** Project coordinate to line. */ + public double distanceToFirst(Coordinate c) { + + double nx = b.x - a.x; + double ny = b.y - a.y; + + double len = Math.sqrt(nx*nx + ny*ny); + + nx /= len; + ny /= len; + + double px = c.x - a.x; + double py = c.y - a.y; + + return nx*px + ny*py; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/importer/parsers/tim/TIMParser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,93 @@ +package de.intevation.flys.importer.parsers.tim; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.log4j.Logger; + +import de.intevation.flys.utils.EpsilonComparator; + +/** Parser for single .tim files. */ +public class TIMParser +{ + /** Private logger. */ + private static Logger logger = Logger.getLogger(TIMParser.class); + + /** Proper encoding. */ + public static final String ENCODING = + System.getProperty("tim.encoding", "ISO-8859-1"); + + /** Map of stations (km) to points (xyz). */ + protected Map<Double, List<Coordinate>> lines; + + public TIMParser() { + lines = new TreeMap<Double, List<Coordinate>>(EpsilonComparator.CMP); + } + + /** Access map of stations (km) to coordinates (xyz). */ + public Map<Double, List<Coordinate>> getLines() { + return lines; + } + + /** Get number of lines (data). */ + public int numLines() { + return lines.size(); + } + + /** Parse single .tim file. */ + public void load(String filename) throws IOException { + BufferedReader reader = + new BufferedReader( + new InputStreamReader( + new FileInputStream(filename), ENCODING)); + try { + String row; + while ((row = reader.readLine()) != null) { + if (row.length() < 54) { + logger.warn("row too short"); + continue; + } + double station, x, y, z; + try { + station = Double.parseDouble(row.substring( 9, 16))/1000d; + x = Double.parseDouble(row.substring(20, 30))/1000d; + y = Double.parseDouble(row.substring(30, 40))/1000d; + z = Double.parseDouble(row.substring(47, 54))/10000d; + } catch (NumberFormatException nfe) { + logger.warn("Invalid row"); + continue; + } + + Double km = station; + + List<Coordinate> line = lines.get(km); + if (line == null) { + line = new ArrayList<Coordinate>(); + lines.put(km, line); + } + + line.add(new Coordinate(x, y, z)); + } + // Bring coords in lexicographical order. + sortCoordinates(); + } finally { + reader.close(); + } + } + + /** Sort coordinates of lines lexicographically. */ + protected void sortCoordinates() { + for (List<Coordinate> line: lines.values()) { + Collections.sort(line, LexiComparator.CMP); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Annotation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,111 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "annotations") +public class Annotation +implements Serializable +{ + private Integer id; + private Range range; + private Attribute attribute; + private Position position; + private Edge edge; + private AnnotationType type; + + public Annotation() { + } + + public Annotation( + Range range, + Attribute attribute, + Position position, + Edge edge, + AnnotationType type + ) { + this.range = range; + this.attribute = attribute; + this.position = position; + this.edge = edge; + this.type = type; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_ANNOTATIONS_ID_SEQ", + sequenceName = "ANNOTATIONS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_ANNOTATIONS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "range_id") + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @OneToOne + @JoinColumn(name = "attribute_id") + public Attribute getAttribute() { + return attribute; + } + + public void setAttribute(Attribute attribute) { + this.attribute = attribute; + } + + @OneToOne + @JoinColumn(name = "position_id") + public Position getPosition() { + return position; + } + + public void setPosition(Position position) { + this.position = position; + } + + @OneToOne + @JoinColumn(name = "edge_id") + public Edge getEdge() { + return edge; + } + + public void setEdge(Edge edge) { + this.edge = edge; + } + + @OneToOne + @JoinColumn(name = "type_id") + public AnnotationType getType() { + return type; + } + + public void setType(AnnotationType type) { + this.type = type; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/AnnotationType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,54 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "annotation_types") +public class AnnotationType +implements Serializable +{ + private Integer id; + private String name; + + public AnnotationType() { + } + + public AnnotationType(String name) { + this.name = name; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_ANNOTATION_TYPES_ID_SEQ", + sequenceName = "ANNOTATION_TYPES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_ANNOTATION_TYPES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Attribute.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,55 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "attributes") +public class Attribute +implements Serializable +{ + private Integer id; + + private String value; + + public Attribute() { + } + + public Attribute(String value) { + this.value = value; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_ATTRIBUTES_ID_SEQ", + sequenceName = "ATTRIBUTES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_ATTRIBUTES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "value") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/AxisKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,44 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "axis_kinds") +public class AxisKind implements Serializable { + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return The display Name of the kind as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BedHeightEpoch.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,211 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "bed_height_epoch") +public class BedHeightEpoch implements Serializable { + + private Integer id; + + private River river; + + private TimeInterval timeInterval; + + private ElevationModel curElevationModel; + private ElevationModel oldElevationModel; + + private Range range; + + private String evaluationBy; + private String description; + + private List<BedHeightEpochValue> values; + + + public BedHeightEpoch() { + } + + + public BedHeightEpoch( + River river, + TimeInterval timeInterval, + Range range, + ElevationModel curElevationModel, + ElevationModel oldElevationModel, + String evaluationBy, + String description + ) { + this.river = river; + this.timeInterval = timeInterval; + this.range = range; + this.curElevationModel = curElevationModel; + this.oldElevationModel = oldElevationModel; + this.evaluationBy = evaluationBy; + this.description = description; + this.values = new ArrayList<BedHeightEpochValue>(); + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_BED_HEIGHT_EPOCH_ID_SEQ", + sequenceName = "BED_HEIGHT_EPOCH_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_BED_HEIGHT_EPOCH_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + @OneToOne + @JoinColumn(name = "cur_elevation_model_id") + public ElevationModel getCurElevationModel() { + return curElevationModel; + } + + public void setCurElevationModel(ElevationModel curElevationModel) { + this.curElevationModel = curElevationModel; + } + + @OneToOne + @JoinColumn(name = "old_elevation_model_id") + public ElevationModel getOldElevationModel() { + return oldElevationModel; + } + + public void setOldElevationModel(ElevationModel oldElevationModel) { + this.oldElevationModel = oldElevationModel; + } + + @OneToOne + @JoinColumn(name = "range_id") + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @Column(name = "evaluation_by") + public String getEvaluationBy() { + return evaluationBy; + } + + public void setEvaluationBy(String evaluationBy) { + this.evaluationBy = evaluationBy; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @JoinColumn(name = "bed_height_epoch_id") + public List<BedHeightEpochValue> getValues() { + return values; + } + + public void setValues(List<BedHeightEpochValue> values) { + this.values = values; + } + + + public static List<BedHeightEpoch> getBedHeightEpochs( + River river, + double kmLo, + double kmHi + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightEpoch where river=:river"); + + query.setParameter("river", river); + + // TODO Do km range filtering in SQL statement + + List<BedHeightEpoch> epochs = query.list(); + List<BedHeightEpoch> good = new ArrayList<BedHeightEpoch>(); + + OUTER: for (BedHeightEpoch e: epochs) { + for (BedHeightEpochValue value: e.getValues()) { + double station = value.getStation().doubleValue(); + + if (station >= kmLo && station <= kmHi) { + good.add(e); + continue OUTER; + } + } + } + + return good; + } + + + public static BedHeightEpoch getBedHeightEpochById(int id) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightEpoch where id=:id"); + + query.setParameter("id", id); + + List<BedHeightEpoch> singles = query.list(); + + return singles != null ? singles.get(0) : null; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BedHeightEpochValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,119 @@ +package de.intevation.flys.model; + +import java.util.List; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "bed_height_epoch_values") +public class BedHeightEpochValue +implements Serializable +{ + private static Logger logger = + Logger.getLogger(BedHeightEpochValue.class); + + private Integer id; + + private BedHeightEpoch bedHeight; + + private BigDecimal station; + private BigDecimal height; + + + public BedHeightEpochValue() { + } + + public BedHeightEpochValue( + BedHeightEpoch bedHeight, + BigDecimal station, + BigDecimal height + ) { + this.bedHeight = bedHeight; + this.station = station; + this.height = height; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_BED_EPOCH_VALUE_ID_SEQ", + sequenceName = "BED_EPOCH_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_BED_EPOCH_VALUE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "bed_height_epoch_id" ) + public BedHeightEpoch getBedHeight() { + return bedHeight; + } + + public void setBedHeight(BedHeightEpoch bedHeight) { + this.bedHeight = bedHeight; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "height") + public BigDecimal getHeight() { + return height; + } + + public void setHeight(BigDecimal height) { + this.height = height; + } + + + public static List<BedHeightEpochValue> getBedHeightEpochValues( + BedHeightEpoch epoch, + double kmLo, + double kmHi + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightEpochValue where bedHeight=:epoch " + + " and station >= :kmLo and station <= :kmHi"); + + query.setParameter("epoch", epoch); + query.setParameter("kmLo", new BigDecimal(kmLo)); + query.setParameter("kmHi", new BigDecimal(kmHi)); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BedHeightSingle.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,272 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "bed_height_single") +public class BedHeightSingle implements Serializable { + + private Integer id; + private Integer year; + private Integer soundingWidth; + + private String evaluationBy; + private String description; + + private River river; + + private BedHeightType type; + + private LocationSystem locationSystem; + + private ElevationModel curElevationModel; + + private ElevationModel oldElevationModel; + + private Range range; + + private List<BedHeightSingleValue> values; + + + public BedHeightSingle() { + } + + + public BedHeightSingle( + River river, + Integer year, + Integer soundingWidth, + BedHeightType type, + LocationSystem locationSystem, + ElevationModel curElevationModel, + Range range + ) { + this( + river, + year, + soundingWidth, + type, + locationSystem, + curElevationModel, + null, + range, + null, + null); + } + + + public BedHeightSingle( + River river, + Integer year, + Integer soundingWidth, + BedHeightType type, + LocationSystem locationSystem, + ElevationModel curElevationModel, + ElevationModel oldElevationModel, + Range range, + String evaluationBy, + String description + ) { + this.river = river; + this.year = year; + this.soundingWidth = soundingWidth; + this.type = type; + this.locationSystem = locationSystem; + this.curElevationModel = curElevationModel; + this.oldElevationModel = oldElevationModel; + this.range = range; + this.evaluationBy = evaluationBy; + this.description = description; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_BED_HEIGHT_SINGLE_ID_SEQ", + sequenceName = "BED_HEIGHT_SINGLE_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_BED_HEIGHT_SINGLE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "year") + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + @Column(name = "sounding_width") + public Integer getSoundingWidth() { + return soundingWidth; + } + + public void setSoundingWidth(Integer soundingWidth) { + this.soundingWidth = soundingWidth; + } + + @OneToOne + @JoinColumn(name = "type_id") + public BedHeightType getType() { + return type; + } + + public void setType(BedHeightType type) { + this.type = type; + } + + @OneToOne + @JoinColumn(name = "location_system_id") + public LocationSystem getLocationSystem() { + return locationSystem; + } + + public void setLocationSystem(LocationSystem locationSystem) { + this.locationSystem = locationSystem; + } + + @OneToOne + @JoinColumn(name = "cur_elevation_model_id") + public ElevationModel getCurElevationModel() { + return curElevationModel; + } + + public void setCurElevationModel(ElevationModel curElevationModel) { + this.curElevationModel = curElevationModel; + } + + @OneToOne + @JoinColumn(name = "old_elevation_model_id") + public ElevationModel getOldElevationModel() { + return oldElevationModel; + } + + public void setOldElevationModel(ElevationModel oldElevationModel) { + this.oldElevationModel = oldElevationModel; + } + + @OneToOne + @JoinColumn(name = "range_id") + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @Column(name = "evaluation_by") + public String getEvaluationBy() { + return evaluationBy; + } + + public void setEvaluationBy(String evaluationBy) { + this.evaluationBy = evaluationBy; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @JoinColumn(name = "bed_height_single_id") + public List<BedHeightSingleValue> getValues() { + return values; + } + + public void setValues(List<BedHeightSingleValue> values) { + this.values = values; + } + + + public static List<BedHeightSingle> getBedHeightSingles( + River river, + double kmLo, + double kmHi + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightSingle where river=:river"); + + query.setParameter("river", river); + + // TODO Do km range filtering in SQL statement + + List<BedHeightSingle> singles = query.list(); + List<BedHeightSingle> good = new ArrayList<BedHeightSingle>(); + + for (BedHeightSingle s: singles) { + for (BedHeightSingleValue value: s.getValues()) { + double station = value.getStation().doubleValue(); + + if (station >= kmLo && station <= kmHi) { + good.add(s); + break; + } + } + } + + return good; + } + + + public static BedHeightSingle getBedHeightSingleById(int id) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightSingle where id=:id"); + + query.setParameter("id", id); + + List<BedHeightSingle> singles = query.list(); + + return singles != null ? singles.get(0) : null; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BedHeightSingleValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,167 @@ +package de.intevation.flys.model; + +import java.util.List; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "bed_height_single_values") +public class BedHeightSingleValue +implements Serializable +{ + private static Logger logger = + Logger.getLogger(BedHeightSingleValue.class); + + private Integer id; + + private BedHeightSingle bedHeight; + + private BigDecimal station; + private BigDecimal height; + private BigDecimal uncertainty; + private BigDecimal dataGap; + private BigDecimal soundingWidth; + private BigDecimal width; + + + public BedHeightSingleValue() { + } + + public BedHeightSingleValue( + BedHeightSingle bedHeight, + BigDecimal station, + BigDecimal height, + BigDecimal uncertainty, + BigDecimal dataGap, + BigDecimal soundingWidth, + BigDecimal width + ) { + this.bedHeight = bedHeight; + this.station = station; + this.height = height; + this.uncertainty = uncertainty; + this.dataGap = dataGap; + this.soundingWidth = soundingWidth; + this.width = width; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_BED_SINGLE_VALUE_ID_SEQ", + sequenceName = "BED_SINGLE_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_BED_SINGLE_VALUE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "bed_height_single_id" ) + public BedHeightSingle getBedHeight() { + return bedHeight; + } + + public void setBedHeight(BedHeightSingle bedHeight) { + this.bedHeight = bedHeight; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "height") + public BigDecimal getHeight() { + return height; + } + + public void setHeight(BigDecimal height) { + this.height = height; + } + + @Column(name="uncertainty") + public BigDecimal getUncertainty() { + return uncertainty; + } + + public void setUncertainty(BigDecimal uncertainty) { + this.uncertainty = uncertainty; + } + + @Column(name="data_gap") + public BigDecimal getDataGap() { + return dataGap; + } + + public void setDataGap(BigDecimal dataGap) { + this.dataGap = dataGap; + } + + @Column(name="sounding_width") + public BigDecimal getSoundingWidth() { + return soundingWidth; + } + + public void setSoundingWidth(BigDecimal soundingWidth) { + this.soundingWidth = soundingWidth; + } + + @Column(name="width") + public BigDecimal getWidth() { + return width; + } + + public void setWidth(BigDecimal width) { + this.width = width; + } + + + public static List<BedHeightSingleValue> getBedHeightSingleValues( + BedHeightSingle single, + double kmLo, + double kmHi + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from BedHeightSingleValue where bedHeight=:single " + + " and station >= :kmLo and station <= :kmHi"); + + query.setParameter("single", single); + query.setParameter("kmLo", new BigDecimal(kmLo)); + query.setParameter("kmHi", new BigDecimal(kmHi)); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BedHeightType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,86 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; + +import de.intevation.flys.backend.SessionHolder; + +@Entity +@Table(name = "bed_height_type") +public class BedHeightType +implements Serializable +{ + private static Logger log = Logger.getLogger(BedHeightType.class); + + private Integer id; + private String name; + + + public BedHeightType() { + } + + public BedHeightType(String name) { + this.name = name; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_BED_HEIGHT_TYPE_ID_SEQ", + sequenceName = "BED_HEIGHT_TYPE_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_BED_HEIGHT_TYPE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static BedHeightType fetchBedHeightTypeForType(String type) { + return fetchBedHeightTypeForType(type, null); + } + + public static BedHeightType fetchBedHeightTypeForType(String name, Session session) { + + if (session == null) { + session = SessionHolder.HOLDER.get(); + } + + Query query = session.createQuery( + "from BedHeightType where name=:name"); + + query.setParameter("name", name); + + List<Object> results = query.list(); + + return results.isEmpty() ? null : (BedHeightType)results.get(0); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/BoundaryKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "boundary_kinds") +public class BoundaryKind implements Serializable { + + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return name of the kind of boundary as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Building.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,104 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.LineString; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "buildings") +public class Building +implements Serializable +{ + private Integer id; + private River river; + private String name; + private LineString geom; + + public Building() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public LineString getGeom() { + return geom; + } + + + public void setGeom(LineString geom) { + this.geom = geom; + } + + public static List<Building> getBuildings(int riverId, int kindId) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Building where river.id =:river_id and kind_id=:kind_id"); + query.setParameter("kind_id", kindId); + query.setParameter("river_id", riverId); + + return query.list(); + } + + public static List<Building> getBuildings(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Building where river.id =:river_id and name=:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/CrossSection.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,198 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.List; +import java.util.ArrayList; + +import java.awt.geom.Point2D; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; +import javax.persistence.JoinColumn; + +import java.math.MathContext; +import java.math.BigDecimal; + +import org.hibernate.Session; +import org.hibernate.SQLQuery; +import org.hibernate.Query; + +import org.hibernate.type.StandardBasicTypes; + +import de.intevation.flys.backend.SessionHolder; + +@Entity +@Table(name = "cross_sections") +public class CrossSection +implements Serializable +{ + public static final MathContext PRECISION = new MathContext(6); + + public static final String SQL_FAST_CROSS_SECTION_LINES = + "SELECT km, x, y, csl.id AS csl_id " + + "FROM cross_section_lines csl JOIN cross_section_points csp " + + "ON csp.cross_section_line_id = csl.id " + + "WHERE csl.cross_section_id = :cs_id AND " + + "km between :from_km AND :to_km " + + "ORDER BY csl.id, csp.col_pos"; + + private Integer id; + private River river; + private TimeInterval timeInterval; + private String description; + private List<CrossSectionLine> lines; + + public CrossSection() { + } + + public CrossSection( + River river, + TimeInterval timeInterval, + String description + ) { + this.river = river; + this.timeInterval = timeInterval; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_CROSS_SECTIONS_ID_SEQ", + sequenceName = "CROSS_SECTIONS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_CROSS_SECTIONS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @OrderBy("km") + @JoinColumn(name="cross_section_id") + public List<CrossSectionLine> getLines() { + return lines; + } + + public void setLines(List<CrossSectionLine> lines) { + this.lines = lines; + } + + public List<CrossSectionLine> getLines(double startKm, double endKm) { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from CrossSectionLine where crossSection=:crossSection " + + "and km between :startKm and :endKm order by km"); + query.setParameter("crossSection", this); + query.setParameter("startKm", new BigDecimal(startKm, PRECISION)); + query.setParameter("endKm", new BigDecimal(endKm, PRECISION)); + + return query.list(); + } + + public List<FastCrossSectionLine> getFastLines( + double startKm, + double endKm + ) { + Session session = SessionHolder.HOLDER.get(); + + SQLQuery sqlQuery = session.createSQLQuery(SQL_FAST_CROSS_SECTION_LINES) + .addScalar("km", StandardBasicTypes.DOUBLE) + .addScalar("x", StandardBasicTypes.DOUBLE) + .addScalar("y", StandardBasicTypes.DOUBLE) + .addScalar("csl_id", StandardBasicTypes.INTEGER); + + sqlQuery + .setInteger("cs_id", getId()) + .setDouble("from_km", startKm) + .setDouble("to_km", endKm); + + List<Object []> results = sqlQuery.list(); + + ArrayList<Point2D> points = new ArrayList<Point2D>(500); + ArrayList<FastCrossSectionLine> lines = + new ArrayList<FastCrossSectionLine>(); + + Integer lastId = null; + Double lastKm = null; + + for (Object [] result: results) { + Double km = (Double)result[0]; + Double x = (Double)result[1]; + Double y = (Double)result[2]; + Integer id = (Integer)result[3]; + + if (lastId != null && !lastId.equals(id)) { + points.trimToSize(); + FastCrossSectionLine line = + new FastCrossSectionLine(lastKm, points); + lines.add(line); + points = new ArrayList<Point2D>(500); + } + + Point2D p = new Point2D.Double(x, y); + + if (CrossSectionLine.isValid(p)) { + points.add(p); + } + + lastKm = km; + lastId = id; + } + + if (lastId != null) { + points.trimToSize(); + FastCrossSectionLine line = + new FastCrossSectionLine(lastKm, points); + lines.add(line); + } + + lines.trimToSize(); + + return lines; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/CrossSectionLine.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,174 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Collections; +import java.util.Comparator; + +import java.awt.geom.Point2D; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; +import javax.persistence.JoinColumn; + +import org.apache.log4j.Logger; + +@Entity +@Table(name = "cross_section_lines") +public class CrossSectionLine +implements Serializable +{ + private static Logger logger = Logger.getLogger(CrossSectionLine.class); + + public static final double EPSILON = 1e-4; + + public static final double TOO_SMALL = 0.2; + public static final double TOO_BIG = 2500; + + private Integer id; + private Double km; + private CrossSection crossSection; + + private List<CrossSectionPoint> points; + + public static final Comparator<CrossSectionPoint> COL_POS_CMP = + new Comparator<CrossSectionPoint>() { + @Override + public int compare(CrossSectionPoint a, CrossSectionPoint b) { + double xa = a.getX().doubleValue(); + double xb = b.getX().doubleValue(); + double d = xa - xb; + if (d < -EPSILON) return -1; + if (d > +EPSILON) return +1; + int diff = a.getColPos() - b.getColPos(); + return diff < 0 ? -1 : diff > 0 ? +1 : 0; + } + }; + + + public static final boolean isValid(double x) { + x = Math.abs(x); + return x > TOO_SMALL && x < TOO_BIG; + } + + public static final boolean isValid(Point2D p) { + return isValid(p.getX()) && isValid(p.getY()); + } + + + public CrossSectionLine() { + } + + public CrossSectionLine(CrossSection crossSection, Double km) { + this.crossSection = crossSection; + this.km = km; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_CROSS_SECTION_LINES_ID_SEQ", + sequenceName = "CROSS_SECTION_LINES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_CROSS_SECTION_LINES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "km") + public Double getKm() { + return km; + } + + public void setKm(Double km) { + this.km = km; + } + + @OneToOne + @JoinColumn(name = "cross_section_id") + public CrossSection getCrossSection() { + return crossSection; + } + + public void setCrossSection(CrossSection CrossSection) { + this.crossSection = crossSection; + } + + @OneToMany + @JoinColumn(name="cross_section_line_id") + public List<CrossSectionPoint> getPoints() { + return points; + } + + public void setPoints(List<CrossSectionPoint> points) { + this.points = points; + } + + + public List<Point2D> fetchCrossSectionLinesPoints() { + + List<CrossSectionPoint> linePoints = + new ArrayList<CrossSectionPoint>(getPoints()); + + Collections.sort(linePoints, COL_POS_CMP); + + List<Point2D> points = new ArrayList<Point2D>(linePoints.size()); + for (CrossSectionPoint p: linePoints) { + double x = p.getX().doubleValue(); + double y = p.getY().doubleValue(); + if (isValid(x) && isValid(y)) { + points.add(new Point2D.Double(x, y)); + } + } + + return points; + } + + public double [][] fetchCrossSectionProfile() { + return fetchCrossSectionProfile(fetchCrossSectionLinesPoints()); + } + + public static double [][] fetchCrossSectionProfile(List<Point2D> points) { + + int P = points.size(); + + double [] xs = new double[P]; + double [] ys = new double[P]; + + if (P > 0) { + xs[0] = points.get(0).getX(); + ys[0] = points.get(0).getY(); + + for (int i = 1; i < P; i++) { + Point2D p = points.get(i); + double x = p.getX(); + double y = p.getY(); + + if (x <= xs[i-1]) { + x = xs[i-1] + EPSILON; + } + + xs[i] = x; + ys[i] = y; + } + } + + return new double [][] { xs, ys }; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/CrossSectionPoint.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,96 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +/** Mapped Point of a cross section line. */ +@Entity +@Table(name = "cross_section_points") +public class CrossSectionPoint +implements Serializable +{ + private Integer id; + private CrossSectionLine crossSectionLine; + private Integer colPos; + private Double x; + private Double y; + + public CrossSectionPoint() { + } + + public CrossSectionPoint( + CrossSectionLine crossSectionLine, + Integer colPos, + Double x, + Double y + ) { + this.crossSectionLine = crossSectionLine; + this.colPos = colPos; + this.x = x; + this.y = y; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_CROSS_SECTION_POINTS_ID_SEQ", + sequenceName = "CROSS_SECTION_POINTS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_CROSS_SECTION_POINTS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "cross_section_line_id") + public CrossSectionLine getCrossSectionLine() { + return crossSectionLine; + } + + public void setCrossSectionLine(CrossSectionLine crossSectionLine) { + this.crossSectionLine = crossSectionLine; + } + + @Column(name = "col_pos") + public Integer getColPos() { + return colPos; + } + + public void setColPos(Integer colPos) { + this.colPos = colPos; + } + + @Column(name = "x") + public Double getX() { + return x; + } + + public void setX(Double x) { + this.x = x; + } + + @Column(name = "y") + public Double getY() { + return y; + } + + public void setY(Double y) { + this.y = y; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/CrossSectionTrack.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,200 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.LineString; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "cross_section_tracks") +public class CrossSectionTrack +implements Serializable +{ + private Integer id; + private River river; + private String name; + private LineString geom; + private BigDecimal km; + private BigDecimal z; + + public CrossSectionTrack() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public LineString getGeom() { + return geom; + } + + + public void setGeom(LineString geom) { + this.geom = geom; + } + + + @Column(name = "km") + public BigDecimal getKm() { + return km; + } + + + public void setKm(BigDecimal km) { + this.km = km; + } + + + @Column(name = "z") + public BigDecimal getZ() { + return z; + } + + + public void setZ(BigDecimal z) { + this.z = z; + } + + + public static List<CrossSectionTrack> getCrossSectionTrack( + String river) + { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from CrossSectionTrack where river.name =:river"); + query.setParameter("river", river); + + return query.list(); + } + + + public static List<CrossSectionTrack> getCrossSectionTrack( + String river, + String name + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from CrossSectionTrack as cst " + + " where river.name =:river" + + " and cst.name=:name"); + query.setParameter("river", river); + query.setParameter("name", name); + + return query.list(); + } + + public static List<CrossSectionTrack> getCrossSectionTrack( + String river, + int kind_id + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from CrossSectionTrack as cst " + + " where river.name =:river" + + " and kind_id=:kind_id"); + query.setParameter("river", river); + query.setParameter("kind_id", kind_id); + + return query.list(); + } + + public static List<CrossSectionTrack> getCrossSectionTrack( + String river, + String name, + int kind_id + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from CrossSectionTrack as cst " + + " where river.name =:river" + + " and cst.name=:name" + + " and kind_id=:kind_id"); + query.setParameter("river", river); + query.setParameter("name", name); + query.setParameter("kind_id", kind_id); + + return query.list(); + } + + + /** + * Returns the nearest CrossSectionTrack of <i>river</i> to a given + * <i>km</i>. + * + * @param river The name of a river. + * @param km The kilometer value. + * + * @return the nearest CrossSectionTrack to <i>km</i> of river <i>river</i>. + */ + public static CrossSectionTrack getCrossSectionTrack( + String river, + double km + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from CrossSectionTrack where river.name =:river " + + "and kind_id = 1 " + + "order by abs( km - :mykm)"); + query.setParameter("river", river); + query.setParameter("mykm", new BigDecimal(km)); + + List<CrossSectionTrack> cst = query.list(); + + return cst != null && !cst.isEmpty() ? cst.get(0) : null; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/CrossSectionTrackKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "cross_section_track_kinds") +public class CrossSectionTrackKind implements Serializable { + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return The name of the Cross section kind as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/DGM.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,138 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.SequenceGenerator; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "dem") +public class DGM implements Serializable { + + private Integer id; + private Integer srid; + + private River river; + + private Range range; + private TimeInterval time_interval; + + private String path; + + + public DGM() { + } + + + public void setId(Integer id) { + this.id = id; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_DEM_ID_SEQ", + sequenceName = "DEM_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_DEM_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setPath(String path) { + this.path = path; + } + + @Column(name = "path") + public String getPath() { + return path; + } + + public void setSrid(int srid) { + this.srid = srid; + } + + @Column(name = "srid") + public int getSrid() { + return srid; + } + + public static DGM getDGM(int id) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from DGM where Id =:id"); + query.setParameter("id", id); + + List<DGM> result = query.list(); + + return result.isEmpty() ? null : result.get(0); + } + + + public static DGM getDGM(String river, double lower, double upper) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from DGM where river.name =:river and " + + "range.a <=:lower and range.b >=:lower and " + + "range.a <=:upper and range.b >=:upper"); + query.setParameter("river", river); + query.setParameter("lower", new BigDecimal(lower)); + query.setParameter("upper", new BigDecimal(upper)); + + List<DGM> result = query.list(); + + return result.isEmpty() ? null : result.get(0); + } + + @OneToOne + @JoinColumn(name = "range_id") + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return time_interval; + } + + public void setTimeInterval(TimeInterval time_interval) { + this.time_interval = time_interval; + } + + +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Depth.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,70 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + + +@Entity +@Table(name = "depths") +public class Depth implements Serializable { + + private Integer id; + + private BigDecimal lower; + private BigDecimal upper; + + + public Depth() { + } + + + public Depth(BigDecimal lower, BigDecimal upper) { + this.lower = lower; + this.upper = upper; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_DEPTHS_ID_SEQ", + sequenceName = "DEPTHS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_DEPTHS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "lower") + public BigDecimal getLower() { + return lower; + } + + public void setLower(BigDecimal lower) { + this.lower = lower; + } + + @Column(name = "upper") + public BigDecimal getUpper() { + return upper; + } + + public void setUpper(BigDecimal upper) { + this.upper = upper; + } + +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/DischargeTable.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,193 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.OrderBy; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +@Entity +@Table(name = "discharge_tables") +public class DischargeTable +implements Serializable, Comparable<DischargeTable> +{ + private Integer id; + private Gauge gauge; + private String description; + private String bfgId; + private Integer kind; + private TimeInterval timeInterval; + + private List<DischargeTableValue> dischargeTableValues; + + public DischargeTable() { + kind = 0; + } + + public DischargeTable(Gauge gauge) { + this(gauge, null, null, 0, null); + } + + public DischargeTable( + Gauge gauge, + String description, + String bfgId, + Integer kind, + TimeInterval timeInterval + ) { + this.gauge = gauge; + this.description = description; + this.bfgId = bfgId; + this.kind = kind; + this.timeInterval = timeInterval; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_DISCHARGE_TABLES_ID_SEQ", + sequenceName = "DISCHARGE_TABLES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_DISCHARGE_TABLES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "gauge_id" ) + public Gauge getGauge() { + return gauge; + } + + public void setGauge(Gauge gauge) { + this.gauge = gauge; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Column(name = "bfg_id") + public String getBfgId() { + return bfgId; + } + + public void setBfgId(String bfgId) { + this.bfgId = bfgId; + } + + @Column(name = "kind") + public Integer getKind() { + return kind; + } + + public void setKind(Integer kind) { + this.kind = kind; + } + + @OneToOne + @JoinColumn(name = "time_interval_id" ) + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + @OneToMany + @JoinColumn(name = "table_id") + @OrderBy("q") + public List<DischargeTableValue> getDischargeTableValues() { + return dischargeTableValues; + } + + public void setDischargeTableValues( + List<DischargeTableValue> dischargeTableValues + ) { + this.dischargeTableValues = dischargeTableValues; + } + + @Override + public int compareTo(DischargeTable o) { + if (getKind() == 0 && o.getKind() != 0) { + return 1; + } + + TimeInterval other = o.getTimeInterval(); + if (other == null && timeInterval == null) { + return 1; + } + else if (other == null) { + return -1; + } + else if (timeInterval == null) { + return 1; + } + + Date otherStartTime = other.getStartTime(); + Date thisStartTime = timeInterval.getStartTime(); + + if (otherStartTime == null) { + return -1; + } + else if (thisStartTime == null) { + return 1; + } + + long otherStart = otherStartTime.getTime(); + long thisStart = thisStartTime.getTime(); + + if (otherStart < thisStart) { + return 1; + } + else if (otherStart > thisStart) { + return -1; + } + + Date otherStopTime = other.getStopTime(); + Date thisStopTime = timeInterval.getStopTime(); + + if (otherStopTime == null) { + return -1; + } + else if (thisStopTime == null) { + return 1; + } + + long otherEnd = otherStopTime.getTime(); + long thisEnd = thisStopTime.getTime(); + + if (otherEnd < thisEnd) { + return 1; + } + else if (otherEnd > thisEnd) { + return -1; + } + else { + return 0; + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/DischargeTableValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,84 @@ +package de.intevation.flys.model; + +import java.math.BigDecimal; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "discharge_table_values") +public class DischargeTableValue +implements Serializable +{ + private Integer id; + private DischargeTable dischargeTable; + private BigDecimal q; + private BigDecimal w; + + public DischargeTableValue() { + } + + public DischargeTableValue( + DischargeTable dischargeTable, BigDecimal q, BigDecimal w) + { + this.dischargeTable = dischargeTable; + this.q = q; + this.w = w; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_DISCHARGE_TABLE_VALUES_ID_SEQ", + sequenceName = "DISCHARGE_TABLE_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_DISCHARGE_TABLE_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "table_id" ) + public DischargeTable getDischargeTable() { + return dischargeTable; + } + + public void setDischargeTable(DischargeTable dischargeTable) { + this.dischargeTable = dischargeTable; + } + + + @Column(name = "q") + public BigDecimal getQ() { + return q; + } + + public void setQ(BigDecimal q) { + this.q = q; + } + + @Column(name = "w") + public BigDecimal getW() { + return w; + } + + public void setW(BigDecimal w) { + this.w = w; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/DischargeZone.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,159 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.hibernate.Session; +import org.hibernate.Query; + +import org.apache.log4j.Logger; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "discharge_zone") +public class DischargeZone +implements Serializable +{ + private static Logger logger = Logger.getLogger(DischargeZone.class); + + private Integer id; + + private River river; + + private String gaugeName; + + private BigDecimal value; + + private String lowerDischarge; + private String upperDischarge; + + private String type; + + public DischargeZone() { + } + + + public DischargeZone( + River river, + String gaugeName, + BigDecimal value, + String lowerDischarge, + String upperDischarge + ) { + this.river = river; + this.gaugeName = gaugeName; + this.value = value; + this.lowerDischarge = lowerDischarge; + this.upperDischarge = upperDischarge; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_DISCHARGE_ZONE_ID_SEQ", + sequenceName = "DISCHARGE_ZONE_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_DISCHARGE_ZONE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "value") + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + @Column(name = "gauge_name") + public String getGaugeName() { + return gaugeName; + } + + public void setGaugeName(String gaugeName) { + this.gaugeName = gaugeName; + } + + @Column(name = "lower_discharge") + public String getLowerDischarge() { + return lowerDischarge; + } + + public void setLowerDischarge(String lowerDischarge) { + this.lowerDischarge = lowerDischarge; + } + + @Column(name = "upper_discharge") + public String getUpperDischarge() { + return upperDischarge; + } + + public void setUpperDischarge(String upperDischarge) { + this.upperDischarge = upperDischarge; + } + + public void putType(String type) { + this.type = type; + } + + public String fetchType() { + return this.type; + } + + public static List<DischargeZone> getDischargeZones(River river) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from DischargeZone where river=:river"); + + query.setParameter("river", river); + + return query.list(); + } + + + public static DischargeZone getDischargeZoneById(int id) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from DischargeZone where id=:id"); + + query.setParameter("id", id); + + List<DischargeZone> zones = query.list(); + + return zones.isEmpty() ? null : zones.get(0); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Edge.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,67 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "edges") +public class Edge +implements Serializable +{ + private Integer id; + private BigDecimal top; + private BigDecimal bottom; + + public Edge() { + } + + public Edge(BigDecimal top, BigDecimal bottom) { + this.top = top; + this.bottom = bottom; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_EDGES_ID_SEQ", + sequenceName = "EDGES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_EDGES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "top") + public BigDecimal getTop() { + return top; + } + + public void setTop(BigDecimal top) { + this.top = top; + } + + @Column(name = "bottom") + public BigDecimal getBottom() { + return bottom; + } + + public void setBottom(BigDecimal bottom) { + this.bottom = bottom; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/ElevationModel.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,78 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + + +@Entity +@Table(name = "elevation_model") +public class ElevationModel +implements Serializable +{ + private static Logger logger = Logger.getLogger(ElevationModel.class); + + protected Integer id; + + protected String name; + + protected Unit unit; + + + public ElevationModel() { + } + + + public ElevationModel(String name, Unit unit) { + this.name = name; + this.unit = unit; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_ELEVATION_MODE_ID_SEQ", + sequenceName = "ELEVATION_MODEL_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_ELEVATION_MODE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @OneToOne + @JoinColumn(name = "unit_id") + public Unit getUnit() { + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FastAnnotations.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,335 @@ +package de.intevation.flys.model; + +import java.util.Comparator; +import java.util.ArrayList; +import java.util.List; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.NoSuchElementException; + +import java.io.Serializable; + +import org.hibernate.Session; +import org.hibernate.SQLQuery; + +import org.hibernate.type.StandardBasicTypes; + +import de.intevation.flys.backend.SessionHolder; + +public class FastAnnotations +implements Serializable +{ + public static final String SQL_BY_RIVER_NAME = + "SELECT r.a AS a, r.b AS b, p.value AS position, " + + "at.value AS attribute, ant.name AS name, " + + "e.top AS top, e.bottom AS bottom " + + "FROM annotations an " + + "JOIN ranges r " + + "ON an.range_id = r.id " + + "JOIN attributes at " + + "ON an.attribute_id = at.id " + + "JOIN positions p " + + "ON an.position_id = p.id " + + "JOIN rivers riv " + + "ON r.river_id = riv.id " + + "LEFT JOIN annotation_types ant " + + "ON an.type_id = ant.id " + + "LEFT JOIN edges e " + + "ON an.edge_id = e.id " + + "WHERE riv.name = :river_name " + + "ORDER BY r.a"; + + public static final String SQL_BY_RIVER_ID = + "SELECT r.a AS a, r.b AS b, p.value AS position, " + + "at.value AS attribute, ant.name AS name, " + + "e.top AS top, e.bottom AS bottom " + + "FROM annotations an " + + "JOIN ranges r " + + "ON an.range_id = r.id " + + "JOIN attributes at " + + "ON an.attribute_id = at.id " + + "JOIN positions p " + + "ON an.position_id = p.id " + + "LEFT JOIN annotation_types ant " + + "ON an.type_id = ant.id " + + "LEFT JOIN edges e " + + "ON an.edge_id = e.id " + + "WHERE r.id = :river_id " + + "ORDER BY r.a"; + + public static final double EPSILON = 1e-5; + + public static final Comparator<Annotation> KM_CMP = + new Comparator<Annotation>() { + @Override + public int compare(Annotation a, Annotation b) { + double diff = a.a - b.a; + if (diff < -EPSILON) return -1; + if (diff > +EPSILON) return +1; + return 0; + } + }; + + public static final class Annotation + implements Serializable + { + private double a; + private double b; + private String position; + private String attribute; + private String name; + private double top; + private double bottom; + + public Annotation() { + } + + public Annotation(double a) { + this.a = a; + } + + public Annotation( + double a, + double b, + String position, + String attribute, + String name, + double top, + double bottom + ) { + this.a = a; + this.b = b; + this.position = position; + this.attribute = attribute; + this.name = name; + this.top = top; + this.bottom = bottom; + } + + public double getA() { + return a; + } + + public double getB() { + return b; + } + + public String getPosition() { + return position; + } + + public String getAttribute() { + return attribute; + } + + public String getName() { + return name; + } + + public double getTop() { + return top; + } + + public double getBottom() { + return bottom; + } + + @Override + public String toString() { + return "[a=" + a + ";b=" + b + + ";pos=" + position + ";attr=" + attribute + + ";name=" + name + ";top=" + top + + ";bot=" + bottom + "]"; + } + } // class Annotation + + public interface Filter { + + boolean accept(Annotation annotation); + + } // interface Filter + + public static class NameFilter implements Filter { + + private String name; + + public NameFilter(String name) { + this.name = name; + } + + @Override + public boolean accept(Annotation annotation) { + return annotation.getName().contains(name); + } + } // class NameFilter + + public static final Filter ALL = new Filter() { + @Override + public boolean accept(Annotation annotation) { + return true; + } + }; + + public static final Filter IS_POINT = new Filter() { + @Override + public boolean accept(Annotation annotation) { + return Double.isNaN(annotation.getB()); + } + }; + + public static final Filter IS_RANGE = new Filter() { + @Override + public boolean accept(Annotation annotation) { + return !Double.isNaN(annotation.getB()); + } + }; + + private Annotation [] annotations; + + public FastAnnotations() { + } + + public FastAnnotations(Annotation [] annotations) { + this.annotations = annotations; + } + + public FastAnnotations(String riverName) { + this(loadByRiverName(riverName)); + } + + public FastAnnotations(int riverId) { + this(loadByRiverId(riverId)); + } + + public FastAnnotations(Iterator<Annotation> iter) { + this(toArray(iter)); + } + + public int size() { + return annotations.length; + } + + public Iterator<Annotation> filter(final Filter filter) { + return new Iterator<Annotation>() { + + private int idx; + private Annotation current = findNext(); + + @Override + public boolean hasNext() { + return current != null; + } + + @Override + public Annotation next() { + if (current == null) { + throw new NoSuchElementException(); + } + Annotation result = current; + current = findNext(); + return result; + } + + private Annotation findNext() { + + while (idx < annotations.length) { + Annotation annotation = annotations[idx++]; + if (filter.accept(annotation)) { + return annotation; + } + } + + return null; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + public static Annotation [] toArray(Iterator<Annotation> iter) { + + ArrayList<Annotation> list = new ArrayList<Annotation>(); + + while (iter.hasNext()) { + list.add(iter.next()); + } + + return list.toArray(new Annotation[list.size()]); + } + + public Annotation findByKm(double km) { + Annotation key = new Annotation(km); + int idx = Arrays.binarySearch(annotations, key, KM_CMP); + return idx < 0 ? null : annotations[idx]; + } + + private static SQLQuery createQuery(String query) { + Session session = SessionHolder.HOLDER.get(); + + return session.createSQLQuery(query) + .addScalar("a", StandardBasicTypes.DOUBLE) + .addScalar("b", StandardBasicTypes.DOUBLE) + .addScalar("position", StandardBasicTypes.STRING) + .addScalar("attribute", StandardBasicTypes.STRING) + .addScalar("name", StandardBasicTypes.STRING) + .addScalar("top", StandardBasicTypes.DOUBLE) + .addScalar("bottom", StandardBasicTypes.DOUBLE); + } + + private static Annotation [] buildAnnotations(List<Object []> list) { + Annotation [] anns = new Annotation[list.size()]; + + // Names are likely the same because they are a type + // like 'Pegel' or 'Hafen'. + HashMap<String, String> names = new HashMap<String, String>(); + + for (int i = 0; i < anns.length; ++i) { + Object [] data = list.get(i); + double a = ((Double)data[0]); + double b = data[1] != null ? (Double)data[1] : Double.NaN; + String position = (String)data[2]; + String attribute = (String)data[3]; + String name = (String)data[4]; + double top = data[5] != null ? (Double)data[5] : Double.NaN; + double bottom = data[6] != null ? (Double)data[6] : Double.NaN; + + if (name != null) { + String old = names.get(name); + if (old != null) { + name = old; + } + else { + names.put(name, name); + } + } + + anns[i] = new Annotation( + a, b, position, attribute, name, top, bottom); + } + + return anns; + } + + public static Annotation [] loadByRiverName(String riverName) { + + SQLQuery query = createQuery(SQL_BY_RIVER_NAME); + + query.setString("river_name", riverName); + + return buildAnnotations(query.list()); + } + + public static Annotation [] loadByRiverId(int riverId) { + + SQLQuery query = createQuery(SQL_BY_RIVER_ID); + + query.setInteger("river_id", riverId); + + return buildAnnotations(query.list()); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FastCrossSectionLine.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,68 @@ +package de.intevation.flys.model; + +import java.util.List; +import java.util.Comparator; + +import java.io.Serializable; + +import java.awt.geom.Point2D; + +public class FastCrossSectionLine +implements Serializable +{ + public static final double EPSILON = 1e-5; + + public static final Comparator<FastCrossSectionLine> KM_CMP = + new Comparator<FastCrossSectionLine>() { + public int compare( + FastCrossSectionLine a, + FastCrossSectionLine b + ) { + double diff = a.km - b.km; + if (diff < -EPSILON) return -1; + return diff > +EPSILON ? +1 : 0; + } + }; + + protected double km; + protected List<Point2D> points; + + public FastCrossSectionLine() { + } + + public FastCrossSectionLine(double km) { + this.km = km; + } + + public FastCrossSectionLine(double km, List<Point2D> points) { + this(km); + this.points = points; + } + + public FastCrossSectionLine(CrossSectionLine csl) { + Double kmBD = csl.getKm(); + km = kmBD != null ? kmBD.doubleValue() : 0d; + points = csl.fetchCrossSectionLinesPoints(); + } + + public double getKm() { + return km; + } + + public void setKm(double km) { + this.km = km; + } + + public List<Point2D> getPoints() { + return points; + } + + public void setPoints(List<Point2D> points) { + this.points = points; + } + + public double [][] fetchCrossSectionProfile() { + return CrossSectionLine.fetchCrossSectionProfile(points); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FedState.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "fed_states") +public class FedState implements Serializable { + + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return name of the Federal State as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Fixpoint.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,130 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.Point; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "fixpoints") +public class Fixpoint +implements Serializable +{ + private Integer id; + private River river; + private Integer x; + private Integer y; + private BigDecimal km; + private String hpgp; + private Point geom; + + public Fixpoint() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "x") + public Integer getX() { + return x; + } + + + public void setX(Integer x) { + this.x = x; + } + + + @Column(name = "y") + public Integer getY() { + return y; + } + + + public void setY(Integer y) { + this.y = y; + } + + + @Column(name = "km") + public BigDecimal getKm() { + return km; + } + + + public void setKm(BigDecimal km) { + this.km = km; + } + + + @Column(name = "hpgp") + public String getHpgp() { + return hpgp; + } + + + public void setHpgp(String hpgp) { + this.hpgp = hpgp; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Point getGeom() { + return geom; + } + + + public void setGeom(Point geom) { + this.geom = geom; + } + + + public static List<Fixpoint> getFixpoints(int riverId) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Fixpoint where river.id =:river_id"); + query.setParameter("river_id", riverId); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Floodmaps.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,155 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.Geometry; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "floodmaps") +public class Floodmaps +implements Serializable +{ + private Integer id; + private River river; + private String name; + private Integer kind; + private Integer count; + private BigDecimal diff; + private BigDecimal area; + private BigDecimal perimeter; + private Geometry geom; + + public Floodmaps() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "kind") + public Integer getKind() { + return kind; + } + + + public void setKind(Integer kind) { + this.kind = kind; + } + + + @Column(name = "count") + public Integer getCount() { + return count; + } + + + public void setCount(Integer count) { + this.count = count; + } + + + @Column(name = "diff") + public BigDecimal getDiff() { + return diff; + } + + + public void setDiff(BigDecimal diff) { + this.diff = diff; + } + + + @Column(name = "area") + public BigDecimal getArea() { + return area; + } + + + public void setArea(BigDecimal area) { + this.area = area; + } + + + @Column(name = "perimeter") + public BigDecimal getPerimeter() { + return perimeter; + } + + + public void setPerimeter(BigDecimal perimeter) { + this.perimeter = perimeter; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Geometry getGeom() { + return geom; + } + + + public void setGeom(Geometry geom) { + this.geom = geom; + } + + + public static List<Floodmaps> getFloodmaps(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Floodmaps where river.id =:river_id AND name =:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Floodmark.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,129 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.Point; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "flood_marks") +public class Floodmark +implements Serializable +{ + private Integer id; + private River river; + private Integer z; + private Integer year; + private BigDecimal km; + private Point geom; + + public Floodmark() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "z") + public Integer getZ() { + return z; + } + + + public void setZ(Integer z) { + this.z = z; + } + + + @Column(name = "year") + public Integer getYear() { + return year; + } + + + public void setYear(Integer year) { + this.year = year; + } + + + @Column(name = "km") + public BigDecimal getKm() { + return km; + } + + + public void setKm(BigDecimal km) { + this.km = km; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Point getGeom() { + return geom; + } + + + public void setGeom(Point geom) { + this.geom = geom; + } + + public static List<Floodmark> getFloodmarks(int riverId) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Floodmark where river.id =:river_id"); + query.setParameter("river_id", riverId); + + return query.list(); + } + + public static List<Floodmark> getFloodmarks(int riverId, int year) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Floodmark where river.id =:river_id and year = :year"); + query.setParameter("river_id", riverId); + query.setParameter("year", year); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Floodplain.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,134 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.annotations.Type; +import org.hibernate.HibernateException; + +import com.vividsolutions.jts.geom.Polygon; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "floodplain") +public class Floodplain +implements Serializable +{ + private Integer id; + + private FloodplainKind kind; + + private River river; + + private Polygon geom; + + private String name; + + + public Floodplain() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "kind_id") + public FloodplainKind getKind() { + return kind; + } + + public void setKind(FloodplainKind kind) { + this.kind = kind; + } + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Polygon getGeom() { + return geom; + } + + public void setGeom(Polygon geom) { + this.geom = geom; + } + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + public static List<Floodplain> getFloodplains(String river, String name, int kind) + throws HibernateException { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from Floodplain as fp where river.name =:river" + + " and kind.id =:kind" + + " and fp.name=:name"); + query.setParameter("river", river); + query.setParameter("kind", kind); + query.setParameter("name", name); + + List<Floodplain> list = query.list(); + return list.isEmpty() ? null : list; + } + + public static List<Floodplain> getFloodplains(String river, int kind) + throws HibernateException { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from Floodplain where river.name =:river AND kind.id =:kind"); + query.setParameter("river", river); + query.setParameter("kind", kind); + + List<Floodplain> list = query.list(); + return list.isEmpty() ? null : list; + } + + public static Floodplain getFloodplain(String river) { + Session session = SessionHolder.HOLDER.get(); + + // kind_id 0 -> Offical + // kind_id 1 -> Misc. + Query query = session.createQuery( + "from Floodplain where river.name =:river and kind_id=1"); + query.setParameter("river", river); + + List<Floodplain> result = query.list(); + + return result.isEmpty() ? null : result.get(0); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FloodplainKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "floodplain_kinds") +public class FloodplainKind implements Serializable { + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return The name of the Floodplain Kind as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FlowVelocityMeasurement.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,96 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +import org.apache.log4j.Logger; + + +@Entity +@Table(name = "flow_velocity_measurements") +public class FlowVelocityMeasurement +implements Serializable +{ + private static Logger logger = + Logger.getLogger(FlowVelocityMeasurement.class); + + private Integer id; + + private River river; + + private String description; + + private List<FlowVelocityMeasurementValue> values; + + + public FlowVelocityMeasurement() { + } + + + public FlowVelocityMeasurement(River river, String description) { + this.river = river; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_FV_MEASURE_ID_SEQ", + sequenceName = "FV_MEASURE_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_FV_MEASURE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @JoinColumn(name = "measurements_id") + public List<FlowVelocityMeasurementValue> getValues() { + return values; + } + + public void setValues(List<FlowVelocityMeasurementValue> values) { + this.values = values; + } + + public void addValue(FlowVelocityMeasurementValue value) { + this.values.add(value); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FlowVelocityMeasurementValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,196 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + + +/** Measured Flow Velocities. */ +@Entity +@Table(name = "flow_velocity_measure_values") +public class FlowVelocityMeasurementValue +implements Serializable +{ + private static Logger logger = + Logger.getLogger(FlowVelocityMeasurementValue.class); + + private Integer id; + + private FlowVelocityMeasurement measurement; + + private BigDecimal station; + private BigDecimal w; + private BigDecimal q; + private BigDecimal v; + + private Date datetime; + + private String description; + + /** Non-mapped class holding same values. */ + public static class FastFlowVelocityMeasurementValue { + protected double station; + protected double w; + protected double q; + protected double v; + protected Date datetime; + protected String description; + + public FastFlowVelocityMeasurementValue(double station, + double w, double q, double v, Date datetime, String description) { + this.station = station; + this.w = w; + this.q = q; + this.v = v; + this.datetime = datetime; + this.description = description; + } + + public double getStation() { + return station; + } + + public double getW() { + return w; + } + + public double getQ() { + return q; + } + + public double getV() { + return v; + } + + public Date getDatetime() { + return datetime; + } + + public String getDescription() { + return description; + } + } + + + public FlowVelocityMeasurementValue() { + } + + + public FlowVelocityMeasurementValue( + FlowVelocityMeasurement measurement, + Date datetime, + BigDecimal station, + BigDecimal w, + BigDecimal q, + BigDecimal v, + String description + ) { + this.measurement = measurement; + this.datetime = datetime; + this.station = station; + this.w = w; + this.q = q; + this.v = v; + this.description = description; + } + + public static FastFlowVelocityMeasurementValue getUnmapped( + double station, double w, double q, double v, Date datetime, String description) { + return new FastFlowVelocityMeasurementValue( + station, w, q, v, datetime, description); + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_FV_MEASURE_VALUES_ID_SEQ", + sequenceName = "FV_MEASURE_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_FV_MEASURE_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "measurements_id") + public FlowVelocityMeasurement getMeasurement() { + return measurement; + } + + public void setMeasurement(FlowVelocityMeasurement measurement) { + this.measurement = measurement; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "datetime") + public Date getDatetime() { + return datetime; + } + + public void setDatetime(Date datetime) { + this.datetime = datetime; + } + + @Column(name = "w") + public BigDecimal getW() { + return w; + } + + public void setW(BigDecimal w) { + this.w = w; + } + + @Column(name = "q") + public BigDecimal getQ() { + return q; + } + + public void setQ(BigDecimal q) { + this.q = q; + } + + @Column(name = "v") + public BigDecimal getV() { + return v; + } + + public void setV(BigDecimal v) { + this.v = v; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FlowVelocityModel.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,106 @@ +package de.intevation.flys.model; + +import de.intevation.flys.backend.SessionHolder; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.apache.log4j.Logger; + +import org.hibernate.Query; +import org.hibernate.Session; + + +@Entity +@Table(name = "flow_velocity_model") +public class FlowVelocityModel +implements Serializable +{ + private static Logger logger = Logger.getLogger(FlowVelocityModel.class); + + + private Integer id; + + private DischargeZone dischargeZone; + + private String description; + + + public FlowVelocityModel() { + } + + + public FlowVelocityModel(DischargeZone dischargeZone) { + this(dischargeZone, null); + } + + + public FlowVelocityModel( + DischargeZone dischargeZone, + String description + ) { + this.dischargeZone = dischargeZone; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_FLOW_VELOCITY_MODEL_ID_SEQ", + sequenceName = "FLOW_VELOCITY_MODEL_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_FLOW_VELOCITY_MODEL_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "discharge_zone_id") + public DischargeZone getDischargeZone() { + return dischargeZone; + } + + public void setDischargeZone(DischargeZone dischargeZone) { + this.dischargeZone = dischargeZone; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public static List<FlowVelocityModel> getModels(DischargeZone zone) { + + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from FlowVelocityModel where dischargeZone=:zone"); + + query.setParameter("zone", zone); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/FlowVelocityModelValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,158 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.hibernate.Session; +import org.hibernate.Query; + +import org.apache.log4j.Logger; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "flow_velocity_model_values") +public class FlowVelocityModelValue +implements Serializable +{ + private static Logger logger = + Logger.getLogger(FlowVelocityModelValue.class); + + + private Integer id; + + private FlowVelocityModel flowVelocity; + + private BigDecimal station; + private BigDecimal q; + private BigDecimal totalChannel; + private BigDecimal mainChannel; + private BigDecimal shearStress; + + + public FlowVelocityModelValue() { + } + + + public FlowVelocityModelValue( + FlowVelocityModel flowVelocity, + BigDecimal station, + BigDecimal q, + BigDecimal totalChannel, + BigDecimal mainChannel, + BigDecimal shearStress + ) { + this.flowVelocity = flowVelocity; + this.station = station; + this.q = q; + this.totalChannel = totalChannel; + this.mainChannel = mainChannel; + this.shearStress = shearStress; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_FLOW_VELOCITY_M_VALUES_ID_SEQ", + sequenceName = "FLOW_VELOCITY_M_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_FLOW_VELOCITY_M_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "flow_velocity_model_id") + public FlowVelocityModel getFlowVelocity() { + return flowVelocity; + } + + public void setFlowVelocity(FlowVelocityModel flowVelocity) { + this.flowVelocity = flowVelocity; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "q") + public BigDecimal getQ() { + return q; + } + + public void setQ(BigDecimal q) { + this.q = q; + } + + @Column(name = "total_channel") + public BigDecimal getTotalChannel() { + return totalChannel; + } + + public void setTotalChannel(BigDecimal totalChannel) { + this.totalChannel = totalChannel; + } + + @Column(name = "main_channel") + public BigDecimal getMainChannel() { + return mainChannel; + } + + public void setMainChannel(BigDecimal mainChannel) { + this.mainChannel = mainChannel; + } + + @Column(name = "shear_stress") + public BigDecimal getShearStress() { + return shearStress; + } + + public void setShearStress(BigDecimal shearStress) { + this.shearStress = shearStress; + } + + + public static List<FlowVelocityModelValue> getValues( + FlowVelocityModel model, + double kmLo, + double kmHi + ) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from FlowVelocityModelValue where " + + " flowVelocity=:model and" + + " station >= :kmLo and " + + " station <= :kmHi"); + + query.setParameter("model", model); + query.setParameter("kmLo", new BigDecimal(kmLo)); + query.setParameter("kmHi", new BigDecimal(kmHi)); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Gauge.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,334 @@ +package de.intevation.flys.model; + +import java.math.BigDecimal; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + +/** Database-mapped Gauge with all info about it. */ +@Entity +@Table(name = "gauges") +public class Gauge +implements Serializable, Comparable<Gauge> +{ + public static final int DEFAULT_SCALE = 100; + + public static final int MASTER_DISCHARGE_TABLE = 0; + + private Integer id; + private String name; + private River river; + private BigDecimal station; + private BigDecimal aeo; + private BigDecimal datum; + private Long officialNumber; + private Range range; + + private List<DischargeTable> dischargeTables; + + /** MainValues at this Gauge. */ + protected List<MainValue> mainValues; + + public Gauge() { + } + + public Gauge( + String name, + River river, + BigDecimal station, + BigDecimal aeo, + BigDecimal datum, + Long officialNumber, + Range range + ) { + this.name = name; + this.river = river; + this.station = station; + this.aeo = aeo; + this.datum = datum; + this.officialNumber = officialNumber; + this.range = range; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_GAUGES_ID_SEQ", + sequenceName = "GAUGES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_GAUGES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "station") // FIXME: type mapping needed + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "aeo") // FIXME: type mapping needed + public BigDecimal getAeo() { + return aeo; + } + + public void setAeo(BigDecimal aeo) { + this.aeo = aeo; + } + + @Column(name = "datum") // FIXME: type mapping needed + public BigDecimal getDatum() { + return datum; + } + + public void setDatum(BigDecimal datum) { + this.datum = datum; + } + + @Column(name = "official_number") + public Long getOfficialNumber() { + return officialNumber; + } + + public void setOfficialNumber(Long officialNumber) { + this.officialNumber = officialNumber; + } + + @OneToOne + @JoinColumn(name = "range_id" ) + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @OneToMany + @JoinColumn(name = "gauge_id") + public List<DischargeTable> getDischargeTables() { + return dischargeTables; + } + + public void setDischargeTables(List<DischargeTable> dischargeTables) { + this.dischargeTables = dischargeTables; + } + + + /** + * Returns min and max W values of this gauge based with a DEFAULT_SCALE. + * + * @return min and max W value of this gauge [min,max]. + */ + public double[] determineMinMaxW() { + return determineMinMaxW(DEFAULT_SCALE); + } + + + /** + * Returns min and max W values of this gauge. + * + * @return the min and max W value of this gauge [min,max]. + */ + public double[] determineMinMaxW(int scale) { + Session session = SessionHolder.HOLDER.get(); + + List<DischargeTable> tables = getDischargeTables(); + DischargeTable dischargeTable = null; + + for (DischargeTable tmp: tables) { + if (tmp.getKind() == 0) { + dischargeTable = tmp; + break; + } + } + + if (dischargeTable == null) { + return null; + } + + Query query = session.createQuery( + "select min(w) as min, max(w) as max from DischargeTableValue " + + "where table_id =:table"); + query.setParameter("table", dischargeTable.getId()); + + List results = query.list(); + Object[] result = (Object[]) results.get(0); + + return result != null + ? new double[] { + ((BigDecimal) result[0]).doubleValue() * scale, + ((BigDecimal) result[1]).doubleValue() * scale} + : null; + } + + @OneToMany + @JoinColumn(name = "gauge_id") + public List<MainValue> getMainValues() { + return mainValues; + } + + public void setMainValues(List<MainValue> mainValues) { + this.mainValues = mainValues; + } + + + public static Gauge getGaugeByOfficialNumber(long number) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Gauge where officialNumber=:number"); + + query.setParameter("number", number); + + List<Gauge> results = query.list(); + + return results.isEmpty() ? null : results.get(0); + } + + + public DischargeTable fetchMasterDischargeTable() { + for (DischargeTable dt: dischargeTables) { + if (dt.getKind() == MASTER_DISCHARGE_TABLE) { + return dt; + } + } + + return null; + } + + /** + * Returns an array of [days, qs] necessary to create duration curves. + * + * @return a 2dim array of [days, qs] where days is an int[] and qs is + * an double[]. + */ + public Object[] fetchDurationCurveData() { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "select cast(nmv.name as integer) as days, mv.value as q " + + "from MainValue as mv " + + "join mv.mainValue as nmv " + + "join nmv.type mvt " + + "where mvt.name = 'D' and mv.gauge.id = :gauge_id " + + "order by days"); + + query.setParameter("gauge_id", getId()); + + List<Object> results = query.list(); + int[] days = new int[results.size()]; + double[] qs = new double[results.size()]; + + int idx = 0; + + for (Object obj: results) { + Object[] arr = (Object[]) obj; + + try { + int day = ((Integer) arr[0]).intValue(); + double q = ((BigDecimal) arr[1]).doubleValue(); + + days[idx] = day; + qs[idx++] = q; + } + catch (NumberFormatException nfe) { + } + } + + return new Object[] { days, qs }; + } + + /** + * Calculates the maximum and minimum W and Q values + * + * @return the MaxMinWQ object representing the calculated values + */ + public MinMaxWQ fetchMaxMinWQ() { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "select max(mv.value) as max, min(mv.value) as min " + + "from MainValue as mv " + + "join mv.mainValue as nmv " + + "join nmv.type mvt " + + "where mvt.name in ('W', 'Q') " + + "and mv.gauge.id = :gauge_id " + + "group by mvt.name order by mvt.name" + ); + + query.setParameter("gauge_id", getId()); + + List<Object> results = query.list(); + if (results.isEmpty()) { + // No values found + return new MinMaxWQ(); + } + + Object[] arr = (Object[]) results.get(0); + BigDecimal maxw = (BigDecimal)arr[0]; + BigDecimal minw = (BigDecimal)arr[1]; + BigDecimal maxq = null; + BigDecimal minq = null; + + + if (results.size() > 1) { + arr = (Object[]) results.get(1); + maxq = (BigDecimal)arr[0]; + minq = (BigDecimal)arr[1]; + } + + return new MinMaxWQ(minw, maxw, minq, maxq); + } + + @Override + public int compareTo(Gauge o) { + return getName().compareTo(o.getName()); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/GaugeLocation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,106 @@ +package de.intevation.flys.model; + +import com.vividsolutions.jts.geom.Point; + +import de.intevation.flys.backend.SessionHolder; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Query; +import org.hibernate.Session; + +import org.hibernate.annotations.Type; + + +@Entity +@Table(name = "gauge_location") +public class GaugeLocation +implements Serializable +{ + private Integer id; + private River river; + private String name; + private Point geom; + + + public GaugeLocation() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Point getGeom() { + return geom; + } + + + public void setGeom(Point geom) { + this.geom = geom; + } + + + /** + * Returns a list of RiverAxisKm objects for a given river. + * + * @param riverid The ID of a river in the database. + * + * @return a list of RiverAxisKm objects. + */ + public static List<GaugeLocation> getGaugeLocations(int riverid, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from GaugeLocation where river.id =:riverid and name=:name"); + query.setParameter("riverid", riverid); + query.setParameter("name", name); + + List<GaugeLocation> list = query.list(); + + return list; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/GrainFraction.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,94 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +import org.apache.log4j.Logger; + + +@Entity +@Table(name = "grain_fraction") +public class GrainFraction +implements Serializable +{ + public static final String TOTAL = "total"; + public static final String COARSE = "coarse"; + public static final String FINE_MIDDLE = "fine_middle"; + public static final String SAND = "sand"; + public static final String SUSP_SAND = "susp_sand"; + public static final String SUSP_SAND_BED = "susp_sand_bed"; + public static final String SUSPENDED_SEDIMENT = "suspended_sediment"; + + + private static Logger logger = Logger.getLogger(GrainFraction.class); + + private Integer id; + + private String name; + + private Double lower; + private Double upper; + + + public GrainFraction() { + } + + public GrainFraction(String name, Double lower, Double upper) { + this.name = name; + this.lower = lower; + this.upper = upper; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_GRAIN_FRACTION_ID_SEQ", + sequenceName = "GRAIN_FRACTION_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_GRAIN_FRACTION_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name" ) + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "lower") + public Double getLower() { + return lower; + } + + public void setLower(Double lower) { + this.lower = lower; + } + + @Column(name = "upper") + public Double getUpper() { + return upper; + } + + public void setUpper(Double upper) { + this.upper = upper; + } + +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HWSKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,44 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "hws_kinds") +public class HWSKind implements Serializable { + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return The name of the Hochwasserschutzanlagenart as String. + */ + @Column(name = "kind") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HWSLine.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,336 @@ +package de.intevation.flys.model; + +import com.vividsolutions.jts.geom.Geometry; + +import de.intevation.flys.model.HWSKind; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.SequenceGenerator; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import de.intevation.flys.backend.SessionHolder; + +@Entity +@Table(name = "hws_lines") +public class HWSLine implements Serializable { + + private Integer id; + + private Integer ogrFid; + private HWSKind kind; + private FedState fedState; + private River river; + private Integer official; + private Integer shoreSide; + private String name; + private String path; + private String agency; + private String range; + private String source; + private String status_date; + private String description; + private Geometry geom; + + @Id + @SequenceGenerator( + name = "SEQUENCE_HWS_LINES_ID_SEQ", + sequenceName = "HWS_LINES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HWS_LINES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Geometry getGeom() { + return geom; + } + + + public void setGeom(Geometry geom) { + this.geom = geom; + } + + /** + * Get ogrFid. + * + * @return ogrFid as Integer. + */ + @Column(name = "ogr_fid") + public Integer getOgrFid() { + return ogrFid; + } + + /** + * Set ogrFid. + * + * @param ogrFid the value to set. + */ + public void setOgrFid(Integer ogrFid) { + this.ogrFid = ogrFid; + } + + + /** + * Get official. + * + * @return official as Integer. + */ + @Column(name = "official") + public Integer getofficial() { + return official; + } + + /** + * Set official. + * + * @param official the value to set. + */ + public void setofficial(Integer official) { + this.official = official; + } + + /** + * Get shoreSide. + * + * @return shoreSide as Integer. + */ + @Column(name = "shore_side") + public Integer getShoreSide() { + return shoreSide; + } + + /** + * Set shoreSide. + * + * @param shoreSide the value to set. + */ + public void setShoreSide(Integer shoreSide) { + this.shoreSide = shoreSide; + } + + /** + * Get name. + * + * @return name as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get path. + * + * @return path as String. + */ + @Column(name = "path") + public String getPath() { + return path; + } + + /** + * Set path. + * + * @param path the value to set. + */ + public void setPath(String path) { + this.path = path; + } + + /** + * Get agency. + * + * @return agency as String. + */ + @Column(name = "agency") + public String getAgency() { + return agency; + } + + /** + * Set agency. + * + * @param agency the value to set. + */ + public void setAgency(String agency) { + this.agency = agency; + } + + /** + * Get range. + * + * @return range as String. + */ + @Column(name = "range") + public String getRange() { + return range; + } + + /** + * Set range. + * + * @param range the value to set. + */ + public void setRange(String range) { + this.range = range; + } + + /** + * Get source. + * + * @return source as String. + */ + @Column(name = "source") + public String getSource() { + return source; + } + + /** + * Set source. + * + * @param source the value to set. + */ + public void setSource(String source) { + this.source = source; + } + + /** + * Get status_date. + * + * @return status_date as String. + */ + @Column(name = "status_date") + public String getStatusDate() { + return status_date; + } + + /** + * Set status_date. + * + * @param status_date the value to set. + */ + public void setStatusDate(String status_date) { + this.status_date = status_date; + } + + /** + * Get description. + * + * @return description as String. + */ + @Column(name = "description") + public String getDescription() { + return description; + } + + /** + * Set description. + * + * @param description the value to set. + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Get kind. + * + * @return kind as HWSKind. + */ + @OneToOne + @JoinColumn(name = "kind_id") + public HWSKind getKind() { + return kind; + } + + /** + * Set kind. + * + * @param kind the value to set. + */ + public void setKind(HWSKind kind) { + this.kind = kind; + } + + /** + * Get fedState. + * + * @return fedState as FedState. + */ + @OneToOne + @JoinColumn(name = "fed_state_id") + public FedState getFedState() { + return fedState; + } + + /** + * Set fedState. + * + * @param fedState the value to set. + */ + public void setFedState(FedState fedState) { + this.fedState = fedState; + } + + /** + * Get river. + * + * @return river as River. + */ + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + /** + * Set river. + * + * @param river the value to set. + */ + public void setRiver(River river) { + this.river = river; + } + + public static List<HWSLine> getLines(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from HWSLine where river.id =:river_id and name=:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HWSPoint.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,457 @@ +package de.intevation.flys.model; + +import com.vividsolutions.jts.geom.Geometry; + +import java.io.Serializable; +import java.util.List; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.SequenceGenerator; + +import org.hibernate.annotations.Type; +import org.hibernate.Session; +import org.hibernate.Query; + +import de.intevation.flys.backend.SessionHolder; + +@Entity +@Table(name = "hws_points") +public class HWSPoint implements Serializable { + + private Integer id; + + private Integer ogrFid; + private HWSKind kind; + private FedState fedState; + private River river; + private Integer official; + private Integer shoreSide; + private String name; + private String path; + private String agency; + private String range; + private String source; + private String statusDate; + private String description; + private BigDecimal freeboard; + private BigDecimal dikeKm; + private BigDecimal z; + private BigDecimal zTarget; + private BigDecimal ratedLevel; + private Geometry geom; + + @Id + @SequenceGenerator( + name = "SEQUENCE_HWS_POINTS_ID_SEQ", + sequenceName = "HWS_POINTS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HWS_POINTS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Geometry getGeom() { + return geom; + } + + + public void setGeom(Geometry geom) { + this.geom = geom; + } + + /** + * Get ogrFid. + * + * @return ogrFid as Integer. + */ + @Column(name = "ogr_fid") + public Integer getOgrFid() { + return ogrFid; + } + + /** + * Set ogrFid. + * + * @param ogrFid the value to set. + */ + public void setOgrFid(Integer ogrFid) { + this.ogrFid = ogrFid; + } + + + /** + * Get official. + * + * @return official as Integer. + */ + @Column(name = "official") + public Integer getofficial() { + return official; + } + + /** + * Set official. + * + * @param official the value to set. + */ + public void setofficial(Integer official) { + this.official = official; + } + + /** + * Get shoreSide. + * + * @return shoreSide as Integer. + */ + @Column(name = "shore_side") + public Integer getShoreSide() { + return shoreSide; + } + + /** + * Set shoreSide. + * + * @param shoreSide the value to set. + */ + public void setShoreSide(Integer shoreSide) { + this.shoreSide = shoreSide; + } + + /** + * Get name. + * + * @return name as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get path. + * + * @return path as String. + */ + @Column(name = "path") + public String getPath() { + return path; + } + + /** + * Set path. + * + * @param path the value to set. + */ + public void setPath(String path) { + this.path = path; + } + + /** + * Get agency. + * + * @return agency as String. + */ + @Column(name = "agency") + public String getAgency() { + return agency; + } + + /** + * Set agency. + * + * @param agency the value to set. + */ + public void setAgency(String agency) { + this.agency = agency; + } + + /** + * Get range. + * + * @return range as String. + */ + @Column(name = "range") + public String getRange() { + return range; + } + + /** + * Set range. + * + * @param range the value to set. + */ + public void setRange(String range) { + this.range = range; + } + + /** + * Get source. + * + * @return source as String. + */ + @Column(name = "source") + public String getSource() { + return source; + } + + /** + * Set source. + * + * @param source the value to set. + */ + public void setSource(String source) { + this.source = source; + } + + /** + * Get statusDate. + * + * @return statusDate as String. + */ + @Column(name = "status_date") + public String getStatusDate() { + return statusDate; + } + + /** + * Set statusDate. + * + * @param statusDate the value to set. + */ + public void setStatusDate(String statusDate) + { + this.statusDate = statusDate; + } + + /** + * Get description. + * + * @return description as String. + */ + @Column(name = "description") + public String getDescription() + { + return description; + } + + /** + * Set description. + * + * @param description the value to set. + */ + public void setDescription(String description) + { + this.description = description; + } + + /** + * Get freeboard. + * + * @return freeboard as BigDecimal. + */ + @Column(name = "freeboard") + public BigDecimal getFreeboard() + { + return freeboard; + } + + /** + * Set freeboard. + * + * @param freeboard the value to set. + */ + public void setFreeboard(BigDecimal freeboard) + { + this.freeboard = freeboard; + } + + /** + * Get dikeKm. + * + * @return dikeKm as BigDecimal. + */ + @Column(name = "dike_km") + public BigDecimal getDikeKm() + { + return dikeKm; + } + + /** + * Set dikeKm. + * + * @param dikeKm the value to set. + */ + public void setDikeKm(BigDecimal dikeKm) + { + this.dikeKm = dikeKm; + } + + /** + * Get z. + * + * @return z as BigDecimal. + */ + @Column(name = "z") + public BigDecimal getZ() + { + return z; + } + + /** + * Set z. + * + * @param z the value to set. + */ + public void setZ(BigDecimal z) + { + this.z = z; + } + + /** + * Get zTarget. + * + * @return zTarget as BigDecimal. + */ + @Column(name = "z_target") + public BigDecimal getZTarget() + { + return zTarget; + } + + /** + * Set zTarget. + * + * @param zTarget the value to set. + */ + public void setZTarget(BigDecimal zTarget) + { + this.zTarget = zTarget; + } + + /** + * Get ratedLevel. + * + * @return ratedLevel as BigDecimal. + */ + @Column(name = "rated_level") + public BigDecimal getRatedLevel() + { + return ratedLevel; + } + + /** + * Set ratedLevel. + * + * @param ratedLevel the value to set. + */ + public void setRatedLevel(BigDecimal ratedLevel) + { + this.ratedLevel = ratedLevel; + } + + /** + * Get kind. + * + * @return kind as HWSKind. + */ + @OneToOne + @JoinColumn(name = "kind_id") + public HWSKind getKind() + { + return kind; + } + + /** + * Set kind. + * + * @param kind the value to set. + */ + public void setKind(HWSKind kind) + { + this.kind = kind; + } + + /** + * Get fedState. + * + * @return fedState as FedState. + */ + @OneToOne + @JoinColumn(name = "fed_state_id") + public FedState getFedState() + { + return fedState; + } + + /** + * Set fedState. + * + * @param fedState the value to set. + */ + public void setFedState(FedState fedState) + { + this.fedState = fedState; + } + + /** + * Get river. + * + * @return river as River. + */ + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() + { + return river; + } + + /** + * Set river. + * + * @param river the value to set. + */ + public void setRiver(River river) + { + this.river = river; + } + + public static List<HWSPoint> getPoints(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from HWSPoint where river.id =:river_id and name=:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HYK.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,85 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "hyks") +public class HYK +implements Serializable +{ + private Integer id; + private River river; + private String description; + + private List<HYKEntry> entries; + + public HYK() { + } + + public HYK(River river, String description) { + this.river = river; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYKS_ID_SEQ", + sequenceName = "HYKS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYKS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @OrderBy("km") + @JoinColumn(name="hyk_id") + public List<HYKEntry> getEntries() { + return entries; + } + + public void setEntries(List<HYKEntry> entries) { + this.entries = entries; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HYKEntry.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,99 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.math.BigDecimal; + +import java.util.Date; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "hyk_entries") +public class HYKEntry +implements Serializable +{ + private Integer id; + private HYK hyk; + private BigDecimal km; + private Date measure; + + private List<HYKFormation> formations; + + public HYKEntry() { + } + + public HYKEntry(HYK hyk, BigDecimal km, Date measure) { + this.hyk = hyk; + this.km = km; + this.measure = measure; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYK_ENTRIES_ID_SEQ", + sequenceName = "HYK_ENTRIES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYK_ENTRIES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "hyk_id") + public HYK getHYK() { + return hyk; + } + + public void setHYK(HYK hyk) { + this.hyk = hyk; + } + + @Column(name = "km") + public BigDecimal getKm() { + return km; + } + + public void setKm(BigDecimal km) { + this.km = km; + } + + @Column(name = "measure") + public Date getMeasure() { + return measure; + } + + public void setMeasure(Date measure) { + this.measure = measure; + } + + @OneToMany + @OrderBy("formationNum") + @JoinColumn(name="hyk_entry_id") + public List<HYKFormation> getFormations() { + return formations; + } + + public void setFormations(List<HYKFormation> formations) { + this.formations = formations; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HYKFlowZone.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,98 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "hyk_flow_zones") +public class HYKFlowZone +implements Serializable +{ + private Integer id; + private HYKFormation formation; + private HYKFlowZoneType type; + private BigDecimal a; + private BigDecimal b; + + public HYKFlowZone() { + } + + public HYKFlowZone( + HYKFormation formation, + HYKFlowZoneType type, + BigDecimal a, + BigDecimal b + ) { + this.formation = formation; + this.type = type; + this.a = a; + this.b = b; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYK_FLOW_ZONES_ID_SEQ", + sequenceName = "HYK_FLOW_ZONES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYK_FLOW_ZONES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "formation_id") + public HYKFormation getFormation() { + return formation; + } + + public void setFormation(HYKFormation formation) { + this.formation = formation; + } + + @OneToOne + @JoinColumn(name = "type_id") + public HYKFlowZoneType getType() { + return type; + } + + public void setType(HYKFlowZoneType type) { + this.type = type; + } + + @Column(name = "a") + public BigDecimal getA() { + return a; + } + + public void setA(BigDecimal a) { + this.a = a; + } + + @Column(name = "b") + public BigDecimal getB() { + return b; + } + + public void setB(BigDecimal b) { + this.b = b; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HYKFlowZoneType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,69 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "hyk_flow_zone_types") +public class HYKFlowZoneType +implements Serializable +{ + private Integer id; + private String name; + private String description; + + public HYKFlowZoneType() { + } + + public HYKFlowZoneType(String name) { + this.name = name; + } + + public HYKFlowZoneType(String name, String description) { + this.name = name; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYK_FLOW_ZONE_TYPES_ID_SEQ", + sequenceName = "HYK_FLOW_ZONE_TYPES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYK_FLOW_ZONE_TYPES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HYKFormation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,151 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.List; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "hyk_formations") +public class HYKFormation +implements Serializable +{ + private Integer id; + private Integer formationNum; + private HYKEntry entry; + private BigDecimal top; + private BigDecimal bottom; + private BigDecimal distanceVL; + private BigDecimal distanceHF; + private BigDecimal distanceVR; + + private List<HYKFlowZone> zones; + + public HYKFormation() { + } + + public HYKFormation( + Integer formationNum, + HYKEntry entry, + BigDecimal top, + BigDecimal bottom, + BigDecimal distanceVL, + BigDecimal distanceHF, + BigDecimal distanceVR + ) { + this.formationNum = formationNum; + this.entry = entry; + this.top = top; + this.bottom = bottom; + this.distanceVL = distanceVL; + this.distanceHF = distanceHF; + this.distanceVR = distanceVR; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYK_FORMATIONS_ID_SEQ", + sequenceName = "HYK_FORMATIONS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYK_FORMATIONS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "formation_num") + public Integer getFormationNum() { + return formationNum; + } + + public void setFormationNum(Integer formationNum) { + this.formationNum = formationNum; + } + + @OneToOne + @JoinColumn(name = "hyk_entry_id") + public HYKEntry getEntry() { + return entry; + } + + public void setEntry(HYKEntry entry) { + this.entry = entry; + } + + @Column(name = "top") + public BigDecimal getTop() { + return top; + } + + public void setTop(BigDecimal top) { + this.top = top; + } + + @Column(name = "bottom") + public BigDecimal getBottom() { + return bottom; + } + + public void setBottom(BigDecimal bottom) { + this.bottom = bottom; + } + + @Column(name = "distance_vl") + public BigDecimal getDistanceVL() { + return distanceVL; + } + + public void setDistanceVL(BigDecimal distanceVL) { + this.distanceVL = distanceVL; + } + + @Column(name = "distance_hf") + public BigDecimal getDistanceHF() { + return distanceHF; + } + + public void setDistanceHF(BigDecimal distanceHF) { + this.distanceHF = distanceHF; + } + + @Column(name = "distance_vr") + public BigDecimal getDistanceVR() { + return distanceVR; + } + + public void setDistanceVR(BigDecimal distanceVR) { + this.distanceVR = distanceVR; + } + + + @OneToMany + @OrderBy("a") + @JoinColumn(name="formation_id") + public List<HYKFlowZone> getZones() { + return zones; + } + + public void setZones(List<HYKFlowZone> zones) { + this.zones = zones; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HydrBoundary.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,184 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.SequenceGenerator; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.MultiLineString; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "hydr_boundaries") +public class HydrBoundary +implements Serializable +{ + private Integer id; + private SectieKind sectie; + private SobekKind sobek; + private String name; + private River river; + private MultiLineString geom; + private BoundaryKind kind; + + public HydrBoundary() { + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYDR_BOUNDARIES_ID_SEQ", + sequenceName = "HYDR_BOUNDARIES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYDR_BOUNDARIES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public MultiLineString getGeom() { + return geom; + } + + + public void setGeom(MultiLineString geom) { + this.geom = geom; + } + + public static List<HydrBoundary> getHydrBoundaries(int riverId, String name, int kindId) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from HydrBoundary where river.id =:river_id and name=:name" + + " and kind.id=:kind_id"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + query.setParameter("kind_id", kindId); + + return query.list(); + } + + public static List<HydrBoundary> getHydrBoundaries(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from HydrBoundary where river.id =:river_id and name=:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } + + /** + * Get sectie. + * + * @return sectie as SectieKind. + */ + @OneToOne + @JoinColumn(name = "sectie") + public SectieKind getSectie() + { + return sectie; + } + + /** + * Set sectie. + * + * @param sectie the value to set. + */ + public void setSectie(SectieKind sectie) + { + this.sectie = sectie; + } + + /** + * Get sobek. + * + * @return sobek as SobekKind. + */ + @OneToOne + @JoinColumn(name = "sobek") + public SobekKind getSobek() + { + return sobek; + } + + /** + * Set sobek. + * + * @param sobek the value to set. + */ + public void setSobek(SobekKind sobek) + { + this.sobek = sobek; + } + + /** + * Get kind. + * + * @return kind as BoundaryKind. + */ + @OneToOne + @JoinColumn(name = "kind") + public BoundaryKind getKind() + { + return kind; + } + + /** + * Set kind. + * + * @param kind the value to set. + */ + public void setKind(BoundaryKind kind) + { + this.kind = kind; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/HydrBoundaryPoly.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,194 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.SequenceGenerator; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.Geometry; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "hydr_boundaries_poly") +public class HydrBoundaryPoly +implements Serializable +{ + private Integer id; + private String name; + private River river; + private Geometry geom; + private SectieKind sectie; + private SobekKind sobek; + private BoundaryKind kind; + + public HydrBoundaryPoly() { + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_HYDR_BOUNDARIES_POLY_ID_SEQ", + sequenceName = "HYDR_BOUNDARIES_POLY_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_HYDR_BOUNDARIES_POLY_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Geometry getGeom() { + return geom; + } + + + public void setGeom(Geometry geom) { + this.geom = geom; + } + + + public static List<HydrBoundaryPoly> getHydrBoundaries(int riverId, String name) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from HydrBoundaryPoly where river.id =:river_id and name=:name"); + query.setParameter("river_id", riverId); + query.setParameter("name", name); + + return query.list(); + } + + public static List<HydrBoundaryPoly> getHydrBoundaries(int riverId, + int kind, int sectie, int sobek) { + Session session = SessionHolder.HOLDER.get(); + + String filter = " where river.id =:river_id"; + + if (kind != -1) { + filter += " and kind = " + kind; + } + if (sectie != -1) { + filter += " and sectie = " + sectie; + } + if (sobek != -1){ + filter += " and sobek = " + sobek; + } + + Query query = session.createQuery("from HydrBoundaryPoly" + filter); + query.setParameter("river_id", riverId); + return query.list(); + } + + /** + * Get sectie. + * + * @return sectie as SectieKind. + */ + @OneToOne + @JoinColumn(name = "sectie") + public SectieKind getSectie() + { + return sectie; + } + + /** + * Set sectie. + * + * @param sectie the value to set. + */ + public void setSectie(SectieKind sectie) + { + this.sectie = sectie; + } + + /** + * Get sobek. + * + * @return sobek as SobekKind. + */ + @OneToOne + @JoinColumn(name = "sobek") + public SobekKind getSobek() + { + return sobek; + } + + /** + * Set sobek. + * + * @param sobek the value to set. + */ + public void setSobek(SobekKind sobek) + { + this.sobek = sobek; + } + + /** + * Get kind. + * + * @return kind as BoundaryKind. + */ + @OneToOne + @JoinColumn(name = "kind") + public BoundaryKind getKind() + { + return kind; + } + + /** + * Set kind. + * + * @param kind the value to set. + */ + public void setKind(BoundaryKind kind) + { + this.kind = kind; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Jetty.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,79 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import com.vividsolutions.jts.geom.Geometry; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import de.intevation.flys.backend.SessionHolder; + +@Entity +@Table(name = "jetties") +public class Jetty +implements Serializable +{ + private Integer id; + private River river; + private Geometry geom; + + public Jetty() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Geometry getGeom() { + return geom; + } + + + public void setGeom(Geometry geom) { + this.geom = geom; + } + + public static List<Jetty> getJetties(int riverId, int kindId) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Jetty where river.id =:river_id and kind_id=:kind_id"); + query.setParameter("kind_id", kindId); + query.setParameter("river_id", riverId); + + return query.list(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/LocationSystem.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,68 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + + +@Entity +@Table(name = "location_system") +public class LocationSystem implements Serializable { + + protected Integer id; + + protected String name; + protected String description; + + + public LocationSystem() { + } + + + public LocationSystem(String name, String description) { + this.name = name; + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_LOCATION_SYSTEM_ID_SEQ", + sequenceName = "LOCATION_SYSTEM_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_LOCATION_SYSTEM_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MainValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,105 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; +import javax.persistence.GenerationType; + +import java.math.BigDecimal; + + +/** A Main or Extreme value of a rivers gauge. */ +@Entity +@Table(name = "main_values") +public class MainValue +implements Serializable +{ + private Integer id; + + private Gauge gauge; + + private NamedMainValue mainValue; + + private BigDecimal value; + + private TimeInterval timeInterval; + + public MainValue() { + } + + public MainValue( + Gauge gauge, + NamedMainValue mainValue, + BigDecimal value, + TimeInterval timeInterval + ) { + this.gauge = gauge; + this.mainValue = mainValue; + this.value = value; + this.timeInterval = timeInterval; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_MAIN_VALUES_ID_SEQ", + sequenceName = "MAIN_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_MAIN_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "gauge_id") + public Gauge getGauge() { + return gauge; + } + + public void setGauge(Gauge gauge) { + this.gauge = gauge; + } + + @OneToOne + @JoinColumn(name = "named_value_id") + public NamedMainValue getMainValue() { + return mainValue; + } + + public void setMainValue(NamedMainValue mainValue) { + this.mainValue = mainValue; + } + + @Column(name = "value") // FIXME: type mapping needed? + public BigDecimal getValue() { + return value; + } + + public void setValue(BigDecimal value) { + this.value = value; + } + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MainValueType.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,54 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "main_value_types") +public class MainValueType +implements Serializable +{ + private Integer id; + private String name; + + public MainValueType() { + } + + public MainValueType(String name) { + this.name = name; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_MAIN_VALUE_TYPES_ID_SEQ", + sequenceName = "MAIN_VALUE_TYPES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_MAIN_VALUE_TYPES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") // FIXME: Type conversion needed? + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MeasurementStation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,171 @@ +package de.intevation.flys.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + + +@Entity +@Table(name = "measurement_station") +public class MeasurementStation { + + private Integer id; + + private String name; + private String measurementType; + private String riverside; + private String operator; + private String description; + + private Double station; + private Range range; + + private River river; + + private Gauge gauge; + private String gaugeName; + + private TimeInterval observationTimerange; + + public MeasurementStation() { + } + + public MeasurementStation(River river, String name, String measurementType, + String riverside, Double station, Range range, Gauge gauge, + String gaugeName, TimeInterval observationTimerange, String operator, + String description + ) { + this.river = river; + this.name = name; + this.measurementType = measurementType; + this.riverside = riverside; + this.station = station; + this.range = range; + this.gauge = gauge; + this.gaugeName = gaugeName; + this.observationTimerange = observationTimerange; + this.operator = operator; + this.description = description; + } + + @Id + @SequenceGenerator(name = "SEQ_MEASUREMENT_STATION_ID_SEQ", sequenceName = "MEASUREMENT_STATION_ID_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_MEASUREMENT_STATION_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "measurement_type") + public String getMeasurementType() { + return measurementType; + } + + public void setMeasurementType(String measurementType) { + this.measurementType = measurementType; + } + + @Column(name = "riverside") + public String getRiverside() { + return riverside; + } + + public void setRiverside(String riverside) { + this.riverside = riverside; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "reference_gauge_id") + public Gauge getGauge() { + return gauge; + } + + public void setGauge(Gauge gauge) { + this.gauge = gauge; + } + + @Column(name = "reference_gauge_name") + public String getGaugeName() { + return gaugeName; + } + + public void setGaugeName(String gaugeName) { + this.gaugeName = gaugeName; + } + + @Column(name = "station") + public Double getStation() { + return station; + } + + public void setStation(Double station) { + this.station = station; + } + + @OneToOne + @JoinColumn(name = "range_id") + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @OneToOne + @JoinColumn(name = "observation_timerange_id") + public TimeInterval getObservationTimerange() { + return observationTimerange; + } + + public void setObservationTimerange(TimeInterval observationTimerange) { + this.observationTimerange = observationTimerange; + } + + @Column(name = "operator") + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MinMaxWQ.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,58 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * Represents minmimum and maximum values for W and Q + */ +public class MinMaxWQ implements Serializable { + + private BigDecimal minw; + private BigDecimal maxw; + private BigDecimal minq; + private BigDecimal maxq; + + /** + * Default constuctor to indecate that no min and max w and q values + * are available + */ + public MinMaxWQ() { + } + + /** + * Constructor for a new MinMaxWQ value + * + * @param minw Mimimim W + * @param maxw Maximum W + * @param minq Mimimim Q + * @param maxq Maximum Q + */ + public MinMaxWQ( + BigDecimal minw, + BigDecimal maxw, + BigDecimal minq, + BigDecimal maxq) + { + this.minw = minw; + this.maxw = maxw; + this.minq = minq; + this.maxq = maxq; + } + + public BigDecimal getMinW() { + return this.minw; + } + + public BigDecimal getMaxW() { + return this.maxw; + } + + public BigDecimal getMinQ() { + return this.minq; + } + + public BigDecimal getMaxQ() { + return this.maxq; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MorphologicalWidth.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,88 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; + + +@Entity +@Table(name = "morphologic_width") +public class MorphologicalWidth implements Serializable { + + private Integer id; + + private River river; + + private Unit unit; + + private List<MorphologicalWidthValue> values; + + + public MorphologicalWidth() { + } + + + public MorphologicalWidth(River river, Unit unit) { + this.river = river; + this.unit = unit; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_MORPHOLOGIC_WIDTH_ID_SEQ", + sequenceName = "MORPHOLOGIC_WIDTH_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_MORPHOLOGIC_WIDTH_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "unit_id") + public Unit getUnit() { + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } + + @OneToMany + @JoinColumn(name = "morphologic_width_id") + public List<MorphologicalWidthValue> getValues() { + return values; + } + + public void setValues(List<MorphologicalWidthValue> values) { + this.values = values; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/MorphologicalWidthValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,103 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + + +@Entity +@Table(name = "morphologic_width_values") +public class MorphologicalWidthValue implements Serializable { + + private Integer id; + + private MorphologicalWidth morphologicalWidth; + + private BigDecimal station; + private BigDecimal width; + + private String description; + + + public MorphologicalWidthValue() { + } + + + public MorphologicalWidthValue( + MorphologicalWidth morphologicalWidth, + BigDecimal station, + BigDecimal width, + String description + ) { + this.morphologicalWidth = morphologicalWidth; + this.station = station; + this.width = width; + this.description = description; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_MORPH_WIDTH_VALUES_ID_SEQ", + sequenceName = "MORPH_WIDTH_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_MORPH_WIDTH_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "morphologic_width_id") + public MorphologicalWidth getMorphologicalWidth() { + return morphologicalWidth; + } + + public void setMorphologicalWidth(MorphologicalWidth width) { + this.morphologicalWidth = width; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "width") + public BigDecimal getWidth() { + return width; + } + + public void setWidth(BigDecimal width) { + this.width = width; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/NamedMainValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,68 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "named_main_values") +public class NamedMainValue +implements Serializable +{ + private Integer id; + private String name; + private MainValueType type; + + public NamedMainValue() { + } + + public NamedMainValue(String name, MainValueType type) { + this.name = name; + this.type = type; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_NAMED_MAIN_VALUES_ID_SEQ", + sequenceName = "NAMED_MAIN_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_NAMED_MAIN_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @OneToOne + @JoinColumn(name = "type_id" ) + public MainValueType getType() { + return type; + } + + public void setType(MainValueType type) { + this.type = type; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Position.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,71 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.OneToMany; +import javax.persistence.JoinColumn; +import javax.persistence.GenerationType; + +import java.util.List; + +@Entity +@Table(name = "positions") +public class Position +implements Serializable +{ + private Integer id; + + private String value; + + private List<Annotation> annotations; + + public Position() { + } + + public Position(String value) { + this.value = value; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_POSITIONS_ID_SEQ", + sequenceName = "POSITIONS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_POSITIONS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "value") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @OneToMany + @JoinColumn(name="position_id") + public List<Annotation> getAnnotations() { + return annotations; + } + + public void setAnnotations(List<Annotation> annotations) { + this.annotations = annotations; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Range.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,173 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +@Entity +@Table(name = "ranges") +public class Range +implements Serializable +{ + public static final double EPSILON = 1e-5; + private Integer id; + private BigDecimal a; + private BigDecimal b; + + private River river; + + public Range() { + } + + public Range(double a, double b, River river) { + this(new BigDecimal(a), new BigDecimal(b), river); + } + + public Range(BigDecimal a, BigDecimal b, River river) { + this.a = a; + this.b = b; + this.river = river; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_RANGES_ID_SEQ", + sequenceName = "RANGES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_RANGES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "a") // FIXME: type mapping needed? + public BigDecimal getA() { + return a; + } + + public void setA(BigDecimal a) { + this.a = a; + } + + @Column(name = "b") // FIXME: type mapping needed? + public BigDecimal getB() { + return b; + } + + public void setB(BigDecimal b) { + this.b = b; + } + + public boolean containsTolerant(double x) { + return containsTolerant(x, EPSILON); + } + + public boolean containsTolerant(double x, double tolerance) { + BigDecimal b = this.b != null ? this.b : a; + double av = a.doubleValue(); + double bv = b.doubleValue(); + if (av > bv) { + double t = av; + av = bv; + bv = t; + } + return x+tolerance >= av && x-tolerance <= bv; + } + + public boolean contains(double x) { + BigDecimal b = this.b != null ? this.b : a; + double av = a.doubleValue(); + double bv = b.doubleValue(); + if (av > bv) { + double t = av; + av = bv; + bv = t; + } + return x >= av && x <= bv; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + public int code() { + int code = 0; + if (a != null) code = 1; + if (b != null) code |= 2; + return code; + } + + public boolean intersects(BigDecimal c) { + return !(a.compareTo(c) > 0 || b.compareTo(c) < 0); + } + + public boolean intersects(Range other) { + + int code = code(); + int ocode = other.code(); + + if (code == 0 || ocode == 0) { + return false; + } + + switch (code) { + case 1: // has a + switch (ocode) { + case 1: // has a + return a.compareTo(other.a) == 0; + case 2: // has b + return a.compareTo(other.b) == 0; + case 3: // has range + return other.intersects(a); + } + break; + case 2: // has b + switch (ocode) { + case 1: // has a + return b.compareTo(other.a) == 0; + case 2: // has b + return b.compareTo(other.b) == 0; + case 3: // has range + return other.intersects(b); + } + break; + case 3: // has range + switch (ocode) { + case 1: // has a + return intersects(other.a); + case 2: // has b + return intersects(other.b); + case 3: // has range + return !(other.b.compareTo(a) < 0 + ||other.a.compareTo(b) > 0); + } + break; + + } + + return false; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/River.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,345 @@ +package de.intevation.flys.model; + +import de.intevation.flys.backend.SessionHolder; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.OrderBy; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.hibernate.Query; +import org.hibernate.Session; + + +@Entity +@Table(name = "rivers") +public class River +implements Serializable +{ + public static final MathContext PRECISION = new MathContext(6); + + public static final double EPSILON = 1e-5; + + public static final Comparator<Double> KM_CMP = new Comparator<Double>() { + @Override + public int compare(Double a, Double b) { + double diff = a - b; + if (diff < -EPSILON) return -1; + if (diff > EPSILON) return +1; + return 0; + } + }; + + private Integer id; + + private Long officialNumber; + + private String name; + + private boolean kmUp; + + private List<Gauge> gauges; + + private List<MeasurementStation> measurementstations; + + private Unit wstUnit; + + @Id + @SequenceGenerator( + name = "SEQUENCE_RIVERS_ID_SEQ", + sequenceName = "RIVERS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_RIVERS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "official_number") + public Long getOfficialNumber() { + return officialNumber; + } + + public void setOfficialNumber(Long officialNumber) { + this.officialNumber = officialNumber; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "km_up") + public boolean getKmUp() { + return kmUp; + } + + public void setKmUp(boolean kmUp) { + this.kmUp = kmUp; + } + + public River() { + } + + public River(String name, Unit wstUnit) { + this.name = name; + this.wstUnit = wstUnit; + } + + @OneToMany + @JoinColumn(name="river_id") + public List<Gauge> getGauges() { + return gauges; + } + + public void setGauges(List<Gauge> gauges) { + this.gauges = gauges; + } + + + @OneToMany + @OrderBy("station") + @JoinColumn(name="river_id") + public List<MeasurementStation> getMeasurementStations() { + return measurementstations; + } + + public void setMeasurementStations(List<MeasurementStation> mstations) { + this.measurementstations = mstations; + } + + @OneToOne + @JoinColumn(name = "wst_unit_id" ) + public Unit getWstUnit() { + return wstUnit; + } + + public void setWstUnit(Unit wstUnit) { + this.wstUnit = wstUnit; + } + + + + @Override + public String toString() { + return name != null ? name : ""; + } + + + /** + * This method returns the gauges that intersect with <i>a</i> and + * <i>b</i>, + * + * @param a A start point. + * @param b An end point. + * + * @return the intersecting gauges. + */ + public List<Gauge> determineGauges(double a, double b) { + Session session = SessionHolder.HOLDER.get(); + + if (a > b) { double t = a; a = b; b = t; } + + Query query = session.createQuery( + "from Gauge where river=:river " + + "and not (range.a > :b or range.b < :a) order by a"); + query.setParameter("river", this); + query.setParameter("a", new BigDecimal(a, PRECISION)); + query.setParameter("b", new BigDecimal(b, PRECISION)); + + return query.list(); + } + + public Gauge maxOverlap(double a, double b) { + List<Gauge> gauges = determineGauges(a, b); + if (gauges == null) { + return null; + } + + if (a > b) { double t = a; a = b; b = t; } + + double max = -Double.MAX_VALUE; + + Gauge result = null; + + for (Gauge gauge: gauges) { + Range r = gauge.getRange(); + double c = r.getA().doubleValue(); + double d = r.getB().doubleValue(); + + double start = c >= a ? c : a; + double stop = d <= b ? d : b; + + double length = stop - start; + + if (length > max) { + max = length; + result = gauge; + } + } + + return result; + } + + public Gauge determineGaugeByName(String name) { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from Gauge where river=:river and name=:name"); + query.setParameter("river", this); + query.setParameter("name", name); + List<Gauge> gauges = query.list(); + return gauges.isEmpty() ? null : gauges.get(0); + } + + public Gauge determineGaugeByPosition(double p) { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from Gauge g where river=:river " + + "and :p between g.range.a and g.range.b"); + query.setParameter("river", this); + query.setParameter("p", new BigDecimal(p, PRECISION)); + List<Gauge> gauges = query.list(); + return gauges.isEmpty() ? null : gauges.get(0); + } + + public Gauge determineGaugeByStation(double a, double b) { + + if (a > b) { double t = a; a = b; b = t; } + + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from Gauge where river.id=:river " + + "and station between :a and :b"); + query.setParameter("river", getId()); + query.setParameter("a", new BigDecimal(a)); + query.setParameter("b", new BigDecimal(b)); + + List<Gauge> gauges = query.list(); + return gauges.isEmpty() ? null : gauges.get(0); + } + + public double[] determineMinMaxQ() { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "select min(wqr.q) as min, max(wqr.q) as max " + + "from Wst as w " + + "join w.columns as wc " + + "join wc.columnQRanges as wcqr " + + "join wcqr.wstQRange as wqr " + + "where w.kind = 0 and river_id = :river"); + + query.setParameter("river", getId()); + + double minmax[] = new double[] { Double.MAX_VALUE, Double.MIN_VALUE }; + + List<Object> results = query.list(); + + if (!results.isEmpty()) { + Object[] arr = (Object[]) results.get(0); + BigDecimal minq = (BigDecimal)arr[0]; + BigDecimal maxq = (BigDecimal)arr[1]; + minmax[0] = minq.doubleValue(); + minmax[1] = maxq.doubleValue(); + } + + return minmax; + } + + + /** + * This method returns the first gauge that is intersected by <i>a</i> and + * <i>b</i>, + * + * @param a A start point. + * @param b An end point. + * + * @return the first intersecting gauge. + */ + public Gauge determineGauge(double a, double b) { + List<Gauge> gauges = determineGauges(a, b); + + int idx = a < b ? 0 : gauges.size() - 1; + + return gauges.isEmpty() ? null : gauges.get(idx); + } + + /** + * Returns the min and max distance of this river. The first position in the + * resulting array contains the min distance, the second position the max + * distance. + * + * @return the min and max distance of this river. + */ + public double[] determineMinMaxDistance() { + List<Gauge> gauges = getGauges(); + + if (gauges == null || gauges.isEmpty()) { + return null; + } + + double minmax[] = new double[] { Double.MAX_VALUE, Double.MIN_VALUE }; + + for (Gauge g: gauges) { + Range r = g.getRange(); + + if (r == null) { + continue; + } + + double a = r.getA().doubleValue(); + minmax[0] = minmax[0] < a ? minmax[0] : a; + + BigDecimal bigB = r.getB(); + if (bigB != null) { + double b = bigB.doubleValue(); + minmax[1] = minmax[1] > b ? minmax[1] : b; + } + } + + return minmax; + } + + public Map<Double, Double> queryGaugeDatumsKMs() { + List<Gauge> gauges = getGauges(); + Map result = new TreeMap<Double, Double>(KM_CMP); + + for (Gauge gauge: gauges) { + BigDecimal km = gauge.getStation(); + BigDecimal datum = gauge.getDatum(); + if (km != null && datum != null) { + result.put(km.doubleValue(), datum.doubleValue()); + } + } + + return result; + } + +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/RiverAxis.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,146 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.MultiLineString; + +import de.intevation.flys.backend.SessionHolder; +import de.intevation.flys.model.AxisKind; + + +/** + * A river has one axis that is used for calculation. + * Additional axes of a river can be used to be painted int maps etc. + * which one is the main river axis can be determined over the axis kind. + */ +@Entity +@Table(name = "river_axes") +public class RiverAxis +implements Serializable +{ + private Integer id; + private AxisKind kind; + private River river; + private String name; + private MultiLineString geom; + + public static final int KIND_UNKOWN = 0; + public static final int KIND_CURRENT = 1; + public static final int KIND_OTHER = 2; + + public RiverAxis() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + /** + * Get kind. + * + * @return kind as AxisKind. + */ + @OneToOne + @JoinColumn(name = "kind_id") + public AxisKind getKind() { + return kind; + } + + /** + * Set kind. + * + * @param kind the value to set. + */ + public void setKind(AxisKind kind) { + this.kind = kind; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public MultiLineString getGeom() { + return geom; + } + + + public void setGeom(MultiLineString geom) { + this.geom = geom; + } + + + public static List<RiverAxis> getRiverAxis(String river) + throws IllegalArgumentException { + return getRiverAxis(river, KIND_CURRENT); + } + + public static List<RiverAxis> getRiverAxis(String river, String name, int kind) + throws HibernateException { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from RiverAxis as ax where river.name =:river" + + " and kind.id =:kind" + + " and ax.name=:name"); + query.setParameter("river", river); + query.setParameter("kind", kind); + query.setParameter("name", name); + + List<RiverAxis> list = query.list(); + return list.isEmpty() ? null : list; + } + + public static List<RiverAxis> getRiverAxis(String river, int kind) + throws HibernateException { + Session session = SessionHolder.HOLDER.get(); + Query query = session.createQuery( + "from RiverAxis where river.name =:river AND kind.id =:kind"); + query.setParameter("river", river); + query.setParameter("kind", kind); + + List<RiverAxis> list = query.list(); + return list.isEmpty() ? null : list; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/RiverAxisKm.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,104 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.hibernate.Session; +import org.hibernate.Query; +import org.hibernate.annotations.Type; + +import com.vividsolutions.jts.geom.Point; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "river_axes_km") +public class RiverAxisKm +implements Serializable +{ + private Integer id; + private River river; + private BigDecimal km; + private Point geom; + + + public RiverAxisKm() { + } + + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "km") + public BigDecimal getKm() { + return km; + } + + + public void setKm(BigDecimal km) { + this.km = km; + } + + + @Column(name = "geom") + @Type(type = "org.hibernatespatial.GeometryUserType") + public Point getGeom() { + return geom; + } + + + public void setGeom(Point geom) { + this.geom = geom; + } + + + /** + * Returns a list of RiverAxisKm objects for a given river. + * + * @param riverid The ID of a river in the database. + * + * @return a list of RiverAxisKm objects. + */ + public static List<RiverAxisKm> getRiverAxisKms(int riverid) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "from RiverAxisKm where river.id =:riverid"); + query.setParameter("riverid", riverid); + + List<RiverAxisKm> list = query.list(); + + return list; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SQRelation.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,105 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; +import javax.persistence.GenerationType; + + +@Entity +@Table(name = "sq_relation") +public class SQRelation implements Serializable { + + private Integer id; + + private River river; + + private TimeInterval timeInterval; + + private String description; + + private List<SQRelationValue> values; + + + protected SQRelation() { + } + + + public SQRelation(River river, TimeInterval timeInterval, String desc) { + this.river = river; + this.timeInterval = timeInterval; + this.description = desc; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_SQ_ID_SEQ", + sequenceName = "SQ_RELATION_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SQ_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + + @OneToMany + @JoinColumn(name = "sq_relation_id") + public List<SQRelationValue> getValues() { + return values; + } + + public void setValues(List<SQRelationValue> values) { + this.values = values; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SQRelationValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,191 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.JoinColumn; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.OneToOne; +import javax.persistence.GenerationType; + + +@Entity +@Table(name = "sq_relation_value") +public class SQRelationValue implements Serializable { + + private Integer id; + + private SQRelation sqRelation; + + private String parameter; + + private MeasurementStation measurementStation; + + private Double a; + private Double b; + private Double qMax; + private Double rSQ; + private Integer nTot; + private Integer nOutlier; + private Double cFerguson; + private Double cDuan; + + + protected SQRelationValue() { + } + + + public SQRelationValue( + SQRelation sqRelation, + String parameter, + MeasurementStation measurementStation, + Double a, + Double b, + Double qMax, + Double rSQ, + Integer nTot, + Integer nOutlier, + Double cFerguson, + Double cDuan + ) { + this.sqRelation = sqRelation; + this.parameter = parameter; + this.measurementStation = measurementStation; + this.a = a; + this.b = b; + this.qMax = qMax; + this.rSQ = rSQ; + this.nTot = nTot; + this.nOutlier = nOutlier; + this.cFerguson = cFerguson; + this.cDuan = cDuan; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_SQ_VALUE_ID_SEQ", + sequenceName = "SQ_RELATION_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SQ_VALUE_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + @OneToOne + @JoinColumn(name = "sq_relation_id") + public SQRelation getSqRelation() { + return sqRelation; + } + + public void setSqRelation(SQRelation sqRelation) { + this.sqRelation = sqRelation; + } + + + @Column(name = "parameter") + public String getParameter() { + return parameter; + } + + public void setParameter(String parameter) { + this.parameter = parameter; + } + + @OneToOne + @JoinColumn(name = "measurement_station_id") + public MeasurementStation getMeasurementStation() { + return measurementStation; + } + + public void setMeasurementStation(MeasurementStation measurementStation) { + this.measurementStation = measurementStation; + } + + + @Column(name = "a") + public Double getA() { + return a; + } + + public void setA(Double a) { + this.a = a; + } + + + @Column(name = "b") + public Double getB() { + return b; + } + + public void setB(Double b) { + this.b = b; + } + + @Column(name = "qmax") + public Double getQMax() { + return qMax; + } + + public void setQMax(Double qMax) { + this.qMax = qMax; + } + + @Column(name = "rsq") + public Double getRSQ() { + return rSQ; + } + + public void setRSQ(Double rSQ) { + this.rSQ = rSQ; + } + + @Column(name = "ntot") + public Integer getNTot () { + return nTot; + } + + public void setNTot(Integer nTot) { + this.nTot = nTot; + } + + @Column(name = "noutl") + public Integer getNOutlier() { + return nOutlier; + } + + public void setNOutlier(Integer nOutlier) { + this.nOutlier = nOutlier; + } + + @Column(name = "cferguson") + public Double getCFerguson() { + return cFerguson; + } + + public void setCFerguson(Double cFerguson) { + this.cFerguson = cFerguson; + } + + @Column(name = "cduan") + public Double getCDuan() { + return cDuan; + } + + public void setCDuan(Double cDuan) { + this.cDuan = cDuan; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SectieKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,44 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "sectie_kinds") +public class SectieKind implements Serializable { + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return name of the kind of sectie as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SedimentDensity.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,103 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + + +@Entity +@Table(name = "sediment_density") +public class SedimentDensity implements Serializable { + + private Integer id; + + private River river; + + private Depth depth; + + private List<SedimentDensityValue> values; + + private String description; + + + public SedimentDensity() { + } + + + public SedimentDensity(River river, Depth depth, String desc) { + this.river = river; + this.depth = depth; + this.description = desc; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_SEDIMENT_DENSITY_ID_SEQ", + sequenceName = "SEDIMENT_DENSITY_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SEDIMENT_DENSITY_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name = "depth_id") + public Depth getDepth() { + return depth; + } + + public void setDepth(Depth depth) { + this.depth = depth; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @OneToMany + @JoinColumn(name="sediment_density_id") + public List<SedimentDensityValue> getValues() { + return values; + } + + public void setValues(List<SedimentDensityValue> values) { + this.values = values; + } + + public void addValue(SedimentDensityValue value) { + this.values.add(value); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SedimentDensityValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,125 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + + +@Entity +@Table(name = "sediment_density_values") +public class SedimentDensityValue implements Serializable { + + private Integer id; + + private SedimentDensity sedimentDensity; + + private BigDecimal station; + private BigDecimal shoreOffset; + private BigDecimal density; + private BigDecimal year; + + private String description; + + + public SedimentDensityValue() { + } + + + public SedimentDensityValue( + SedimentDensity sedimentDensity, + BigDecimal station, + BigDecimal shoreOffset, + BigDecimal density, + BigDecimal year, + String desc + ) { + this.sedimentDensity = sedimentDensity; + this.station = station; + this.shoreOffset = shoreOffset; + this.density = density; + this.year = year; + this.description = desc; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_SEDIMENT_DENSITY_VALUES_ID_SEQ", + sequenceName = "SEDIMENT_DENSITY_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SEDIMENT_DENSITY_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "sediment_density_id") + public SedimentDensity getSedimentDensity() { + return sedimentDensity; + } + + public void setSedimentDensity(SedimentDensity sedimentDensity) { + this.sedimentDensity = sedimentDensity; + } + + @Column(name = "station") + public BigDecimal getStation() { + return station; + } + + public void setStation(BigDecimal station) { + this.station = station; + } + + @Column(name = "shore_offset") + public BigDecimal getShoreOffset() { + return shoreOffset; + } + + public void setShoreOffset(BigDecimal shoreOffset) { + this.shoreOffset = shoreOffset; + } + + @Column(name = "density") + public BigDecimal getDensity() { + return density; + } + + public void setDensity(BigDecimal density) { + this.density = density; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Column(name = "year") + public BigDecimal getYear() { + return year; + } + + public void setYear(BigDecimal year) { + this.year = year; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SedimentYield.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,145 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + + +@Entity +@Table(name = "sediment_yield") +public class SedimentYield +implements Serializable +{ + private static Logger logger = Logger.getLogger(SedimentYield.class); + + private Integer id; + + private River river; + + private GrainFraction grainFraction; + + private Unit unit; + + private TimeInterval timeInterval; + + private String description; + + private List<SedimentYieldValue> values; + + + public SedimentYield() { + this.values = new ArrayList<SedimentYieldValue>(); + } + + public SedimentYield(River river, Unit unit, TimeInterval timeInterval) { + this(); + + this.river = river; + this.unit = unit; + this.timeInterval = timeInterval; + } + + + public SedimentYield( + River river, + Unit unit, + TimeInterval timeInterval, + GrainFraction grainFraction + ) { + this(river, unit, timeInterval); + + this.grainFraction = grainFraction; + } + + + public SedimentYield( + River river, + Unit unit, + TimeInterval timeInterval, + GrainFraction grainFraction, + String description + ) { + this(river, unit, timeInterval, grainFraction); + + this.description = description; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_SEDIMENT_YIELD_ID_SEQ", + sequenceName = "SEDIMENT_YIELD_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SEDIMENT_YIELD_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id") + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @OneToOne + @JoinColumn(name="grain_fraction_id") + public GrainFraction getGrainFraction() { + return grainFraction; + } + + public void setGrainFraction(GrainFraction grainFraction) { + this.grainFraction = grainFraction; + } + + @OneToOne + @JoinColumn(name = "unit_id") + public Unit getUnit() { + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } + + @OneToOne + @JoinColumn(name = "time_interval_id") + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SedimentYieldValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,93 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +import org.apache.log4j.Logger; + + +@Entity +@Table(name = "sediment_yield_values") +public class SedimentYieldValue +implements Serializable +{ + private static Logger logger = Logger.getLogger(SedimentYieldValue.class); + + private Integer id; + + private SedimentYield sedimentYield; + + private Double station; + private Double value; + + private Unit unit; + + + public SedimentYieldValue() { + } + + public SedimentYieldValue( + SedimentYield sedimentYield, + Double station, + Double value + ) { + this.sedimentYield = sedimentYield; + this.station = station; + this.value = value; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_SEDIMENT_YIELD_VALuES_ID_SEQ", + sequenceName = "SEDIMENT_YIELD_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_SEDIMENT_YIELD_VALuES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "sediment_yield_id" ) + public SedimentYield getSedimentYield() { + return sedimentYield; + } + + public void setSedimentYield(SedimentYield sedimentYield) { + this.sedimentYield = sedimentYield; + } + + @Column(name="station") + public Double getStation() { + return station; + } + + public void setStation(Double station) { + this.station = station; + } + + @Column(name = "value") + public Double getValue() { + return value; + } + + public void setValue(Double value) { + this.value = value; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/SobekKind.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,45 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "sobek_kinds") +public class SobekKind implements Serializable { + + private Integer id; + private String name; + + @Id + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + /** + * Get name. + * + * @return name of the kind of sobek as String. + */ + @Column(name = "name") + public String getName() { + return name; + } + + /** + * Set name. + * + * @param name the value to set. + */ + public void setName(String name) { + this.name = name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/TimeInterval.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,67 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; + +@Entity +@Table(name = "time_intervals") +public class TimeInterval +implements Serializable +{ + private Integer id; + private Date startTime; + private Date stopTime; + + public TimeInterval() { + } + + public TimeInterval(Date startTime, Date stopTime) { + this.startTime = startTime; + this.stopTime = stopTime; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_TIME_INTERVALS_ID_SEQ", + sequenceName = "TIME_INTERVALS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_TIME_INTERVALS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Column(name = "start_time") // FIXME: type mapping needed? + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + @Column(name = "stop_time") // FIXME: type mapping needed? + public Date getStopTime() { + return stopTime; + } + + public void setStopTime(Date stopTime) { + this.stopTime = stopTime; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Unit.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,60 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + + +@Entity +@Table(name = "units") +public class Unit +implements Serializable +{ + protected Integer id; + protected String name; + + + public Unit() { + } + + + public Unit(String name) { + this.name = name; + } + + + @Id + @SequenceGenerator( + name = "SEQUENCE_UNITS_ID_SEQ", + sequenceName = "UNITS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_UNITS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + + @Column(name = "name") + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/Wst.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,215 @@ +package de.intevation.flys.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +import org.apache.log4j.Logger; + +import org.hibernate.Session; +import org.hibernate.SQLQuery; +import org.hibernate.Query; +import org.hibernate.type.StandardBasicTypes; + +import de.intevation.flys.backend.SessionHolder; + + +@Entity +@Table(name = "wsts") +public class Wst +implements Serializable +{ + private static Logger logger = Logger.getLogger(Wst.class); + + private Integer id; + private River river; + private String description; + private Integer kind; + + private List<WstColumn> columns; + + + public static final String SQL_SELECT_MINMAX = + "select min(q) as minQ, max(q) as maxQ from wst_q_values " + + "where wst_id = :wst and not (a > :km or b < :km)"; + + public Wst() { + } + + public Wst(River river, String description) { + this(river, description, 0); + } + + public Wst(River river, String description, Integer kind) { + this.river = river; + this.description = description; + this.kind = kind; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_WSTS_ID_SEQ", + sequenceName = "WSTS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_WSTS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "river_id" ) + public River getRiver() { + return river; + } + + public void setRiver(River river) { + this.river = river; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Column(name = "kind") + public Integer getKind() { + return kind; + } + + public void setKind(Integer kind) { + this.kind = kind; + } + + @OneToMany + @JoinColumn(name="wst_id") + public List<WstColumn> getColumns() { + return columns; + } + + public void setColumns(List<WstColumn> columns) { + this.columns = columns; + } + + + /** + * Determines the min and max Q values of this WST. The min value is placed + * in the first field of the resulting array - the max value is placed in + * the second field. + * + * @return the min and max Q values of this WST. + */ + public double[] determineMinMaxQ() { + double[] ab = river.determineMinMaxDistance(); + return determineMinMaxQ(new Range(ab[0], ab[1], river)); + } + + + /** + * Determines the min and max Q values of this WST in the given range. The + * min value is placed in the first field of the resulting array - the max + * value is placed in the second field. + * + * @param range The range used for querying the Q values. + * + * @return the min and max Q values of this WST. + */ + public double[] determineMinMaxQ(Range range) { + if (range != null) { + return determineMinMaxQ( + range.getA().doubleValue(), + range.getB().doubleValue()); + } + + return null; + } + + + /** + * Determines the min and max Q values of this WST in the given range. The + * min value is placed in the first field of the resulting array - the max + * value is placed in the second field. + * + * @param fromKm the lower km value. + * @param toKm the upper km value. + * + * @return the min and max Q values of this WST. + */ + public double[] determineMinMaxQ(double fromKm, double toKm) { + Session session = SessionHolder.HOLDER.get(); + + Query query = session.createQuery( + "select min(q), max(q) from WstQRange where " + + " id in " + + " (select wstQRange.id from WstColumnQRange where " + + " wstColumn.id in (select id from WstColumn where wst.id = :wst)) " + + " and range.id in " + + " (select id from Range where not (a > :end or b < :start))"); + + query.setParameter("wst", getId()); + query.setParameter("start", new BigDecimal(fromKm)); + query.setParameter("end", new BigDecimal(toKm)); + + List<Object []> results = query.list(); + + if (results.isEmpty()) { + return null; + } + + Object [] result = results.get(0); + + return new double [] { + ((BigDecimal)result[0]).doubleValue(), + ((BigDecimal)result[1]).doubleValue() }; + } + + + public double[] determineMinMaxQFree(double km) { + Session session = SessionHolder.HOLDER.get(); + + SQLQuery sqlQuery = session.createSQLQuery(SQL_SELECT_MINMAX) + .addScalar("minQ", StandardBasicTypes.DOUBLE) + .addScalar("maxQ", StandardBasicTypes.DOUBLE); + + sqlQuery.setInteger("wst", getId()); + sqlQuery.setDouble("km", km); + + List<Object[]> minmaxQ = sqlQuery.list(); + + + if (minmaxQ.isEmpty()) { + return null; + } + + Object[] mm = minmaxQ.get(0); + + if (mm[0] == null || mm[1] == null) { + logger.warn ("No min/max Q for km " + km + " found."); + return null; + } + + return new double[] { (Double) mm[0], (Double) mm[1] }; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/WstColumn.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,134 @@ +package de.intevation.flys.model; + +import java.util.List; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.OneToMany; + +@Entity +@Table(name = "wst_columns") +public class WstColumn +implements Serializable +{ + private Integer id; + private Wst wst; + private String name; + private String description; + private Integer position; + private TimeInterval timeInterval; + + private List<WstColumnQRange> columnQRanges; + private List<WstColumnValue> columnValues; + + public WstColumn() { + } + + public WstColumn( + Wst wst, + String name, + String description, + Integer position, + TimeInterval timeInterval + ) { + this.wst = wst; + this.name = name; + this.description = description; + this.position = position; + this.timeInterval = timeInterval; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_WST_COLUMNS_ID_SEQ", + sequenceName = "WST_COLUMNS_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_WST_COLUMNS_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "wst_id" ) + public Wst getWst() { + return wst; + } + + public void setWst(Wst wst) { + this.wst = wst; + } + + @Column(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Column(name = "position") + public Integer getPosition() { + return position; + } + + public void setPosition(Integer position) { + this.position = position; + } + + @OneToOne + @JoinColumn(name = "time_interval_id" ) + public TimeInterval getTimeInterval() { + return timeInterval; + } + + public void setTimeInterval(TimeInterval timeInterval) { + this.timeInterval = timeInterval; + } + + @OneToMany + @JoinColumn(name="wst_column_id") + public List<WstColumnQRange> getColumnQRanges() { + return columnQRanges; + } + + public void setColumnQRanges(List<WstColumnQRange> columnQRanges) { + this.columnQRanges = columnQRanges; + } + + @OneToMany + @JoinColumn(name="wst_column_id") + public List<WstColumnValue> getColumnValues() { + return columnValues; + } + + public void setColumnValues(List<WstColumnValue> columnValues) { + this.columnValues = columnValues; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/WstColumnQRange.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,73 @@ +package de.intevation.flys.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "wst_column_q_ranges") +public class WstColumnQRange +implements Serializable +{ + private Integer id; + private WstColumn wstColumn; + private WstQRange wstQRange; + + public WstColumnQRange() { + } + + public WstColumnQRange( + WstColumn wstColumn, + WstQRange wstQRange + ) { + this.wstColumn = wstColumn; + this.wstQRange = wstQRange; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_WST_Q_RANGES_ID_SEQ", + sequenceName = "WST_Q_RANGES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_WST_Q_RANGES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "wst_column_id" ) + public WstColumn getWstColumn() { + return wstColumn; + } + + public void setWstColumn(WstColumn wstColumn) { + this.wstColumn = wstColumn; + } + + @OneToOne + @JoinColumn(name = "wst_q_range_id" ) + public WstQRange getWstQRange() { + return wstQRange; + } + + public void setWstQRange(WstQRange wstQRange) { + this.wstQRange = wstQRange; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 : +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/WstColumnValue.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,85 @@ +package de.intevation.flys.model; + +import java.math.BigDecimal; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "wst_column_values") +public class WstColumnValue +implements Serializable +{ + private Integer id; + private WstColumn wstColumn; + private BigDecimal position; + private BigDecimal w; + + public WstColumnValue() { + } + + public WstColumnValue( + WstColumn wstColumn, + BigDecimal position, + BigDecimal w + ) { + this.wstColumn = wstColumn; + this.position = position; + this.w = w; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_WST_COLUMN_VALUES_ID_SEQ", + sequenceName = "WST_COLUMN_VALUES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_WST_COLUMN_VALUES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "wst_column_id") + public WstColumn getWstColumn() { + return wstColumn; + } + + public void setWstColumn(WstColumn wstColumn) { + this.wstColumn = wstColumn; + } + + @Column(name = "position") // FIXME: type mapping needed? + public BigDecimal getPosition() { + return position; + } + + public void setPosition(BigDecimal position) { + this.position = position; + } + + @Column(name = "w") // FIXME: type mapping needed? + public BigDecimal getW() { + return w; + } + + public void setW(BigDecimal w) { + this.w = w; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/model/WstQRange.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,70 @@ +package de.intevation.flys.model; + +import java.math.BigDecimal; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +import javax.persistence.Column; +import javax.persistence.SequenceGenerator; +import javax.persistence.GenerationType; +import javax.persistence.OneToOne; +import javax.persistence.JoinColumn; + +@Entity +@Table(name = "wst_q_ranges") +public class WstQRange +implements Serializable +{ + private Integer id; + private Range range; + private BigDecimal q; + + public WstQRange() { + } + + public WstQRange(Range range, BigDecimal q) { + this.range = range; + this.q = q; + } + + @Id + @SequenceGenerator( + name = "SEQUENCE_WST_Q_RANGES_ID_SEQ", + sequenceName = "WST_Q_RANGES_ID_SEQ", + allocationSize = 1) + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "SEQUENCE_WST_Q_RANGES_ID_SEQ") + @Column(name = "id") + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @OneToOne + @JoinColumn(name = "range_id" ) + public Range getRange() { + return range; + } + + public void setRange(Range range) { + this.range = range; + } + + @Column(name = "q") // FIXME: type mapping needed?! + public BigDecimal getQ() { + return q; + } + + public void setQ(BigDecimal q) { + this.q = q; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/utils/DBCPConnectionProvider.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,253 @@ +/* + * Copyright 2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.intevation.flys.utils; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Map; +import java.util.Collections; +import java.util.StringTokenizer; + +import org.apache.commons.dbcp.BasicDataSource; +import org.apache.commons.dbcp.BasicDataSourceFactory; + +import org.apache.log4j.Logger; + +import org.hibernate.HibernateException; + +import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.connection.ConnectionProvider; + +import org.hibernate.cfg.Environment; + +/** + * <p>A connection provider that uses an Apache commons DBCP connection pool.</p> + * + * <p>To use this connection provider set:<br> + * <code>hibernate.connection.provider_class org.hibernate.connection.DBCPConnectionProvider</code></p> + * + * <pre>Supported Hibernate properties: + * hibernate.connection.driver_class + * hibernate.connection.url + * hibernate.connection.username + * hibernate.connection.password + * hibernate.connection.isolation + * hibernate.connection.autocommit + * hibernate.connection.pool_size + * hibernate.connection (JDBC driver properties)</pre> + * <br> + * All DBCP properties are also supported by using the hibernate.dbcp prefix. + * A complete list can be found on the DBCP configuration page: + * <a href="http://jakarta.apache.org/commons/dbcp/configuration.html">http://jakarta.apache.org/commons/dbcp/configuration.html</a>. + * <br> + * <pre>Example: + * hibernate.connection.provider_class org.hibernate.connection.DBCPConnectionProvider + * hibernate.connection.driver_class org.hsqldb.jdbcDriver + * hibernate.connection.username sa + * hibernate.connection.password + * hibernate.connection.url jdbc:hsqldb:test + * hibernate.connection.pool_size 20 + * hibernate.dbcp.initialSize 10 + * hibernate.dbcp.maxWait 3000 + * hibernate.dbcp.validationQuery select 1 from dual</pre> + * + * <p>More information about configuring/using DBCP can be found on the + * <a href="http://jakarta.apache.org/commons/dbcp/">DBCP website</a>. + * There you will also find the DBCP wiki, mailing lists, issue tracking + * and other support facilities</p> + * + * @see org.hibernate.connection.ConnectionProvider + * @author Dirk Verbeeck + */ +public class DBCPConnectionProvider +implements ConnectionProvider +{ + private static Logger log = Logger.getLogger(DBCPConnectionProvider.class); + + private static final String PREFIX = "hibernate.dbcp."; + + private BasicDataSource ds; + + // Old Environment property for backward-compatibility + // (property removed in Hibernate3) + private static final String DBCP_PS_MAXACTIVE = + "hibernate.dbcp.ps.maxActive"; + + // Property doesn't exists in Hibernate2 + private static final String AUTOCOMMIT = + "hibernate.connection.autocommit"; + + public void configure(Properties props) throws HibernateException { + try { + log.debug("Configure DBCPConnectionProvider"); + + // DBCP properties used to create the BasicDataSource + Properties dbcpProperties = new Properties(); + + // DriverClass & url + String jdbcDriverClass = props.getProperty(Environment.DRIVER); + String jdbcUrl = props.getProperty(Environment.URL); + dbcpProperties.put("driverClassName", jdbcDriverClass); + dbcpProperties.put("url", jdbcUrl); + + // Username / password + String username = props.getProperty(Environment.USER); + String password = props.getProperty(Environment.PASS); + dbcpProperties.put("username", username); + dbcpProperties.put("password", password); + + // Isolation level + String isolationLevel = props.getProperty(Environment.ISOLATION); + if (isolationLevel != null + && (isolationLevel = isolationLevel.trim()).length() > 0) { + dbcpProperties.put("defaultTransactionIsolation", isolationLevel); + } + + // Turn off autocommit (unless autocommit property is set) + String autocommit = props.getProperty(AUTOCOMMIT); + if (autocommit != null + && (autocommit = autocommit.trim()).length() > 0) { + dbcpProperties.put("defaultAutoCommit", autocommit); + } else { + dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE)); + } + + // Pool size + String poolSize = props.getProperty(Environment.POOL_SIZE); + if (poolSize != null + && (poolSize = poolSize.trim()).length() > 0 + && Integer.parseInt(poolSize) > 0) { + dbcpProperties.put("maxActive", poolSize); + } + + // Copy all "driver" properties into "connectionProperties" + Properties driverProps = + ConnectionProviderFactory.getConnectionProperties(props); + + if (driverProps.size() > 0) { + StringBuilder connectionProperties = new StringBuilder(); + for (Iterator iter = driverProps.entrySet().iterator(); + iter.hasNext(); + ) { + Map.Entry entry = (Map.Entry)iter.next(); + String key = (String)entry.getKey(); + String value = (String)entry.getValue(); + connectionProperties + .append(key) + .append('=') + .append(value); + if (iter.hasNext()) { + connectionProperties.append(';'); + } + } + dbcpProperties.put( + "connectionProperties", connectionProperties.toString()); + } + + // Copy all DBCP properties removing the prefix + for (Iterator iter = props.entrySet().iterator() ; iter.hasNext() ;) { + Map.Entry entry = (Map.Entry)iter.next(); + String key = (String)entry.getKey(); + if (key.startsWith(PREFIX)) { + String property = key.substring(PREFIX.length()); + String value = (String)entry.getValue(); + dbcpProperties.put(property, value); + } + } + + // Backward-compatibility + if (props.getProperty(DBCP_PS_MAXACTIVE) != null) { + dbcpProperties.put( + "poolPreparedStatements", + String.valueOf(Boolean.TRUE)); + dbcpProperties.put( + "maxOpenPreparedStatements", + props.getProperty(DBCP_PS_MAXACTIVE)); + } + + // Some debug info + /* // commented out, because it leaks the password + if (log.isDebugEnabled()) { + log.debug("Creating a DBCP BasicDataSource" + + " with the following DBCP factory properties:"); + StringWriter sw = new StringWriter(); + dbcpProperties.list(new PrintWriter(sw, true)); + log.debug(sw.toString()); + } + */ + + // Let the factory create the pool + ds = (BasicDataSource)BasicDataSourceFactory + .createDataSource(dbcpProperties); + + // This needs to be done manually as it is somehow ignored + // by the BasicDataSourceFactory if you set it as a dbcpProperty + String connectionInitSqls = props.getProperty("connectionInitSqls"); + if (connectionInitSqls != null) { + StringTokenizer tokenizer = new StringTokenizer(connectionInitSqls, ";"); + ds.setConnectionInitSqls(Collections.list(tokenizer)); + } + // The BasicDataSource has lazy initialization + // borrowing a connection will start the DataSource + // and make sure it is configured correctly. + + // Connection conn = ds.getConnection(); + // conn.close(); + } + catch (Exception e) { + String message = "Could not create a DBCP pool"; + log.fatal(message, e); + if (ds != null) { + BasicDataSource x = ds; ds = null; + try { + x.close(); + } + catch (SQLException sqle) { + } + } + throw new HibernateException(message, e); + } + log.debug("Configure DBCPConnectionProvider complete"); + } + + public Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + public void closeConnection(Connection conn) throws SQLException { + conn.close(); + } + + public void close() throws HibernateException { + try { + if (ds != null) { + BasicDataSource x = ds; ds = null; + x.close(); + } + } + catch (SQLException sqle) { + throw new HibernateException("Could not close DBCP pool", sqle); + } + } + + public boolean supportsAggressiveRelease() { + return false; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/utils/DateGuesser.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,258 @@ +package de.intevation.flys.utils; + +/** + * Copyright (c) 2006 by Intevation GmbH + * + * @author Sascha L. Teichmann (teichmann@intevation.de) + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL coming with FLYS for details. + */ + +import java.util.Date; +import java.util.Calendar; + +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +public final class DateGuesser { + public static final String [] MONTH = { + "jan", "feb", "mrz", "apr", "mai", "jun", + "jul", "aug", "sep", "okt", "nov", "dez" + }; + + public static final int guessMonth(String s) { + s = s.toLowerCase(); + for (int i = 0; i < MONTH.length; ++i) + if (MONTH[i].equals(s)) { + return i; + } + return -1; + } + + public static final Pattern YYYY_MM_DD = + Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})$"); + + public static final Pattern DD_MM_YYYY = + Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})$"); + + public static final Pattern MMM_YYYY = + Pattern.compile("^(\\d{0,2})\\.?(\\w{3})\\.?(\\d{2,4})$"); + + public static final Pattern GARBAGE_YYYY = + Pattern.compile("^\\D*(\\d{2,4})$"); + + public static final Pattern YYYY_MM_DDThh_mm = + Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})$"); + + public static final Pattern YYYY_MM_DDThh_mm_ss = + Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$"); + + public static final Pattern DD_MM_YYYYThh_mm = + Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})T(\\d{1,2}):(\\d{2})$"); + + public static final Pattern DD_MM_YYYYThh_mm_ss = + Pattern.compile("^(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})T(\\d{1,2}):(\\d{2}):(\\d{2})$"); + + public static final Pattern DDMMYY = + Pattern.compile("^(\\d{1,2})(\\d{1,2})(\\d{1,2})$"); + + private DateGuesser() { + } + + public static final int calendarMonth(String month) { + return calendarMonth(Integer.parseInt(month)); + } + + public static final int calendarMonth(int month) { + return Math.max(Math.min(month-1, 11), 0); + } + + /** + * Guess date by trying all different patterns. + * Throws IllegalArgumentException if not able to guess. + * @param s The date to be guessed (e.g. 11.02.2001). + * @return the parsed Date. + */ + public static Date guessDate(String s) { + if (s == null || (s = s.trim()).length() == 0) { + throw new IllegalArgumentException(); + } + + Matcher m; + + m = YYYY_MM_DD.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(1); + String month = m.group(2); + String day = m.group(3); + cal.set( + Integer.parseInt(year), + calendarMonth(month), + Integer.parseInt(day), + 12, 0, 0); + return cal.getTime(); + } + + m = DD_MM_YYYY.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(3); + String month = m.group(2); + String day = m.group(1); + cal.set( + Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), + calendarMonth(month), + Integer.parseInt(m.group(1)), + 12, 0, 0); + return cal.getTime(); + } + + m = MMM_YYYY.matcher(s); + + if (m.matches()) { + int month = guessMonth(m.group(2)); + if (month >= 0) { + Calendar cal = Calendar.getInstance(); + String year = m.group(3); + String day = m.group(1); + cal.set( + Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), + month, + day.length() == 0 ? 15 : Integer.parseInt(day), + 12, 0, 0); + return cal.getTime(); + } + } + + m = YYYY_MM_DDThh_mm.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(1); + String month = m.group(2); + String day = m.group(3); + String hour = m.group(4); + String minute = m.group(5); + cal.set( + Integer.parseInt(year), + calendarMonth(month), + Integer.parseInt(day), + Integer.parseInt(hour), + Integer.parseInt(minute), + 0 + ); + return cal.getTime(); + } + + m = YYYY_MM_DDThh_mm_ss.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(1); + String month = m.group(2); + String day = m.group(3); + String hour = m.group(4); + String minute = m.group(5); + String second = m.group(6); + cal.set( + Integer.parseInt(year), + calendarMonth(month), + Integer.parseInt(day), + Integer.parseInt(hour), + Integer.parseInt(minute), + Integer.parseInt(second) + ); + return cal.getTime(); + } + + m = DD_MM_YYYYThh_mm.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(3); + String month = m.group(2); + String day = m.group(1); + String hour = m.group(4); + String minute = m.group(5); + cal.set( + Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), + calendarMonth(month), + Integer.parseInt(day), + Integer.parseInt(hour), + Integer.parseInt(minute), + 0 + ); + return cal.getTime(); + } + + m = DD_MM_YYYYThh_mm_ss.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(3); + String month = m.group(2); + String day = m.group(1); + String hour = m.group(4); + String minute = m.group(5); + String second = m.group(6); + cal.set( + Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), + calendarMonth(month), + Integer.parseInt(day), + Integer.parseInt(hour), + Integer.parseInt(minute), + Integer.parseInt(second) + ); + return cal.getTime(); + } + + m = DDMMYY.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String day = m.group(1); + String month = m.group(2); + String yearS = m.group(3); + int year = Integer.parseInt(yearS); + + if (year <= cal.get(Calendar.YEAR) % 100) { + year += 2000; + } + else { + year += 1900; + } + cal.set( + year, + Integer.parseInt(month), // month + Integer.parseInt(day), // day + 12, 0, 0); + return cal.getTime(); + } + + m = GARBAGE_YYYY.matcher(s); + + if (m.matches()) { + Calendar cal = Calendar.getInstance(); + String year = m.group(1); + cal.set( + Integer.parseInt(year) + (year.length() == 2 ? 1900 : 0), + 5, // month + 15, // day + 12, 0, 0); + return cal.getTime(); + } + + throw new IllegalArgumentException(); + } + + public static void main(String [] args) { + for (int i = 0; i < args.length; ++i) { + System.out.println(args[i] + ": " + guessDate(args[i])); + } + } +} +// end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/utils/EpsilonComparator.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,27 @@ +package de.intevation.flys.utils; + +import java.util.Comparator; + +/** Comparator with some tolerance (epsilon). */ +public class EpsilonComparator implements Comparator<Double> +{ + public static final double EPSILON = 1e-4; + + /** Ready-made comparator with 1e-4 tolerance. */ + public static final EpsilonComparator CMP = new EpsilonComparator(EPSILON); + + private double epsilon; + + public EpsilonComparator(double epsilon) { + this.epsilon = epsilon; + } + + @Override + public int compare(Double a, Double b) { + double diff = a - b; + if (diff < -epsilon) return -1; + if (diff > epsilon) return +1; + return 0; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/main/java/org/dive4elements/river/utils/StringUtil.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,829 @@ +package de.intevation.flys.utils; + +/** + * Copyright (c) 2006 by Intevation GmbH + * + * @author Sascha L. Teichmann (teichmann@intevation.de) + * @author Ludwig Reiter (ludwig@intevation.de) + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL coming with FLYS for details. + */ +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Locale; + +import java.net.URLEncoder; +import java.net.URLDecoder; + +import java.io.UnsupportedEncodingException; +import java.io.IOException; +import java.io.BufferedReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.PrintWriter; + + +public final class StringUtil { + final static String NUMBER_SEPERATOR = ";"; + final static String LINE_SEPERATOR = ":"; + + private StringUtil() { + } + + public static final String double2DArrayToString(double[][] values) { + + if (values == null) { + throw new IllegalArgumentException("keine double[][]-Werte"); + } + + StringBuilder strbuf = new StringBuilder(); + + for (int i=0; i < values.length; i++) { + if (i>0) { + strbuf.append(LINE_SEPERATOR); + } + for (int j=0; j < values[i].length; j++) { + if (j > 0) { + strbuf.append(NUMBER_SEPERATOR); + } + strbuf.append(values[i][j]); + } + } + + return strbuf.toString(); + } + + public static final double[][] stringToDouble2DArray(String str) { + if (str == null || str.length() == 0) { + return null; + } + + String[] lineSplit = str.split(LINE_SEPERATOR); + double[][] array2D = new double[lineSplit.length][]; + for (int i=0; i < lineSplit.length; i++) { + String[] numberSplit = lineSplit[i].split(NUMBER_SEPERATOR); + + double[] numbers = new double[numberSplit.length]; + for (int j=0; j < numberSplit.length; j++) { + numbers[j] = Double.valueOf(numberSplit[j]).doubleValue(); + } + + array2D[i] = numbers; + } + + return array2D; + } + + /** + * Remove first occurrence of "[" and "]" (if both do occur). + * @param value String to be stripped of [] (might be null). + * @return input string but with [ and ] removed, or input string if no + * brackets were found. + */ + public static final String unbracket(String value) { + // null- guard + if (value == null) return value; + + int start = value.indexOf("["); + int end = value.indexOf("]"); + + if (start < 0 || end < 0) { + return value; + } + + value = value.substring(start + 1, end); + + return value; + } + + + /** + * From "Q=1" make "W(Q=1)". + * @return original string wraped in "W()" if it contains a "Q", original + * string otherwise. + */ + public static String wWrap(String wOrQ) { + return (wOrQ != null && wOrQ.indexOf("Q") >=0) + ? "W(" + wOrQ + ")" + : wOrQ; + } + + + public static final String [] splitLines(String s) { + if (s == null) { + return null; + } + ArrayList<String> list = new ArrayList<String>(); + + BufferedReader in = null; + + try { + in = + new BufferedReader( + new StringReader(s)); + + String line; + + while ((line = in.readLine()) != null) { + list.add(line); + } + } + catch (IOException ioe) { + return null; + } + finally { + if (in != null) + try { + in.close(); + } + catch (IOException ioe) {} + } + + return list.toArray(new String[list.size()]); + } + + public static final String concat(String [] s) { + return concat(s, null); + } + + public static final String concat(String [] s, String glue) { + if (s == null) { + return null; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length; ++i) { + if (i > 0 && glue != null) { + sb.append(glue); + } + sb.append(s[i]); + } + return sb.toString(); + } + + public static final String [] splitAfter(String [] src, int N) { + if (src == null) { + return null; + } + + ArrayList<String> list = new ArrayList<String>(src.length); + for (int i = 0; i < src.length; ++i) { + String s = src[i]; + int R; + if (s == null || (R = s.length()) == 0) { + list.add(s); + } + else { + while (R > N) { + list.add(s.substring(0, N)); + s = s.substring(N); + R = s.length(); + } + list.add(s); + } + } + return list.toArray(new String[list.size()]); + } + + public static final String [] splitQuoted(String s) { + return splitQuoted(s, '"'); + } + + public static final String[] fitArray(String [] src, String [] dst) { + if (src == null) { + return dst; + } + if (dst == null) { + return src; + } + + if (src.length == dst.length) { + return src; + } + + System.arraycopy(src, 0, dst, 0, Math.min(dst.length, src.length)); + + return dst; + } + + public static final String [] splitQuoted(String s, char quoteChar) { + if (s == null) { + return null; + } + ArrayList<String> l = new ArrayList<String>(); + int mode = 0, last_mode = 0; + StringBuilder sb = new StringBuilder(); + for (int N = s.length(), i = 0; i < N; ++i) { + char c = s.charAt(i); + switch (mode) { + case 0: // unquoted mode + if (c == quoteChar) { + mode = 1; // to quoted mode + if (sb.length() > 0) { + l.add(sb.toString()); + sb.setLength(0); + } + } + else if (c == '\\') { + last_mode = 0; + mode = 2; // escape mode + } + else if (!Character.isWhitespace(c)) { + sb.append(c); + } + else if (sb.length() > 0) { + l.add(sb.toString()); + sb.setLength(0); + } + break; + case 1: // quote mode + if (c == '\\') { + last_mode = 1; + mode = 2; // escape mode + } + else if (c == quoteChar) { // leave quote mode + l.add(sb.toString()); + sb.setLength(0); + mode = 0; // to unquoted mode + } + else { + sb.append(c); + } + break; + case 2: // escape mode + sb.append(c); + mode = last_mode; + break; + } + } + if (sb.length() > 0) { + l.add(sb.toString()); + } + return l.toArray(new String[l.size()]); + } + + public static final String [] splitUnique(String s) { + return splitUnique(s, "[\\s,]+"); + } + + public static final String [] splitUnique(String s, String sep) { + return s != null ? unique(s.split(sep)) : null; + } + + public static final String [] unique(String [] str) { + if (str == null || str.length == 1) { + return str; + } + + Arrays.sort(str); + + for (int i = 1; i < str.length; ++i) + if (str[i].equals(str[i-1])) { + ArrayList<String> list = new ArrayList<String>(str.length); + + for (int j = 0; j < i; ++j) { + list.add(str[j]); + } + + String last = str[i]; + + for (++i; i < str.length; ++i) + if (!last.equals(str[i])) { + list.add(last = str[i]); + } + + return list.toArray(new String[list.size()]); + } + + return str; + } + + public static final String [] ensureEmptyExistence(String [] str) { + if (str == null) { + return null; + } + + for (int i = 0; i < str.length; ++i) + if (str[i].length() == 0) { + if (i != 0) { // copy to front + String t = str[0]; + str[0] = str[i]; + str[i] = t; + } + return str; + } + + String [] n = new String[str.length+1]; + n[0] = ""; + System.arraycopy(str, 0, n, 1, str.length); + return n; + } + + public static final String ensureWidthPadLeft(String s, int width, char pad) { + int N = s.length(); + if (N >= width) { + return s; + } + StringBuilder sb = new StringBuilder(width); + for (; N < width; ++N) { + sb.append(pad); + } + sb.append(s); + return sb.toString(); + } + + public static final String [] splitWhiteSpaceWithNAsPad( + String s, + int N, + String pad + ) { + if (s == null) { + return null; + } + + boolean copyChars = true; + int count = 0; // number of WS + + int S = s.length(); + + ArrayList<String> parts = new ArrayList<String>(); + + StringBuilder part = new StringBuilder(S); + + for (int i = 0; i < S; ++i) { + char c = s.charAt(i); + if (copyChars) { // char mode + if (Character.isWhitespace(c)) { + if (part.length() > 0) { + parts.add(part.toString()); + part.setLength(0); + } + count = 1; + copyChars = false; // to WS mode + } + else { + part.append(c); + } + } + else { // counting WS + if (Character.isWhitespace(c)) { + ++count; + } + else { + while (count >= N) {// enough to insert pad? + parts.add(pad); + count -= N; + } + part.append(c); + count = 0; + copyChars = true; // back to char mode + } + } + } // for all chars + + if (copyChars) { + if (part.length() > 0) { + parts.add(part.toString()); + } + } + else { + while (count >= N) { // enough to insert pad? + parts.add(pad); + count -= N; + } + } + + return parts.toArray(new String[parts.size()]); + } + + public static final String encodeURL(String url) { + try { + return url != null + ? URLEncoder.encode(url, "UTF-8") + : ""; + } + catch (UnsupportedEncodingException usee) { + throw new RuntimeException(usee.getLocalizedMessage()); + } + } + + public static final String decodeURL(String url) { + try { + return url != null + ? URLDecoder.decode(url, "UTF-8") + : ""; + } + catch (UnsupportedEncodingException usee) { + throw new RuntimeException(usee.getLocalizedMessage()); + } + } + + public static final boolean isEmpty(String s) { + return s == null || s.length() == 0; + } + + public static final String empty(String s) { + return s == null ? "" : s; + } + + + public static final String trim(String s) { + return s != null ? s.trim() : null; + } + + public static final String uniqueWhitespaces(String s) { + if (s == null) { + return null; + } + + boolean wasWS = false; + StringBuilder sb = new StringBuilder(); + + for (int N = s.length(), i = 0; i < N; ++i) { + char c = s.charAt(i); + if (Character.isWhitespace(c)) { + if (!wasWS) { + sb.append(c); + wasWS = true; + } + } + else { + sb.append(c); + wasWS = false; + } + } + + return sb.toString(); + } + + public static final String replaceNewlines(String s) { + return s == null + ? null + : s.replace('\r', ' ').replace('\n', ' '); + } + + /* + public static final String quoteReplacement(String s) { + + if (s == null || (s.indexOf('\\') == -1 && s.indexOf('$') == -1)) + return s; + + StringBuilder sb = new StringBuilder(); + + for (int N = s.length(), i = 0; i < N; ++i) { + char c = s.charAt(i); + if (c == '\\' || c == '$') sb.append('\\'); + sb.append(c); + } + + return sb.toString(); + } + */ + + public static final String quoteReplacement(String s) { + + if (s == null) { + return null; + } + + for (int N = s.length(), i = 0; i < N; ++i) { // plain check loop + char c = s.charAt(i); + if (c == '$' || c == '\\') { // first special -> StringBuilder + StringBuilder sb = new StringBuilder(s.substring(0, i)) + .append('\\') + .append(c); + for (++i; i < N; ++i) { // build StringBuilder with rest + if ((c = s.charAt(i)) == '$' || c == '\\') { + sb.append('\\'); + } + sb.append(c); + } + return sb.toString(); + } + } + + return s; + } + + public static final String repeat(String what, int times) { + return repeat(what, times, new StringBuilder()).toString(); + } + + public static final StringBuilder repeat(String what, int times, StringBuilder sb) { + while (times-- > 0) { + sb.append(what); + } + return sb; + } + + /** + * Returns the file name without extension. + */ + public static final String cutExtension(String s) { + if (s == null) { + return null; + } + int dot = s.lastIndexOf('.'); + return dot >= 0 + ? s.substring(0, dot) + : s; + } + + public static final String extension(String s) { + if (s == null) { + return null; + } + int dot = s.lastIndexOf('.'); + return dot >= 0 + ? s.substring(dot+1) + : s; + } + + public static final String [] splitExtension(String x) { + if (x == null) { + return null; + } + int i = x.lastIndexOf('.'); + return i < 0 + ? new String[] { x, null } + : new String[] { x.substring(0, Math.max(0, i)), x.substring(i+1).toLowerCase() }; + } + + public static String entityEncode(String s) { + if (s == null || s.length() == 0) { + return s; + } + + StringBuilder sb = new StringBuilder(); + for (int i=0, N =s.length(); i < N; i++) { + char c = s.charAt(i); + switch (c) { + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '&': + sb.append("&"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + + public static String entityDecode(String s) { + if (s == null || s.length() == 0) { + return s; + } + + boolean amp = false; + StringBuilder sb = new StringBuilder(); + StringBuilder ampbuf = new StringBuilder(); + for (int i=0, N =s.length(); i < N; i++) { + char c = s.charAt(i); + if (amp) { + if (c == ';') { + amp = false; + String str = ampbuf.toString(); + ampbuf.setLength(0); + if (str.equals("lt")) { + sb.append('<'); + } + else if (str.equals("gt")) { + sb.append('>'); + } + else if (str.equals("amp")) { + sb.append('&'); + } + else { + sb.append('&').append(str).append(';'); + } + } + else { + ampbuf.append(c); + } + } + else if (c=='&') { + amp = true; + } + else { + sb.append(c); + } + + } + return sb.toString(); + } + + public static final String quote(String s) { + return quote(s, '"'); + } + + public static final String quote(String s, char quoteChar) { + if (s == null) { + return null; + } + + int N = s.length(); + + if (N == 0) + return new StringBuilder(2) + .append(quoteChar) + .append(quoteChar) + .toString(); + + StringBuilder sb = null; + + int i = 0; + + for (; i < N; ++i) { + char c = s.charAt(i); + + if (Character.isWhitespace(c)) { + sb = new StringBuilder() + .append(quoteChar) + .append(s.substring(0, i+1)); + break; + } + else if (c == quoteChar) { + sb = new StringBuilder() + .append(quoteChar) + .append(s.substring(0, i)) + .append('\\') + .append(quoteChar); + break; + } + } + + if (sb == null) { + return s; + } + + for (++i; i < N; ++i) { + char c = s.charAt(i); + if (c == quoteChar || c == '\\') { + sb.append('\\'); + } + + sb.append(c); + } + + return sb.append(quoteChar).toString(); + } + + /* + public static String sprintf(String format, Object... args) { + return sprintf(null, format, args); + } + */ + + public static String sprintf(Locale locale, String format, Object ... args) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.printf(locale, format, args); + pw.flush(); + return sw.toString(); + } + + + public static void testQuote() { + System.err.println("testing quote:"); + + String cases [] = { + "", "''", + "test", "test", + "test test", "'test test'", + " test", "' test'", + "test ", "'test '", + " test ", "' test '", + "'test", "'\\'test'", + "'", "'\\''", + " ' ' ", "' \\' \\' '", + "te'st", "'te\\'st'" + }; + + int failed = 0; + + for (int i = 0; i < cases.length; i += 2) { + String in = cases[i]; + String out = cases[i+1]; + + String res = quote(in, '\''); + if (!res.equals(out)) { + ++failed; + System.err.println( + "quote failed on: >" + in + + "< result: >" + res + + "< expected: >" + out + "<"); + } + } + + int T = cases.length/2; + + System.err.println("tests total: " + T); + System.err.println("tests failed: " + failed); + System.err.println("tests passed: " + (T - failed)); + } + + public static void testQuoteReplacement() { + System.err.println("testing quoteReplacement:"); + + String cases [] = { + "", "", + "test", "test", + "$", "\\$", + "\\", "\\\\", + "\\$", "\\\\\\$", + "test\\$", "test\\\\\\$", + "\\test", "\\\\test", + "test$", "test\\$", + "test$test", "test\\$test", + "$test$", "\\$test\\$" + }; + + int failed = 0; + + for (int i = 0; i < cases.length; i += 2) { + String in = cases[i]; + String out = cases[i+1]; + + String res = quoteReplacement(in); + if (!res.equals(out)) { + ++failed; + System.err.println( + "quoteReplacement failed on: '" + in + + "' result: '" + res + + "' expected: '" + out + "'"); + } + } + + int T = cases.length/2; + + System.err.println("tests total: " + T); + System.err.println("tests failed: " + failed); + System.err.println("tests passed: " + (T - failed)); + } + + public static void testStringArray2D() { + int total = 0; + int fail = 0; + int passed = 0; + + System.err.println("testing StringArray2D:"); + + double[][] testarray = {{1.0, 2.0, 3.0}, + {1.1, 2.1, 3.1}, + {100.2, 200.2} + }; + String str = double2DArrayToString(testarray); + + total += 1; + if (str.equals("1.0;2.0;3.0:1.1;2.1;3.1:100.2;200.2")) { + passed +=1; + } + else { + fail +=1; + System.err.println("Der Ergebnis-String ist nicht richtig:"); + System.err.println(str); + } + + + + double[][] testarray2 = stringToDouble2DArray(str); + boolean failed = false; + + total +=1; + for (int i=0; i < testarray.length; i++) + for (int j=0; j < testarray[i].length; j++) + if (testarray[i][j] != testarray2[i][j]) { + System.err.println("Test scheitert bei i=" +i +" j=" +j); + System.err.println("alter Wert=" + testarray[i][j] +" neuer Wert=" +testarray2[i][j]); + failed = true; + } + if (failed) { + fail +=1; + } + else { + passed +=1; + } + System.err.println("tests total: "+ total); + System.err.println("tests failed: "+ fail); + System.err.println("tests passed: "+ passed); + } + + public static void main(String [] args) { + + testQuoteReplacement(); + testQuote(); + testStringArray2D(); + } + + /** Check for occurence of needle in hay, converting both to lowercase + * to be ignorant of cases. */ + public static boolean containsIgnoreCase(String hay, String needle) { + return hay.toLowerCase().contains(needle.toLowerCase()); + } +} +// end of file
--- a/flys-backend/src/test/java/de/intevation/flys/AppTest.java Thu Apr 25 11:48:36 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,38 +0,0 @@ -package de.intevation.flys; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/flys-backend/src/test/java/org/dive4elements/river/AppTest.java Thu Apr 25 11:53:11 2013 +0200 @@ -0,0 +1,38 @@ +package de.intevation.flys; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +}