Browse Source

Restoring Jetty plugin for local testing
Adding Jersey 2.x for REST services, updating REST services for VGI
Adding services getAllSensors, getAllPhenomenons

Michal Kepka 4 năm trước cách đây
mục cha
commit
37488fcbf1

+ 128 - 36
pom.xml

@@ -39,6 +39,14 @@
                     <doUpdate>false</doUpdate>
                 </configuration>
             </plugin>
+        
+<!-- HACK for testing -->
+    <plugin>
+        <groupId>org.mortbay.jetty</groupId>
+        <artifactId>maven-jetty-plugin</artifactId>
+        <version>6.1.22</version>
+    </plugin>
+<!-- HACK for testing -->
 
             <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
@@ -59,6 +67,9 @@
                 <artifactId>maven-war-plugin</artifactId>
                 <version>2.0.2</version>
                 <configuration>
+<!-- HACK for testing -->
+        <skipTests>true</skipTests>
+<!-- HACK for testing -->
                     <archive>
                         <manifest>
                             <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
@@ -116,7 +127,46 @@
     </build>
 
     <dependencies>
-
+<!-- Tests -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.5</version>
+            <scope>test</scope>
+        </dependency>
+    
+<!-- JETTY -->
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jetty</artifactId>
+            <version>${jetty.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jetty-servlet-tester</artifactId>
+            <version>${jetty.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jetty-util</artifactId>
+            <version>${jetty.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jetty-management</artifactId>
+            <version>${jetty.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jsp-2.1-jetty</artifactId>
+            <version>${jetty.version}</version>
+            <scope>provided</scope>
+        </dependency>
+<!-- JETTY -->    
         <!-- Provided dependencies -->
         <dependency>
             <groupId>net.sf.jasperreports</groupId>
@@ -133,32 +183,88 @@
         </dependency>
 
         <dependency>
-            <groupId>com.sun.jersey.contribs</groupId>
-            <artifactId>jersey-multipart</artifactId>
-            <version>1.19.4</version>
-            <scope>provided</scope>
-        </dependency>
-
-        <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-core</artifactId>
-            <version>2.11.1</version>
+            <version>2.9.7</version>
+            <!-- <version>2.11.1</version> -->
             <scope>provided</scope>
         </dependency>
 
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-annotations</artifactId>
-            <version>2.11.1</version>
+            <!-- <version>2.11.1</version>-->
+            <version>2.9.7</version>
             <scope>provided</scope>
         </dependency>
 
+<!-- JERSEY -->
+<!-- 
+    <dependency>
+        <groupId>com.sun.jersey</groupId>
+        <artifactId>jersey-server</artifactId>
+        <version>1.19.4</version>
+    </dependency>
+    <dependency>
+        <groupId>com.sun.jersey</groupId>
+        <artifactId>jersey-core</artifactId>
+        <version>1.19.4</version>
+    </dependency>
+    <dependency>
+        <groupId>com.sun.jersey</groupId>
+        <artifactId>jersey-servlet</artifactId>
+        <version>1.19.4</version>
+    </dependency>
+    <dependency>
+        <groupId>com.sun.jersey</groupId>
+        <artifactId>jersey-json</artifactId>
+        <version>1.19.4</version>
+    </dependency>
+ -->
+    <dependency>
+        <groupId>org.glassfish.jersey.containers</groupId>
+        <artifactId>jersey-container-servlet</artifactId>
+        <version>${jersey2.version}</version>
+    </dependency>
+    <dependency>
+        <groupId>org.glassfish.jersey.core</groupId>
+        <artifactId>jersey-client</artifactId>
+        <version>${jersey2.version}</version>
+    </dependency>
+    <dependency>
+        <groupId>org.glassfish.jersey.media</groupId>
+        <artifactId>jersey-media-json-jackson</artifactId>
+        <version>${jersey2.version}</version>
+    </dependency>
+    
+<!--
+    <dependency>
+        <groupId>org.glassfish.jersey.inject</groupId>
+        <artifactId>jersey-hk2</artifactId>
+        <version>${jersey2.version}</version>
+    </dependency>
+-->
         <dependency>
-            <groupId>org.glassfish.jersey.core</groupId>
-            <artifactId>jersey-server</artifactId>
-            <version>2.31</version>
-            <scope>provided</scope>
+            <groupId>org.glassfish.jersey.media</groupId>
+            <artifactId>jersey-media-multipart</artifactId>
+            <version>${jersey2.version}</version>
         </dependency>
+<!-- 
+        <dependency>
+            <groupId>com.sun.jersey.contribs</groupId>
+            <artifactId>jersey-multipart</artifactId>
+            <version>1.19.4</version>
+        </dependency>
+-->
+<!-- JERSEY -->
+    <!-- https://mvnrepository.com/artifact/org.jvnet.mimepull/mimepull -->
+    <dependency>
+        <groupId>org.jvnet.mimepull</groupId>
+        <artifactId>mimepull</artifactId>
+        <version>1.9.3</version>
+    </dependency>
+    
+
 
         <dependency>
             <groupId>commons-io</groupId>
@@ -172,15 +278,14 @@
             <version>2.4</version>
             <classifier>jdk15</classifier>
         </dependency>
+
         <dependency>
             <groupId>commons-collections</groupId>
             <artifactId>commons-collections</artifactId>
             <version>3.2.2</version>
         </dependency>
 
-
-
-        <dependency>
+    <dependency>
             <groupId>org.jfree</groupId>
             <artifactId>jfreechart</artifactId>
             <version>1.5.0</version>
@@ -191,28 +296,15 @@
             <artifactId>postgresql</artifactId>
             <version>42.2.14</version>
         </dependency>
-
-        <!-- Tests -->
-        <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <version>4.5</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.mortbay.jetty</groupId>
-            <artifactId>jetty-util</artifactId>
-            <version>7.0.0.pre5</version>
-            <scope>test</scope>
-        </dependency>
-
+    
     </dependencies>
 
     <properties>
-        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-        <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding>
-        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+       <jetty.version>6.1.22</jetty.version>
+       <jersey2.version>2.23</jersey2.version>
+       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+       <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding>
+       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
     </properties>
 
     <reporting>

+ 193 - 190
src/main/java/cz/hsrs/db/model/Phenomenon.java

@@ -1,191 +1,194 @@
-package cz.hsrs.db.model;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-// default package
-// Generated 3.6.2008 8:21:13 by Hibernate Tools 3.2.2.GA
-
-import cz.hsrs.db.DBObject;
-import cz.hsrs.db.util.SensorUtil;
-
-/**
- * Phenomenon generated by hbm2java
- */
-public class Phenomenon implements DBObject{
-
-    @Override
-    public DBObject getDBObject(ResultSet set) throws SQLException {
-        return new Phenomenon(set);
-    }
-
-    private String phenomenonId;
-    private String phenomenonName;
-    private String unit;
-
-    /**
-     * Constructor for creating object from ResultSet
-     * @param set
-     * @throws SQLException
-     */
-    public Phenomenon(ResultSet set) throws SQLException{
-        this.phenomenonId = set.getString("phenomenon_id");
-        this.phenomenonName = set.getString("phenomenon_name");
-        this.unit = set.getString("unit");
-    }
-
-    /**
-     * Constructor creates object from ID and UoM
-     * @param phenomenonId
-     * @param unit
-     * @param valuetype
-     */
-    public Phenomenon(String phenomenonId, String unit, String valuetype) {
-        this.phenomenonId = phenomenonId;
-        this.unit = unit;
-    }
-
-    /**
-     * Constructor creates object with all attributes
-     * @param phenomenonId
-     * @param phenomenonName
-     * @param unit
-     * @param valuetype
-     */
-    public Phenomenon(String phenomenonId, String phenomenonName, String unit, String valuetype) {
-        this.phenomenonId = phenomenonId;
-        this.phenomenonName = phenomenonName;
-        this.unit = unit;
-    }
-    
-    /**
-     * Constructor creates object without ID 
-     * @param phenomenonName
-     * @param unit
-     */
-    public Phenomenon(String phenomenonName, String unit) {
-        this.phenomenonName = phenomenonName;
-        this.unit = unit;
-    }
-    
-    /**
-     * Constructor for creating Phenomenon object that is already in DB
-     * @param phenomenonId
-     */
-    public Phenomenon(String phenomenonId) {
-        this.phenomenonId = phenomenonId;
-    }
-    
-    public String internalGetPhenomenonId() {
-        return this.phenomenonId;
-    }
-    
-    public String getPhenomenonId() {
-        return this.phenomenonId;
-    }
-    
-    public void internalSetPhenomenonId(String id){
-        this.phenomenonId = id;
-    }
-
-    public String getPhenomenonName() {
-        return this.phenomenonName;
-    }
-
-    public String getUnit() {
-        return this.unit;
-    }
-    
-    @Override
-    public String toString() {
-        return "[phenomenonId=" + phenomenonId + ", phenomenonName="
-                + phenomenonName + ", unit=" + unit + "]";
-    }
-
-    /**
-     * Method to insert new Phenomenon to DB
-     * @return instance of new Phenomenon with generated ID or Phenomenon that is already in DB
-     * @throws SQLException if an error occurs during inserting
-     * @throws NoItemFoundException 
-     */
-    public Phenomenon insertToDb() throws SQLException, NoItemFoundException {
-        SensorUtil sUtil = new SensorUtil();
-        if(this.phenomenonId != null){
-            Phenomenon phenDB = sUtil.getPhenomenonById(phenomenonId);
-            if(this.phenomenonName == null && this.unit == null){
-                if(phenDB == null){
-                    throw new NoItemFoundException("Phenomenon with given ID="+this.phenomenonId+" was not found!");
-                }
-                else {
-                    return phenDB;
-                }
-            } else if(this.phenomenonName != null && this.unit != null){
-                if(phenDB == null){
-                    // insert new
-                    int i = sUtil.insertNewPhenomenon(this);
-                    if (i == 1 || i == 0){
-                        return this;
-                    }
-                    else{
-                        throw new SQLException("Phenomenon was not inserted!");
-                    }
-                } else {
-                    if(phenDB.equals(this)){
-                        return this;
-                    } 
-                    else if(phenDB.getPhenomenonName().equalsIgnoreCase(phenomenonName)==true 
-                            && phenDB.getUnit().equalsIgnoreCase(unit) == false){
-                        // insert new
-                        int i = sUtil.insertNewPhenomenon(this);
-                        if (i == 1 || i == 0){
-                            return this;
-                        }
-                        else{
-                            throw new SQLException("Phenomenon was not inserted!");
-                        }
-                    }
-                    else{
-                        throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
-                    }
-                }
-            }
-            else{
-                throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
-            }
-        }
-        else{
-            if(this.phenomenonName != null && this.unit != null){
-                Phenomenon phenDB = sUtil.getPhenomenonByName(phenomenonName);
-                if(phenDB == null){
-                    // get new ID + insert new
-                    this.phenomenonId = sUtil.getNextPhenomenonId();
-                    int i = sUtil.insertNewPhenomenon(this);
-                    if (i == 1 || i == 0){
-                        return this;
-                    }
-                    else{
-                        throw new SQLException("Phenomenon was not inserted!");
-                    }
-                }
-                else{
-                    if(phenDB.getUnit().equalsIgnoreCase(unit)){
-                        return phenDB;
-                    }
-                    else{
-                        // get new ID + insert new
-                        this.phenomenonId = sUtil.getNextPhenomenonId();
-                        int i = sUtil.insertNewPhenomenon(this);
-                        if (i == 1 || i == 0){
-                            return this;
-                        }
-                        else{
-                            throw new SQLException("Phenomenon was not inserted!");
-                        }
-                    }
-                }
-            }
-            else{
-                throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
-            }
-        }
-    }
+package cz.hsrs.db.model;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+// default package
+// Generated 3.6.2008 8:21:13 by Hibernate Tools 3.2.2.GA
+
+import cz.hsrs.db.DBObject;
+import cz.hsrs.db.util.SensorUtil;
+
+/**
+ * Phenomenon generated by hbm2java
+ */
+public class Phenomenon implements DBObject{
+
+    @Override
+    public DBObject getDBObject(ResultSet set) throws SQLException {
+        return new Phenomenon(set);
+    }
+
+    private String phenomenonId;
+    private String phenomenonName;
+    private String unit;
+
+    public Phenomenon() {
+    }
+    
+    /**
+     * Constructor for creating object from ResultSet
+     * @param set
+     * @throws SQLException
+     */
+    public Phenomenon(ResultSet set) throws SQLException{
+        this.phenomenonId = set.getString("phenomenon_id");
+        this.phenomenonName = set.getString("phenomenon_name");
+        this.unit = set.getString("unit");
+    }
+
+    /**
+     * Constructor creates object from ID and UoM
+     * @param phenomenonId
+     * @param unit
+     * @param valuetype
+     */
+    public Phenomenon(String phenomenonId, String unit, String valuetype) {
+        this.phenomenonId = phenomenonId;
+        this.unit = unit;
+    }
+
+    /**
+     * Constructor creates object with all attributes
+     * @param phenomenonId
+     * @param phenomenonName
+     * @param unit
+     * @param valuetype
+     */
+    public Phenomenon(String phenomenonId, String phenomenonName, String unit, String valuetype) {
+        this.phenomenonId = phenomenonId;
+        this.phenomenonName = phenomenonName;
+        this.unit = unit;
+    }
+    
+    /**
+     * Constructor creates object without ID 
+     * @param phenomenonName
+     * @param unit
+     */
+    public Phenomenon(String phenomenonName, String unit) {
+        this.phenomenonName = phenomenonName;
+        this.unit = unit;
+    }
+    
+    /**
+     * Constructor for creating Phenomenon object that is already in DB
+     * @param phenomenonId
+     */
+    public Phenomenon(String phenomenonId) {
+        this.phenomenonId = phenomenonId;
+    }
+    
+    public String internalGetPhenomenonId() {
+        return this.phenomenonId;
+    }
+    
+    public String getPhenomenonId() {
+        return this.phenomenonId;
+    }
+    
+    public void internalSetPhenomenonId(String id){
+        this.phenomenonId = id;
+    }
+
+    public String getPhenomenonName() {
+        return this.phenomenonName;
+    }
+
+    public String getUnit() {
+        return this.unit;
+    }
+    
+    @Override
+    public String toString() {
+        return "[phenomenonId=" + phenomenonId + ", phenomenonName="
+                + phenomenonName + ", unit=" + unit + "]";
+    }
+
+    /**
+     * Method to insert new Phenomenon to DB
+     * @return instance of new Phenomenon with generated ID or Phenomenon that is already in DB
+     * @throws SQLException if an error occurs during inserting
+     * @throws NoItemFoundException 
+     */
+    public Phenomenon insertToDb() throws SQLException, NoItemFoundException {
+        SensorUtil sUtil = new SensorUtil();
+        if(this.phenomenonId != null){
+            Phenomenon phenDB = sUtil.getPhenomenonById(phenomenonId);
+            if(this.phenomenonName == null && this.unit == null){
+                if(phenDB == null){
+                    throw new NoItemFoundException("Phenomenon with given ID="+this.phenomenonId+" was not found!");
+                }
+                else {
+                    return phenDB;
+                }
+            } else if(this.phenomenonName != null && this.unit != null){
+                if(phenDB == null){
+                    // insert new
+                    int i = sUtil.insertNewPhenomenon(this);
+                    if (i == 1 || i == 0){
+                        return this;
+                    }
+                    else{
+                        throw new SQLException("Phenomenon was not inserted!");
+                    }
+                } else {
+                    if(phenDB.equals(this)){
+                        return this;
+                    } 
+                    else if(phenDB.getPhenomenonName().equalsIgnoreCase(phenomenonName)==true 
+                            && phenDB.getUnit().equalsIgnoreCase(unit) == false){
+                        // insert new
+                        int i = sUtil.insertNewPhenomenon(this);
+                        if (i == 1 || i == 0){
+                            return this;
+                        }
+                        else{
+                            throw new SQLException("Phenomenon was not inserted!");
+                        }
+                    }
+                    else{
+                        throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
+                    }
+                }
+            }
+            else{
+                throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
+            }
+        }
+        else{
+            if(this.phenomenonName != null && this.unit != null){
+                Phenomenon phenDB = sUtil.getPhenomenonByName(phenomenonName);
+                if(phenDB == null){
+                    // get new ID + insert new
+                    this.phenomenonId = sUtil.getNextPhenomenonId();
+                    int i = sUtil.insertNewPhenomenon(this);
+                    if (i == 1 || i == 0){
+                        return this;
+                    }
+                    else{
+                        throw new SQLException("Phenomenon was not inserted!");
+                    }
+                }
+                else{
+                    if(phenDB.getUnit().equalsIgnoreCase(unit)){
+                        return phenDB;
+                    }
+                    else{
+                        // get new ID + insert new
+                        this.phenomenonId = sUtil.getNextPhenomenonId();
+                        int i = sUtil.insertNewPhenomenon(this);
+                        if (i == 1 || i == 0){
+                            return this;
+                        }
+                        else{
+                            throw new SQLException("Phenomenon was not inserted!");
+                        }
+                    }
+                }
+            }
+            else{
+                throw new SQLException("It is not possible to insert Phenomenon with given attributes!");
+            }
+        }
+    }
 }

+ 65 - 65
src/main/java/cz/hsrs/db/model/Unit.java

@@ -1,65 +1,65 @@
-package cz.hsrs.db.model;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import cz.hsrs.db.DBObject;
-
-public class Unit implements DBObject{
-	private long unitId;
-	private int holderId;
-	private String description;	
-	
-	public Unit(long unitId, int userId, String description) {
-		super();
-		this.unitId = unitId;
-		this.holderId = userId;
-		this.description = description;
-	}
-	
-	public Unit(long unitId, String description) {
-		super();
-		this.unitId = unitId;		
-		this.description = description;
-	}
-	
-	public Unit(){
-		
-	}
-	
-	public Unit(ResultSet set) throws SQLException {
-		this.unitId = set.getLong("unit_id");
-		this.description = set.getString("description");
-		this.holderId = set.getInt("holder_id");
-	}
-
-	public long getUnitId() {
-		return unitId;
-	}
-	public void setUnitId(long unitId) {
-		this.unitId = unitId;
-	}
-	public int getHolderId() {
-		return holderId;
-	}
-	public void setHolderId(int userId) {
-		this.holderId = userId;
-	}
-	public String getDescription() {
-		return description;
-	}
-	public void setDescription(String description) {
-		this.description = description;
-	}
-
-	@Override
-	public DBObject getDBObject(ResultSet set) throws SQLException {
-		// TODO Auto-generated method stub
-		return new Unit(set);
-	}
-
-
-	
-	
-
-}
+package cz.hsrs.db.model;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import cz.hsrs.db.DBObject;
+
+/**
+ * Class represents unit object from DB
+ * @author mkepka
+ *
+ */
+public class Unit implements DBObject{
+	private long unitId;
+	private int holderId;
+	private String description;	
+	
+	public Unit(long unitId, int userId, String description) {
+		super();
+		this.unitId = unitId;
+		this.holderId = userId;
+		this.description = description;
+	}
+	
+	public Unit(long unitId, String description) {
+		super();
+		this.unitId = unitId;
+		this.description = description;
+	}
+	
+	public Unit(){
+		
+	}
+	
+	public Unit(ResultSet set) throws SQLException {
+		this.unitId = set.getLong("unit_id");
+		this.description = set.getString("description");
+		this.holderId = set.getInt("holder_id");
+	}
+
+	public long getUnitId() {
+		return unitId;
+	}
+	public void setUnitId(long unitId) {
+		this.unitId = unitId;
+	}
+	public int getHolderId() {
+		return holderId;
+	}
+	public void setHolderId(int userId) {
+		this.holderId = userId;
+	}
+	public String getDescription() {
+		return description;
+	}
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	@Override
+	public DBObject getDBObject(ResultSet set) throws SQLException {
+		// TODO Auto-generated method stub
+		return new Unit(set);
+	}
+}

+ 109 - 104
src/main/java/cz/hsrs/db/model/composite/RealUnit.java

@@ -1,104 +1,109 @@
-package cz.hsrs.db.model.composite;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import cz.hsrs.db.DBObject;
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.model.Unit;
-import cz.hsrs.db.model.UnitDriver;
-import cz.hsrs.db.model.UnitHolder;
-import cz.hsrs.db.model.UnitPosition;
-import cz.hsrs.db.model.custom.DBItemInfo;
-import cz.hsrs.db.util.UtilFactory;
-
-public class RealUnit implements DBObject{
-
-	private final Unit unit;
-	private final UnitPosition position ;
-	private final LastPosition lastpos;
-	private final List<UnitSensor> sensors;
-	private final UnitHolder holder;
-	private final List<UnitDriver> drivers;
-	
-	private final List<DBItemInfo> generalInfo;
-	
-	public RealUnit(){
-		unit = null;
-		sensors = null;
-		position = null;
-		holder = null;
-		lastpos = null;
-		generalInfo = null;
-		drivers = null;
-	}
-	
-	public RealUnit(ResultSet set) throws SQLException {
-		generalInfo = new ArrayList<DBItemInfo>();
-		
-		position = new UnitPosition(set);
-		UtilFactory fact = null;		
-		try {
-			fact = new UtilFactory();
-		} catch (Exception e) {
-			// TODO Auto-generated catch block
-			//e.printStackTrace();
-		} 		
-		sensors = fact.sensorUtil.getUnitsSensors(position.getUnit_id());	
-		lastpos = fact.unitUtil.getLastPositionWithStatus(position);
-		UnitHolder h = null;
-		try {
-			h = fact.unitUtil.getUnitHolder(position.getUnit_id());
-		} catch (NoItemFoundException e) {
-			// TODO Auto-generated catch block
-			//e.printStackTrace();
-		}
-		holder = h;
-		
-		 try {
-			DBItemInfo info = new DBItemInfo("custom", "cars", position.getUnit_id(), "unit_id");
-			 generalInfo.add(info);
-		} catch (NoItemFoundException e) {
-			//ignore - leave infos empty
-		}
-		
-		drivers = fact.unitUtil.getUnitDrivers(position.getUnit_id());
-		unit = fact.unitUtil.getUnit(position.getUnit_id());
-	}
-
-
-	public LastPosition getLastpos() {
-		return lastpos;
-	}
-
-	private UnitPosition getPosition() {
-		return position;
-	}
-
-	public List<UnitSensor> getSensors() {
-		return sensors;
-	}
-
-	public UnitHolder getHolder() {
-		return holder;
-	}
-
-	public List<DBItemInfo> getGeneralInfo() {
-		return generalInfo;
-	}
-	@Override	
-	public DBObject getDBObject(ResultSet set) throws SQLException {
-		// TODO Auto-generated method stub
-		return new RealUnit(set);
-	}
-
-	public List<UnitDriver> getDrivers() {
-		return drivers;
-	}
-
-	public Unit getUnit(){
-		return unit;
-	}
-}
+package cz.hsrs.db.model.composite;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import cz.hsrs.db.DBObject;
+import cz.hsrs.db.model.NoItemFoundException;
+import cz.hsrs.db.model.Unit;
+import cz.hsrs.db.model.UnitDriver;
+import cz.hsrs.db.model.UnitHolder;
+import cz.hsrs.db.model.UnitPosition;
+import cz.hsrs.db.model.custom.DBItemInfo;
+import cz.hsrs.db.util.UtilFactory;
+
+/**
+ * Class represents real unit
+ * @author mkepka
+ *
+ */
+public class RealUnit implements DBObject{
+
+    private final Unit unit;
+    private final UnitPosition position ;
+    private final LastPosition lastpos;
+    private final List<UnitSensor> sensors;
+    private final UnitHolder holder;
+    private final List<UnitDriver> drivers;
+    
+    private final List<DBItemInfo> generalInfo;
+    
+    public RealUnit(){
+        unit = null;
+        sensors = null;
+        position = null;
+        holder = null;
+        lastpos = null;
+        generalInfo = null;
+        drivers = null;
+    }
+    
+    public RealUnit(ResultSet set) throws SQLException {
+        generalInfo = new ArrayList<DBItemInfo>();
+        
+        position = new UnitPosition(set);
+        UtilFactory fact = null;
+        try {
+            fact = new UtilFactory();
+        } catch (Exception e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        sensors = fact.sensorUtil.getUnitsSensors(position.getUnit_id());
+        lastpos = fact.unitUtil.getLastPositionWithStatus(position);
+        UnitHolder h = null;
+        try {
+            h = fact.unitUtil.getUnitHolder(position.getUnit_id());
+        } catch (NoItemFoundException e) {
+            // TODO Auto-generated catch block
+            //e.printStackTrace();
+        }
+        holder = h;
+        
+         try {
+            DBItemInfo info = new DBItemInfo("custom", "cars", position.getUnit_id(), "unit_id");
+             generalInfo.add(info);
+        } catch (NoItemFoundException e) {
+            //ignore - leave infos empty
+        }
+        
+        drivers = fact.unitUtil.getUnitDrivers(position.getUnit_id());
+        unit = fact.unitUtil.getUnit(position.getUnit_id());
+    }
+
+
+    public LastPosition getLastpos() {
+        return lastpos;
+    }
+
+    private UnitPosition getPosition() {
+        return position;
+    }
+
+    public List<UnitSensor> getSensors() {
+        return sensors;
+    }
+
+    public UnitHolder getHolder() {
+        return holder;
+    }
+
+    public List<DBItemInfo> getGeneralInfo() {
+        return generalInfo;
+    }
+    @Override    
+    public DBObject getDBObject(ResultSet set) throws SQLException {
+        // TODO Auto-generated method stub
+        return new RealUnit(set);
+    }
+
+    public List<UnitDriver> getDrivers() {
+        return drivers;
+    }
+
+    public Unit getUnit(){
+        return unit;
+    }
+}

+ 122 - 122
src/main/java/cz/hsrs/db/model/composite/UnitSensor.java

@@ -1,122 +1,122 @@
-package cz.hsrs.db.model.composite;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import cz.hsrs.db.DBObject;
-import cz.hsrs.db.model.Phenomenon;
-import cz.hsrs.db.pool.SQLExecutor;
-import cz.hsrs.db.util.SensorUtil;
-
-/**
- * Sensor generated by hbm2java
- */
-public class UnitSensor implements DBObject{
-
-	private long sensorId;
-	private String sensorName;
-	private String sensorType;
-	private Phenomenon phenomenon;
-	
-	private String firstObservationTime;
-	private String lastObservationTime;
-	
-	
-	public UnitSensor(long sensorId, String sensorName, String sensorType,
-			Phenomenon phenomenon, long unitId) throws SQLException {
-		super();
-		this.sensorId = sensorId;
-		this.sensorName = sensorName;
-		this.sensorType = sensorType;
-		this.phenomenon = phenomenon;
-		this.firstObservationTime = findFirstObservationTimeDB(unitId, sensorId);
-		this.lastObservationTime = findLastObservationTimeDB(unitId, sensorId);
-	}
-	
-	public UnitSensor(ResultSet set) throws SQLException{
-		
-		this.sensorId = set.getLong("sensor_id");
-		this.sensorName = set.getString("sensor_name");
-		this.sensorType = set.getString("sensor_type");	
-		this.firstObservationTime = findFirstObservationTimeDB(set.getLong("unit_id"),sensorId);		
-		this.lastObservationTime = findLastObservationTimeDB(set.getLong("unit_id"),sensorId);
-		SensorUtil sUtil = new SensorUtil();		
-		this.phenomenon = sUtil.getPhenomenonById(set.getString("phenomenon_id"));		
-	}
-	
-	public UnitSensor() throws SQLException{
-		
-	}	
-	
-	@Override
-	public DBObject getDBObject(ResultSet set) throws SQLException {	
-		return new UnitSensor(set);
-	}
-
-	public long getSensorId() {
-		return sensorId;
-	}
-	public void setSensorId(long sensorId) {
-		this.sensorId = sensorId;
-	}
-	public String getSensorName() {
-		return sensorName;
-	}
-	public void setSensorName(String sensorName) {
-		this.sensorName = sensorName;
-	}
-	public String getSensorType() {
-		return sensorType;
-	}
-	public void setSensorType(String sensorType) {
-		this.sensorType = sensorType;
-	}
-	public Phenomenon getPhenomenon() {
-		return phenomenon;
-	}
-	public void setPhenomenon(Phenomenon phenomenon) {
-		this.phenomenon = phenomenon;
-	}
-	public String getFirstObservationTime() {
-		return firstObservationTime;
-	}
-	public String getLastObservationTime() {
-		return lastObservationTime;
-	}
-
-	private String findFirstObservationTimeDB(long unitId, long sensorId) throws SQLException{
-		String query = "SELECT first_obs FROM units_to_sensors WHERE unit_id = "+unitId+" AND sensor_id = "+sensorId+";";
-		ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-		if(res.next() == true){
-			String time = res.getString(1);
-			boolean wasNull = res.wasNull();
-			if (wasNull == false){
-				return time;
-			}
-			else{
-				return "unknown";
-			}
-		}
-		else{
-			return "unknown";
-		}		
-	}
-	
-	private String findLastObservationTimeDB(long unitId, long sensorId) throws SQLException{
-		String query = "SELECT last_obs FROM units_to_sensors WHERE unit_id = "+unitId+" AND sensor_id = "+sensorId+";";
-		ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-		if(res.next() == true){
-			String time = res.getString(1);
-			boolean wasNull = res.wasNull();
-			if (wasNull == false){
-				return time;
-			}
-			else{
-				return "unknown";
-			}
-		}
-		else{
-			return "unknown";
-		}			
-	}	
-}
+package cz.hsrs.db.model.composite;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import cz.hsrs.db.DBObject;
+import cz.hsrs.db.model.Phenomenon;
+import cz.hsrs.db.pool.SQLExecutor;
+import cz.hsrs.db.util.SensorUtil;
+
+/**
+ * Sensor generated by hbm2java
+ */
+public class UnitSensor implements DBObject{
+
+	private long sensorId;
+	private String sensorName;
+	private String sensorType;
+	private Phenomenon phenomenon;
+	
+	private String firstObservationTime;
+	private String lastObservationTime;
+	
+	
+	public UnitSensor(long sensorId, String sensorName, String sensorType,
+			Phenomenon phenomenon, long unitId) throws SQLException {
+		super();
+		this.sensorId = sensorId;
+		this.sensorName = sensorName;
+		this.sensorType = sensorType;
+		this.phenomenon = phenomenon;
+		this.firstObservationTime = findFirstObservationTimeDB(unitId, sensorId);
+		this.lastObservationTime = findLastObservationTimeDB(unitId, sensorId);
+	}
+	
+	public UnitSensor(ResultSet set) throws SQLException{
+		
+		this.sensorId = set.getLong("sensor_id");
+		this.sensorName = set.getString("sensor_name");
+		this.sensorType = set.getString("sensor_type");	
+		this.firstObservationTime = findFirstObservationTimeDB(set.getLong("unit_id"),sensorId);
+		this.lastObservationTime = findLastObservationTimeDB(set.getLong("unit_id"),sensorId);
+		SensorUtil sUtil = new SensorUtil();
+		this.phenomenon = sUtil.getPhenomenonById(set.getString("phenomenon_id"));
+	}
+	
+	public UnitSensor() throws SQLException{
+		
+	}	
+	
+	@Override
+	public DBObject getDBObject(ResultSet set) throws SQLException {
+		return new UnitSensor(set);
+	}
+
+	public long getSensorId() {
+		return sensorId;
+	}
+	public void setSensorId(long sensorId) {
+		this.sensorId = sensorId;
+	}
+	public String getSensorName() {
+		return sensorName;
+	}
+	public void setSensorName(String sensorName) {
+		this.sensorName = sensorName;
+	}
+	public String getSensorType() {
+		return sensorType;
+	}
+	public void setSensorType(String sensorType) {
+		this.sensorType = sensorType;
+	}
+	public Phenomenon getPhenomenon() {
+		return phenomenon;
+	}
+	public void setPhenomenon(Phenomenon phenomenon) {
+		this.phenomenon = phenomenon;
+	}
+	public String getFirstObservationTime() {
+		return firstObservationTime;
+	}
+	public String getLastObservationTime() {
+		return lastObservationTime;
+	}
+
+	private String findFirstObservationTimeDB(long unitId, long sensorId) throws SQLException{
+		String query = "SELECT first_obs FROM units_to_sensors WHERE unit_id = "+unitId+" AND sensor_id = "+sensorId+";";
+		ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+		if(res.next() == true){
+			String time = res.getString(1);
+			boolean wasNull = res.wasNull();
+			if (wasNull == false){
+				return time;
+			}
+			else{
+				return "unknown";
+			}
+		}
+		else{
+			return "unknown";
+		}		
+	}
+	
+	private String findLastObservationTimeDB(long unitId, long sensorId) throws SQLException{
+		String query = "SELECT last_obs FROM units_to_sensors WHERE unit_id = "+unitId+" AND sensor_id = "+sensorId+";";
+		ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+		if(res.next() == true){
+			String time = res.getString(1);
+			boolean wasNull = res.wasNull();
+			if (wasNull == false){
+				return time;
+			}
+			else{
+				return "unknown";
+			}
+		}
+		else{
+			return "unknown";
+		}			
+	}	
+}

+ 585 - 558
src/main/java/cz/hsrs/db/util/SensorUtil.java

@@ -1,559 +1,586 @@
-package cz.hsrs.db.util;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.List;
-
-import cz.hsrs.db.model.Phenomenon;
-import cz.hsrs.db.model.Sensor;
-import cz.hsrs.db.model.composite.AggregateObservation;
-import cz.hsrs.db.model.composite.ObservationValue;
-import cz.hsrs.db.model.composite.UnitSensor;
-import cz.hsrs.db.model.composite.UnitSensorObservation;
-import cz.hsrs.db.pool.SQLExecutor;
-
-/**
- * Class provides methods for publishing observations
- * @author jezekjan
- *
- */
-public class SensorUtil extends TrackUtil {
-
-    /**
-     * Empty constructor
-     */
-    public SensorUtil() {
-        super();
-    }
-
-    /**
-     * Method gets list of sensors connected to given unit
-     * @param unit_id - identifier of unit
-     * @return list of UnitSensor objects represents sensors connected to given unit
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<UnitSensor> getUnitsSensors(long unit_id) throws SQLException {
-        String queryObservations = "SELECT *"
-                + " FROM sensors, units_to_sensors "
-                + "WHERE units_to_sensors.unit_id = " + unit_id
-                + " AND units_to_sensors.sensor_id = sensors.sensor_id;";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<UnitSensor>) generateObjectList(new UnitSensor(), res);
-    }
-    
-    /**
-     * Method gets list of sensors connected to given unit
-     * @param unit_id - identifier of unit
-     * @return list of Sensor objects represents sensors connected to given unit
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<Sensor> getSensors(long unit_id) throws SQLException {
-        String queryObservations = "SELECT *"
-                + " FROM sensors, units_to_sensors"
-                + " WHERE units_to_sensors.unit_id = " + unit_id
-                + " AND units_to_sensors.sensor_id = sensors.sensor_id ORDER BY sensors.sensor_id;";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<Sensor>) generateObjectList(new Sensor(), res);
-    }
-
-    /**
-     * Method gets description of sensor by given identifier
-     * @param sensor_id - identifier of sensor
-     * @return Sensor object with all attributes 
-     * @throws SQLException
-     */
-    public Sensor getSensorById(long sensor_id) throws SQLException {
-        String queryObservations = "SELECT * FROM sensors "
-                + "WHERE sensor_id = " + sensor_id + ";";
-        ResultSet res = stmt.executeQuery(queryObservations);
-
-        if (res.next()) {
-            return (Sensor) (new Sensor()).getDBObject(res);
-        } else {
-            throw new SQLException("Sensor " + sensor_id + " not found!");
-        }
-    }
-    
-    /**
-     * Method checks if there is sensor in DB, given by Id or sensor name
-     * @param sensorId - id of sensor
-     * @param sensorName - name of sensor
-     * @return Sensor object from DB or null if there is not sensor with given id nor name
-     * @throws SQLException
-     */
-    public Sensor getSensorByIdOrName(Long sensorId, String sensorName) throws SQLException {
-        if(sensorId == null && sensorName != null){
-            String query = "SELECT * FROM sensors WHERE sensor_name = '" + sensorName + "';";
-            ResultSet res = stmt.executeQuery(query);
-            if (res.next()) {
-                return (Sensor) (new Sensor()).getDBObject(res);
-            } else {
-                return null;
-            }
-        }
-        else if(sensorId != null && sensorName == null){
-            String query = "SELECT * FROM sensors WHERE sensor_id = " + sensorId + ";";
-            ResultSet res = stmt.executeQuery(query);
-            if (res.next()) {
-                return (Sensor) (new Sensor()).getDBObject(res);
-            } else {
-                return null;
-            }
-        } else{
-            throw new SQLException("Either sensor_id or sensor_name must be given!");
-        }
-    }
-
-    /**
-     * Method selects Sensor by given sensor_name, sensor_type and phenomenon_id
-     * @param sensorName 
-     * @param sensorType
-     * @param phenId
-     * @return Sensor object from DB if there is in DB, null if there is not
-     * @throws SQLException
-     */
-    public Sensor getSensorByNameAndTypeAndPhen(String sensorName, String sensorType, String phenId) throws SQLException {
-        String query = "SELECT * FROM sensors WHERE sensor_name = '" + sensorName + "'"
-                + " AND sensor_type = '"+sensorType+"' AND phenomenon_id = '"+phenId+"';";
-        ResultSet res = stmt.executeQuery(query);
-        if (res.next()) {
-            return (Sensor) (new Sensor()).getDBObject(res);
-        } else {
-            return null;
-        }
-    }
-    
-    /**
-     * Method gets next value of sensor_id sequence
-     * @return next value of sensor_id or null if there is not possible to get next value
-     * @throws SQLException
-     */
-    public Long getNextSensorId() throws SQLException{
-        boolean exists = true;
-        Long newId = null;
-        while(exists){
-            try{
-                String selectId = "SELECT nextval('sensors_sensor_id_seq'::regclass);";
-                ResultSet resId = SQLExecutor.getInstance().executeQuery(selectId);
-                if(resId.next()){
-                    newId = resId.getLong(1);
-                } else{
-                    throw new SQLException("Sensor can't get new ID!");
-                }
-                Sensor isSame = this.getSensorByIdOrName(newId, null);
-                if(isSame == null){
-                    exists = false;
-                }
-            } catch(SQLException e){
-                throw new SQLException("Sensor can't get new ID!");
-            }
-        }
-        return newId;
-    }
-    
-    /**
-     * Method detects if given sensor is connected to given unit
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor
-     * @return true if given sensor is connected to given unit, false if not
-     * @throws SQLException
-     */
-    public boolean hasSensor(long unit_id, long sensor_id) throws SQLException {
-        String query = "SELECT * FROM units_to_sensors"
-                + " WHERE units_to_sensors.unit_id = " + unit_id
-                + " AND units_to_sensors.sensor_id = " + sensor_id;
-        ResultSet res = stmt.executeQuery(query);
-        return res.next();
-    }
-
-    /**
-     * Method gets list of observations for given unit-sensor pair and given time stamp interval
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor 
-     * @param from - begin time stamp of time range, optional
-     * @param to - end time stamp of time range, optional
-     * @return list of ObservationValue objects represents observations for given unit-sensor pair for given time stamps
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<ObservationValue> getSensorObservations(long unit_id, long sensor_id, String from, String to) throws SQLException {
-        if (from == null && to == null) {
-            return getSensorObservations(unit_id, sensor_id);
-        } else if (to == null && from != null) {
-            return getSensorObservationsFrom(unit_id, sensor_id, from);
-        } else if (to != null && from == null) {
-            return getSensorObservationsTo(unit_id, sensor_id, to);
-        } else {
-            String query = "SELECT gid, observed_value, time_stamp"
-                    + " FROM observations"
-                    + " WHERE unit_id = " + unit_id
-                    + " AND sensor_id = " + sensor_id 
-                    + " AND time_stamp > '" + from + "'"
-                    + " AND time_stamp < '" + to + "'";
-            ResultSet res = stmt.executeQuery(query);
-            return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
-        }
-    }
-
-    /**
-     * Method gets list of observations for given unit-sensor pair and given time stamp interval and trunc parameter
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor 
-     * @param from - begin time stamp of time range, mandatory
-     * @param to - end time stamp of time range, mandatory
-     * @param trunc - truncate parameter
-     * @return list of AggregateObservation objects represents observations for given unit-sensor pair for given time stamp and truncate
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<AggregateObservation> getSensorObservationsTrunc(long unit_id, long sensor_id, String from, String to, String trunc) throws SQLException {
-        String queryObservations = "SELECT"
-                + " avg(observed_value) as avg_value,"
-                + " date_trunc('" + trunc + "', time_stamp) AS dtrunc,"
-                + " count(*) AS count "
-                + " FROM observations WHERE unit_id = " + unit_id
-                + " AND sensor_id = " + sensor_id 
-                + " AND time_stamp >= '" + from + "'"
-                + " AND time_stamp <= '" + to + "'"
-                + " GROUP BY dtrunc ORDER BY dtrunc DESC;";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<AggregateObservation>) generateObjectList(new AggregateObservation(), res);
-    }
-
-    /**
-     * Method gets list of observations for given unit-sensor pair from given timestamp
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor 
-     * @param from - timestamp represents beginning of given time range
-     * @return list of ObservationValue objects represents observations for given unit-sensor pair from given time stamp
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    protected List<ObservationValue> getSensorObservationsFrom(long unit_id, long sensor_id, String from) throws SQLException {
-        String queryObservations = "SELECT gid, observed_value, time_stamp"
-                + " FROM observations WHERE unit_id = " + unit_id
-                + " AND sensor_id = " + sensor_id
-                + " AND time_stamp > '" + from + "'";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
-    }
-
-    /**
-     * Method gets list of observations for given unit-sensor pair till given end timestamp
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor 
-     * @param to - timestamp represents end of given time range 
-     * @return list of ObservationValue objects represents observations for given unit-sensor pair until given time stamp
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    protected List<ObservationValue> getSensorObservationsTo(long unit_id, long sensor_id, String to) throws SQLException {
-        String queryObservations = "SELECT gid, observed_value, time_stamp"
-                + " FROM observations WHERE unit_id = " + unit_id
-                + " AND sensor_id = " + sensor_id
-                + " AND time_stamp < '" + to + "'";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
-    }
-
-    /**
-     * Method gets list of observations for given unit-sensor pair
-     * @param unit_id - identifier of unit
-     * @param sensor_id - identifier of sensor 
-     * @return list of ObservationValue objects represents all observations for given unit-sensor pair
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<ObservationValue> getSensorObservations(long unit_id, long sensor_id) throws SQLException {
-        String queryObservations = "SELECT gid, observed_value, time_stamp"
-                    + " FROM observations WHERE unit_id = " + unit_id
-                    + " AND sensor_id = " + sensor_id + ";";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
-    }
-    
-    /**
-     * Select phenomenon by given ID
-     * @param id - phenomenonId of phenomenon to select
-     * @return Phenomenon object if there is phenomenon in DB or null if there is not
-     * @throws SQLException
-     */
-    public Phenomenon getPhenomenonById(String id) throws SQLException {
-        String queryObservations = "SELECT * FROM phenomenons"
-                + " WHERE phenomenon_id = '" + id + "';";
-        ResultSet res = stmt.executeQuery(queryObservations);
-        if (res.next()) {
-            return new Phenomenon(res);
-        } else
-            return null;
-    }
-    
-    /**
-     * Select phenomenon by given name
-     * @param phenName - name of phenomenon to select
-     * @return Phenomenon object if there is phenomenon in DB or null if there is not
-     * @throws SQLException
-     */
-    public Phenomenon getPhenomenonByName(String phenName) throws SQLException{
-        String query = "SELECT * FROM phenomenons WHERE phenomenon_name='"+phenName+"';";
-        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-        if(res.next()){
-            return new Phenomenon(res);
-        } else{
-            return null;
-        }
-    }
-    
-    /**
-     * Method get next value of phenomenonId sequence
-     * @return next value of phenomenonId, null if there is not possible to get next value 
-     * @throws SQLException
-     */
-    public String getNextPhenomenonId() throws SQLException{
-        boolean exists = true;
-        String newId = null;
-        while(exists){
-            try{
-                String selectId = "SELECT nextval('phenomenons_id_seq'::regclass);";
-                ResultSet res = SQLExecutor.getInstance().executeQuery(selectId);
-                if(res.next()){
-                    newId = res.getString(1);
-                } else{
-                    throw new SQLException("Phenomenon can't get new ID!");
-                }
-                Phenomenon isSame = getPhenomenonById(newId);
-                if(isSame == null){
-                    exists = false;
-                }
-            } catch(SQLException e){
-                throw new SQLException("Phenomenon can't get new ID!");
-            }
-        }    
-        return newId;
-    }
-    
-    /**
-     * Method checks if there is same phenomenon already in the DB
-     * @param phen Phenomenon to be checked
-     * @return Phenomenon object that is already in the DB, null if there is not any 
-     * @throws SQLException
-     */
-    public Phenomenon isPhenomenonInDB(Phenomenon phen) throws SQLException{
-        if(phen.internalGetPhenomenonId() != null){
-            Phenomenon phenDB = getPhenomenonById(phen.internalGetPhenomenonId());
-            return phenDB;
-        } else if(phen.getPhenomenonName() != null && phen.getUnit() != null){
-            Phenomenon phenDB = getPhenomenonByName(phen.getPhenomenonName());
-            if(phenDB == null){
-                return null;
-            } else{
-                if(phen.internalGetPhenomenonId() == null){
-                    phen.internalSetPhenomenonId(phenDB.internalGetPhenomenonId());
-                }
-                return phenDB;
-            }
-        } else {
-            return null;
-        }
-    }
-    
-    /**
-     * Method checks if there is already same sensor in the DB
-     * @param sen Sensor to be checked
-     * @return Sensor object that is already in the DB, null if there is not any
-     * @throws SQLException 
-     */
-    public Sensor isSensorInDB(Sensor sen) throws SQLException{
-        if(sen.getSensorId() != 0){
-            return getSensorByIdOrName(sen.getSensorId(), null);
-        } else if(sen.getSensorName() != null
-                && sen.getSensorType() != null 
-                && sen.getPhenomenon() != null)
-        {
-            Sensor senDB = getSensorByIdOrName(null, sen.getSensorName());
-            if(senDB != null){
-                Sensor sensorSame = getSensorByNameAndTypeAndPhen(
-                        sen.getSensorName(), sen.getSensorType(),
-                        sen.getPhenomenon().internalGetPhenomenonId());
-                if(sensorSame == null){
-                    throw new SQLException("Sensor with given name is already registered!");
-                } else {
-                    return sensorSame;
-                }
-            } else {
-                return null;
-            }
-        } 
-        else{
-            return null;
-        }
-    }
-    
-    /**
-     * Method try tests if there is same Sensor in the DB
-     * @param sen Sensor object to be compared
-     * @return Sensor object from DB if there is same as given, null if there is not same
-     * @throws SQLException
-     */
-    public Sensor isSameSensorInDB(Sensor sen) throws SQLException{
-        if(sen.getSensorId() != 0){
-            return getSensorByIdOrName(sen.getSensorId(), null);
-        } else if(sen.getSensorName() != null
-                && sen.getSensorType() != null 
-                && sen.getPhenomenon() != null)
-        {
-            Sensor senDB = getSensorByIdOrName(null, sen.getSensorName());
-            if(senDB != null){
-                Sensor sensorSame = getSensorByNameAndTypeAndPhen(
-                        sen.getSensorName(), sen.getSensorType(),
-                        sen.getPhenomenon().internalGetPhenomenonId());
-                if(sensorSame == null){
-                    throw new SQLException("Sensor with given name is already registered!");
-                } else {
-                    return sensorSame;
-                }
-            } else {
-                return null;
-            }
-        } else{
-            return null;
-        }
-    }
-    
-    /**
-     * Method checks if given sensor is paired with given unit
-     * @param sensorId - id of sensor
-     * @param unitId - id of unit
-     * @return true if sensor is paired, false if not
-     * @throws SQLException
-     */
-    public boolean isSensorPairedToUnit(long sensorId, long unitId) throws SQLException{
-        String query = "SELECT sensor_id, unit_id FROM units_to_sensors WHERE unit_id ="+unitId+" AND sensor_id ="+sensorId+";";
-        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-        return res.next();
-    }
-    /**
-     * Method inserts new sensor in DB
-     * @param sen - Sensor to be inserted
-     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
-     * @throws SQLException
-     */
-    public int insertSensor(Sensor sen) throws SQLException{
-        String ins = "INSERT INTO sensors (sensor_id, sensor_name, sensor_type, phenomenon_id)"
-                + " VALUES ("+sen.getSensorId()
-                +", '"+sen.getSensorName()
-                +"', '"+sen.getSensorType()
-                +"', '"+sen.getPhenomenon().internalGetPhenomenonId()+"');";
-        return SQLExecutor.executeUpdate(ins);
-    }
-    
-    /**
-     * Method pairs unit to sensor 
-     * @param unitId - id of unit
-     * @param sensorId - id of sensor
-     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
-     * @throws SQLException
-     */
-    public int pairUnitToSensor(long unitId, long sensorId) throws SQLException{
-        String insUS = "INSERT INTO units_to_sensors(unit_id, sensor_id) VALUES("+unitId+", "+sensorId+");";
-        return SQLExecutor.executeUpdate(insUS);
-    }
-    
-    /**
-     * Method inserts new Phenomenon in DB
-     * @param phen Phenomenon object to be inserted, all attributes must by given
-     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
-     * @throws SQLException 
-     */
-    public int insertNewPhenomenon(Phenomenon phen) throws SQLException{
-        String ins = "INSERT INTO phenomenons (phenomenon_id, phenomenon_name, unit)"
-                + " VALUES ('"+phen.internalGetPhenomenonId()
-                +"', '"+phen.getPhenomenonName()
-                +"', '"+phen.getUnit()+"');";
-        return SQLExecutor.executeUpdate(ins);
-    }
-
-    /**
-     * Method gets last observation for given unit-sensor pair
-     * @param unitId - identifier of unit
-     * @param sensorId - identifier of sensor 
-     * @return ResultSet object represents last observation for given unit-sensor pair
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-	public List<ObservationValue> getSensorLastObservation(long unitId, long sensorId) throws SQLException {
-        String query = "SELECT time_stamp, gid, observed_value"
-                    + " FROM units_to_sensors uts"
-                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
-                    + " WHERE uts.unit_id = "+unitId
-                    + " AND uts.sensor_id = "+sensorId
-                    + " AND uts.sensor_id = o.sensor_id;";
-        ResultSet res = stmt.executeQuery(query);
-        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
-    }
-    
-    /**
-     * Method gets list of last observations from all connected sensors for given unit
-     * @param unitId - identifier of unit
-     * @return list of UnitSensorObservation objects represents last observations from all connected sensors to given unit
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<UnitSensorObservation> getUnitSensorsLastObservations(long unitId) throws SQLException{
-        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
-                    + " FROM units_to_sensors uts"
-                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
-                    + " WHERE uts.unit_id = " + unitId
-                    + " AND uts.sensor_id = o.sensor_id;";
-        ResultSet res = stmt.executeQuery(query);
-        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
-    }
-    
-    /**
-     * Method gets list of last observations from all connected sensors to all units belonging to given group
-     * @param groupName - name of group
-     * @return list of UnitSensorObservation objects represents last observations from all connected sensors to all units
-     * belonging to given group
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName) throws SQLException{
-        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
-                    + " FROM groups g, units_to_groups utg, units_to_sensors uts"
-                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
-                    + " WHERE g.group_name = '"+groupName+"'"
-                    + " AND g.id = utg.group_id"
-                    + " AND utg.unit_id = uts.unit_id"
-                    + " AND uts.unit_id = o.unit_id"
-                    + " AND uts.sensor_id = o.sensor_id"
-                    + " ORDER BY uts.unit_id, uts.sensor_id;";
-        ResultSet res = stmt.executeQuery(query);
-        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
-    }
-
-    /**
-     * Method gets list of last observations of given connected sensor of all units belonging to given group.
-     * @param groupName - name of group
-     * @param sensorId - identifier of sensor
-     * @return list of UnitSensorObservation objects represents last observations for given connected sensors to all units
-     * belonging to given group
-     * @throws SQLException
-     */
-    @SuppressWarnings("unchecked")
-    public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName, long sensorId) throws SQLException{
-        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
-                + " FROM groups g, units_to_groups utg, units_to_sensors uts"
-                + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
-                + " WHERE g.group_name = '"+groupName+"'"
-                + " AND g.id = utg.group_id"
-                + " AND utg.unit_id = uts.unit_id"
-                + " AND uts.sensor_id = "+sensorId
-                + " AND uts.unit_id = o.unit_id"
-                + " AND uts.sensor_id = o.sensor_id"
-                + " ORDER BY uts.unit_id, uts.sensor_id;";
-        ResultSet res = stmt.executeQuery(query);
-        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
-    }
+package cz.hsrs.db.util;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+import cz.hsrs.db.model.Phenomenon;
+import cz.hsrs.db.model.Sensor;
+import cz.hsrs.db.model.composite.AggregateObservation;
+import cz.hsrs.db.model.composite.ObservationValue;
+import cz.hsrs.db.model.composite.UnitSensor;
+import cz.hsrs.db.model.composite.UnitSensorObservation;
+import cz.hsrs.db.pool.SQLExecutor;
+
+/**
+ * Class provides methods for publishing observations
+ * @author jezekjan
+ *
+ */
+public class SensorUtil extends TrackUtil {
+
+    /**
+     * Empty constructor
+     */
+    public SensorUtil() {
+        super();
+    }
+
+    /**
+     * Method gets list of sensors connected to given unit
+     * @param unit_id - identifier of unit
+     * @return list of UnitSensor objects represents sensors connected to given unit
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<UnitSensor> getUnitsSensors(long unit_id) throws SQLException {
+        String queryObservations = "SELECT *"
+                + " FROM sensors, units_to_sensors "
+                + "WHERE units_to_sensors.unit_id = " + unit_id
+                + " AND units_to_sensors.sensor_id = sensors.sensor_id;";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<UnitSensor>) generateObjectList(new UnitSensor(), res);
+    }
+    
+    /**
+     * Method gets list of sensors connected to given unit
+     * @param unit_id - identifier of unit
+     * @return list of Sensor objects represents sensors connected to given unit
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<Sensor> getSensors(long unit_id) throws SQLException {
+        String queryObservations = "SELECT *"
+                + " FROM sensors, units_to_sensors"
+                + " WHERE units_to_sensors.unit_id = " + unit_id
+                + " AND units_to_sensors.sensor_id = sensors.sensor_id ORDER BY sensors.sensor_id;";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<Sensor>) generateObjectList(new Sensor(), res);
+    }
+    
+    /**
+     * 
+     * @return
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+	public List<Sensor> getSensors() throws SQLException {
+        String queryObservations = "SELECT * FROM sensors ORDER BY sensors.sensor_id;";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<Sensor>) generateObjectList(new Sensor(), res);
+    }
+
+    /**
+     * Method gets description of sensor by given identifier
+     * @param sensor_id - identifier of sensor
+     * @return Sensor object with all attributes 
+     * @throws SQLException
+     */
+    public Sensor getSensorById(long sensor_id) throws SQLException {
+        String queryObservations = "SELECT * FROM sensors "
+                + "WHERE sensor_id = " + sensor_id + ";";
+        ResultSet res = stmt.executeQuery(queryObservations);
+
+        if (res.next()) {
+            return (Sensor) (new Sensor()).getDBObject(res);
+        } else {
+            throw new SQLException("Sensor " + sensor_id + " not found!");
+        }
+    }
+    
+    /**
+     * Method checks if there is sensor in DB, given by Id or sensor name
+     * @param sensorId - id of sensor
+     * @param sensorName - name of sensor
+     * @return Sensor object from DB or null if there is not sensor with given id nor name
+     * @throws SQLException
+     */
+    public Sensor getSensorByIdOrName(Long sensorId, String sensorName) throws SQLException {
+        if(sensorId == null && sensorName != null){
+            String query = "SELECT * FROM sensors WHERE sensor_name = '" + sensorName + "';";
+            ResultSet res = stmt.executeQuery(query);
+            if (res.next()) {
+                return (Sensor) (new Sensor()).getDBObject(res);
+            } else {
+                return null;
+            }
+        }
+        else if(sensorId != null && sensorName == null){
+            String query = "SELECT * FROM sensors WHERE sensor_id = " + sensorId + ";";
+            ResultSet res = stmt.executeQuery(query);
+            if (res.next()) {
+                return (Sensor) (new Sensor()).getDBObject(res);
+            } else {
+                return null;
+            }
+        } else{
+            throw new SQLException("Either sensor_id or sensor_name must be given!");
+        }
+    }
+
+    /**
+     * Method selects Sensor by given sensor_name, sensor_type and phenomenon_id
+     * @param sensorName 
+     * @param sensorType
+     * @param phenId
+     * @return Sensor object from DB if there is in DB, null if there is not
+     * @throws SQLException
+     */
+    public Sensor getSensorByNameAndTypeAndPhen(String sensorName, String sensorType, String phenId) throws SQLException {
+        String query = "SELECT * FROM sensors WHERE sensor_name = '" + sensorName + "'"
+                + " AND sensor_type = '"+sensorType+"' AND phenomenon_id = '"+phenId+"';";
+        ResultSet res = stmt.executeQuery(query);
+        if (res.next()) {
+            return (Sensor) (new Sensor()).getDBObject(res);
+        } else {
+            return null;
+        }
+    }
+    
+    /**
+     * Method gets next value of sensor_id sequence
+     * @return next value of sensor_id or null if there is not possible to get next value
+     * @throws SQLException
+     */
+    public Long getNextSensorId() throws SQLException{
+        boolean exists = true;
+        Long newId = null;
+        while(exists){
+            try{
+                String selectId = "SELECT nextval('sensors_sensor_id_seq'::regclass);";
+                ResultSet resId = SQLExecutor.getInstance().executeQuery(selectId);
+                if(resId.next()){
+                    newId = resId.getLong(1);
+                } else{
+                    throw new SQLException("Sensor can't get new ID!");
+                }
+                Sensor isSame = this.getSensorByIdOrName(newId, null);
+                if(isSame == null){
+                    exists = false;
+                }
+            } catch(SQLException e){
+                throw new SQLException("Sensor can't get new ID!");
+            }
+        }
+        return newId;
+    }
+    
+    /**
+     * Method detects if given sensor is connected to given unit
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor
+     * @return true if given sensor is connected to given unit, false if not
+     * @throws SQLException
+     */
+    public boolean hasSensor(long unit_id, long sensor_id) throws SQLException {
+        String query = "SELECT * FROM units_to_sensors"
+                + " WHERE units_to_sensors.unit_id = " + unit_id
+                + " AND units_to_sensors.sensor_id = " + sensor_id;
+        ResultSet res = stmt.executeQuery(query);
+        return res.next();
+    }
+
+    /**
+     * Method gets list of observations for given unit-sensor pair and given time stamp interval
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor 
+     * @param from - begin time stamp of time range, optional
+     * @param to - end time stamp of time range, optional
+     * @return list of ObservationValue objects represents observations for given unit-sensor pair for given time stamps
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<ObservationValue> getSensorObservations(long unit_id, long sensor_id, String from, String to) throws SQLException {
+        if (from == null && to == null) {
+            return getSensorObservations(unit_id, sensor_id);
+        } else if (to == null && from != null) {
+            return getSensorObservationsFrom(unit_id, sensor_id, from);
+        } else if (to != null && from == null) {
+            return getSensorObservationsTo(unit_id, sensor_id, to);
+        } else {
+            String query = "SELECT gid, observed_value, time_stamp"
+                    + " FROM observations"
+                    + " WHERE unit_id = " + unit_id
+                    + " AND sensor_id = " + sensor_id 
+                    + " AND time_stamp > '" + from + "'"
+                    + " AND time_stamp < '" + to + "'";
+            ResultSet res = stmt.executeQuery(query);
+            return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
+        }
+    }
+
+    /**
+     * Method gets list of observations for given unit-sensor pair and given time stamp interval and trunc parameter
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor 
+     * @param from - begin time stamp of time range, mandatory
+     * @param to - end time stamp of time range, mandatory
+     * @param trunc - truncate parameter
+     * @return list of AggregateObservation objects represents observations for given unit-sensor pair for given time stamp and truncate
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<AggregateObservation> getSensorObservationsTrunc(long unit_id, long sensor_id, String from, String to, String trunc) throws SQLException {
+        String queryObservations = "SELECT"
+                + " avg(observed_value) as avg_value,"
+                + " date_trunc('" + trunc + "', time_stamp) AS dtrunc,"
+                + " count(*) AS count "
+                + " FROM observations WHERE unit_id = " + unit_id
+                + " AND sensor_id = " + sensor_id 
+                + " AND time_stamp >= '" + from + "'"
+                + " AND time_stamp <= '" + to + "'"
+                + " GROUP BY dtrunc ORDER BY dtrunc DESC;";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<AggregateObservation>) generateObjectList(new AggregateObservation(), res);
+    }
+
+    /**
+     * Method gets list of observations for given unit-sensor pair from given timestamp
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor 
+     * @param from - timestamp represents beginning of given time range
+     * @return list of ObservationValue objects represents observations for given unit-sensor pair from given time stamp
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    protected List<ObservationValue> getSensorObservationsFrom(long unit_id, long sensor_id, String from) throws SQLException {
+        String queryObservations = "SELECT gid, observed_value, time_stamp"
+                + " FROM observations WHERE unit_id = " + unit_id
+                + " AND sensor_id = " + sensor_id
+                + " AND time_stamp > '" + from + "'";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
+    }
+
+    /**
+     * Method gets list of observations for given unit-sensor pair till given end timestamp
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor 
+     * @param to - timestamp represents end of given time range 
+     * @return list of ObservationValue objects represents observations for given unit-sensor pair until given time stamp
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    protected List<ObservationValue> getSensorObservationsTo(long unit_id, long sensor_id, String to) throws SQLException {
+        String queryObservations = "SELECT gid, observed_value, time_stamp"
+                + " FROM observations WHERE unit_id = " + unit_id
+                + " AND sensor_id = " + sensor_id
+                + " AND time_stamp < '" + to + "'";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
+    }
+
+    /**
+     * Method gets list of observations for given unit-sensor pair
+     * @param unit_id - identifier of unit
+     * @param sensor_id - identifier of sensor 
+     * @return list of ObservationValue objects represents all observations for given unit-sensor pair
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<ObservationValue> getSensorObservations(long unit_id, long sensor_id) throws SQLException {
+        String queryObservations = "SELECT gid, observed_value, time_stamp"
+                    + " FROM observations WHERE unit_id = " + unit_id
+                    + " AND sensor_id = " + sensor_id + ";";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
+    }
+    
+    /**
+     * Method gets all Phenomenons in DB
+     * @return
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+	public List<Phenomenon> getPhenomenons() throws SQLException {
+        String queryObservations = "SELECT * FROM phenomenons ORDER BY phenomenon_id;";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        if (res.next()) {
+            return (List<Phenomenon>) generateObjectList(new Phenomenon(), res);
+        } else
+            return null;
+    }
+    
+    /**
+     * Select phenomenon by given ID
+     * @param id - phenomenonId of phenomenon to select
+     * @return Phenomenon object if there is phenomenon in DB or null if there is not
+     * @throws SQLException
+     */
+    public Phenomenon getPhenomenonById(String id) throws SQLException {
+        String queryObservations = "SELECT * FROM phenomenons"
+                + " WHERE phenomenon_id = '" + id + "';";
+        ResultSet res = stmt.executeQuery(queryObservations);
+        if (res.next()) {
+            return new Phenomenon(res);
+        } else
+            return null;
+    }
+    
+    /**
+     * Select phenomenon by given name
+     * @param phenName - name of phenomenon to select
+     * @return Phenomenon object if there is phenomenon in DB or null if there is not
+     * @throws SQLException
+     */
+    public Phenomenon getPhenomenonByName(String phenName) throws SQLException{
+        String query = "SELECT * FROM phenomenons WHERE phenomenon_name='"+phenName+"';";
+        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+        if(res.next()){
+            return new Phenomenon(res);
+        } else{
+            return null;
+        }
+    }
+    
+    /**
+     * Method get next value of phenomenonId sequence
+     * @return next value of phenomenonId, null if there is not possible to get next value 
+     * @throws SQLException
+     */
+    public String getNextPhenomenonId() throws SQLException{
+        boolean exists = true;
+        String newId = null;
+        while(exists){
+            try{
+                String selectId = "SELECT nextval('phenomenons_id_seq'::regclass);";
+                ResultSet res = SQLExecutor.getInstance().executeQuery(selectId);
+                if(res.next()){
+                    newId = res.getString(1);
+                } else{
+                    throw new SQLException("Phenomenon can't get new ID!");
+                }
+                Phenomenon isSame = getPhenomenonById(newId);
+                if(isSame == null){
+                    exists = false;
+                }
+            } catch(SQLException e){
+                throw new SQLException("Phenomenon can't get new ID!");
+            }
+        }    
+        return newId;
+    }
+    
+    /**
+     * Method checks if there is same phenomenon already in the DB
+     * @param phen Phenomenon to be checked
+     * @return Phenomenon object that is already in the DB, null if there is not any 
+     * @throws SQLException
+     */
+    public Phenomenon isPhenomenonInDB(Phenomenon phen) throws SQLException{
+        if(phen.internalGetPhenomenonId() != null){
+            Phenomenon phenDB = getPhenomenonById(phen.internalGetPhenomenonId());
+            return phenDB;
+        } else if(phen.getPhenomenonName() != null && phen.getUnit() != null){
+            Phenomenon phenDB = getPhenomenonByName(phen.getPhenomenonName());
+            if(phenDB == null){
+                return null;
+            } else{
+                if(phen.internalGetPhenomenonId() == null){
+                    phen.internalSetPhenomenonId(phenDB.internalGetPhenomenonId());
+                }
+                return phenDB;
+            }
+        } else {
+            return null;
+        }
+    }
+    
+    /**
+     * Method checks if there is already same sensor in the DB
+     * @param sen Sensor to be checked
+     * @return Sensor object that is already in the DB, null if there is not any
+     * @throws SQLException 
+     */
+    public Sensor isSensorInDB(Sensor sen) throws SQLException{
+        if(sen.getSensorId() != 0){
+            return getSensorByIdOrName(sen.getSensorId(), null);
+        } else if(sen.getSensorName() != null
+                && sen.getSensorType() != null 
+                && sen.getPhenomenon() != null)
+        {
+            Sensor senDB = getSensorByIdOrName(null, sen.getSensorName());
+            if(senDB != null){
+                Sensor sensorSame = getSensorByNameAndTypeAndPhen(
+                        sen.getSensorName(), sen.getSensorType(),
+                        sen.getPhenomenon().internalGetPhenomenonId());
+                if(sensorSame == null){
+                    throw new SQLException("Sensor with given name is already registered!");
+                } else {
+                    return sensorSame;
+                }
+            } else {
+                return null;
+            }
+        } 
+        else{
+            return null;
+        }
+    }
+    
+    /**
+     * Method try tests if there is same Sensor in the DB
+     * @param sen Sensor object to be compared
+     * @return Sensor object from DB if there is same as given, null if there is not same
+     * @throws SQLException
+     */
+    public Sensor isSameSensorInDB(Sensor sen) throws SQLException{
+        if(sen.getSensorId() != 0){
+            return getSensorByIdOrName(sen.getSensorId(), null);
+        } else if(sen.getSensorName() != null
+                && sen.getSensorType() != null 
+                && sen.getPhenomenon() != null)
+        {
+            Sensor senDB = getSensorByIdOrName(null, sen.getSensorName());
+            if(senDB != null){
+                Sensor sensorSame = getSensorByNameAndTypeAndPhen(
+                        sen.getSensorName(), sen.getSensorType(),
+                        sen.getPhenomenon().internalGetPhenomenonId());
+                if(sensorSame == null){
+                    throw new SQLException("Sensor with given name is already registered!");
+                } else {
+                    return sensorSame;
+                }
+            } else {
+                return null;
+            }
+        } else{
+            return null;
+        }
+    }
+    
+    /**
+     * Method checks if given sensor is paired with given unit
+     * @param sensorId - id of sensor
+     * @param unitId - id of unit
+     * @return true if sensor is paired, false if not
+     * @throws SQLException
+     */
+    public boolean isSensorPairedToUnit(long sensorId, long unitId) throws SQLException{
+        String query = "SELECT sensor_id, unit_id FROM units_to_sensors WHERE unit_id ="+unitId+" AND sensor_id ="+sensorId+";";
+        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+        return res.next();
+    }
+    /**
+     * Method inserts new sensor in DB
+     * @param sen - Sensor to be inserted
+     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
+     * @throws SQLException
+     */
+    public int insertSensor(Sensor sen) throws SQLException{
+        String ins = "INSERT INTO sensors (sensor_id, sensor_name, sensor_type, phenomenon_id)"
+                + " VALUES ("+sen.getSensorId()
+                +", '"+sen.getSensorName()
+                +"', '"+sen.getSensorType()
+                +"', '"+sen.getPhenomenon().internalGetPhenomenonId()+"');";
+        return SQLExecutor.executeUpdate(ins);
+    }
+    
+    /**
+     * Method pairs unit to sensor 
+     * @param unitId - id of unit
+     * @param sensorId - id of sensor
+     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
+     * @throws SQLException
+     */
+    public int pairUnitToSensor(long unitId, long sensorId) throws SQLException{
+        String insUS = "INSERT INTO units_to_sensors(unit_id, sensor_id) VALUES("+unitId+", "+sensorId+");";
+        return SQLExecutor.executeUpdate(insUS);
+    }
+    
+    /**
+     * Method inserts new Phenomenon in DB
+     * @param phen Phenomenon object to be inserted, all attributes must by given
+     * @return either (1) the row count for SQL DML statements or (2) 0 for SQL statements that return nothing
+     * @throws SQLException 
+     */
+    public int insertNewPhenomenon(Phenomenon phen) throws SQLException{
+        String ins = "INSERT INTO phenomenons (phenomenon_id, phenomenon_name, unit)"
+                + " VALUES ('"+phen.internalGetPhenomenonId()
+                +"', '"+phen.getPhenomenonName()
+                +"', '"+phen.getUnit()+"');";
+        return SQLExecutor.executeUpdate(ins);
+    }
+
+    /**
+     * Method gets last observation for given unit-sensor pair
+     * @param unitId - identifier of unit
+     * @param sensorId - identifier of sensor 
+     * @return ResultSet object represents last observation for given unit-sensor pair
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+	public List<ObservationValue> getSensorLastObservation(long unitId, long sensorId) throws SQLException {
+        String query = "SELECT time_stamp, gid, observed_value"
+                    + " FROM units_to_sensors uts"
+                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
+                    + " WHERE uts.unit_id = "+unitId
+                    + " AND uts.sensor_id = "+sensorId
+                    + " AND uts.sensor_id = o.sensor_id;";
+        ResultSet res = stmt.executeQuery(query);
+        return (List<ObservationValue>) generateObjectList(new ObservationValue(), res);
+    }
+    
+    /**
+     * Method gets list of last observations from all connected sensors for given unit
+     * @param unitId - identifier of unit
+     * @return list of UnitSensorObservation objects represents last observations from all connected sensors to given unit
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<UnitSensorObservation> getUnitSensorsLastObservations(long unitId) throws SQLException{
+        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
+                    + " FROM units_to_sensors uts"
+                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
+                    + " WHERE uts.unit_id = " + unitId
+                    + " AND uts.sensor_id = o.sensor_id;";
+        ResultSet res = stmt.executeQuery(query);
+        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
+    }
+    
+    /**
+     * Method gets list of last observations from all connected sensors to all units belonging to given group
+     * @param groupName - name of group
+     * @return list of UnitSensorObservation objects represents last observations from all connected sensors to all units
+     * belonging to given group
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName) throws SQLException{
+        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
+                    + " FROM groups g, units_to_groups utg, units_to_sensors uts"
+                    + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
+                    + " WHERE g.group_name = '"+groupName+"'"
+                    + " AND g.id = utg.group_id"
+                    + " AND utg.unit_id = uts.unit_id"
+                    + " AND uts.unit_id = o.unit_id"
+                    + " AND uts.sensor_id = o.sensor_id"
+                    + " ORDER BY uts.unit_id, uts.sensor_id;";
+        ResultSet res = stmt.executeQuery(query);
+        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
+    }
+
+    /**
+     * Method gets list of last observations of given connected sensor of all units belonging to given group.
+     * @param groupName - name of group
+     * @param sensorId - identifier of sensor
+     * @return list of UnitSensorObservation objects represents last observations for given connected sensors to all units
+     * belonging to given group
+     * @throws SQLException
+     */
+    @SuppressWarnings("unchecked")
+    public List<UnitSensorObservation> getUnitsSensorsLastObservations(String groupName, long sensorId) throws SQLException{
+        String query = "SELECT time_stamp, gid, observed_value, o.sensor_id, o.unit_id"
+                + " FROM groups g, units_to_groups utg, units_to_sensors uts"
+                + " LEFT JOIN observations o ON uts.last_obs = o.time_stamp"
+                + " WHERE g.group_name = '"+groupName+"'"
+                + " AND g.id = utg.group_id"
+                + " AND utg.unit_id = uts.unit_id"
+                + " AND uts.sensor_id = "+sensorId
+                + " AND uts.unit_id = o.unit_id"
+                + " AND uts.sensor_id = o.sensor_id"
+                + " ORDER BY uts.unit_id, uts.sensor_id;";
+        ResultSet res = stmt.executeQuery(query);
+        return (List<UnitSensorObservation>) generateObjectList(new UnitSensorObservation(), res);
+    }
 }

+ 425 - 408
src/main/java/cz/hsrs/db/util/UserUtil.java

@@ -1,409 +1,426 @@
-package cz.hsrs.db.util;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.model.Unit;
-import cz.hsrs.db.model.UnitPosition;
-import cz.hsrs.db.model.composite.LastPosition;
-import cz.hsrs.db.pool.SQLExecutor;
-
-/**
- * @author jezekjan
- */
-public class UserUtil extends GroupUtil {
-
-    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
-
-    public UserUtil() {}
-
-    public String getUserLanguage(String user_name) throws SQLException, NoItemFoundException {
-        String select = "SELECT lang FROM system_users WHERE user_name = '"+user_name+"'";
-        ResultSet res = stmt.executeQuery(select);
-        if (res.next()) {
-            return res.getString(1);
-        } else
-            throw new NoItemFoundException("getUserLanguage " + user_name + " not found.");
-    }
-
-    public int getUserId(String userName) throws NoItemFoundException, SQLException{
-        String query = "SELECT user_id FROM system_users WHERE user_name = '"+userName+"';";
-        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-        if(res.next()){
-            return res.getInt(1);
-        } else{
-            throw new NoItemFoundException("User with given " + userName + " was not found.");
-        }
-    }
-
-    public int setUserLanguage(String user_name, String newLang) throws SQLException{
-        String query = "UPDATE system_users SET lang = '"+newLang+"' WHERE user_name = '"+user_name+"';";
-        return SQLExecutor.executeUpdate(query);
-    }
-    
-    public boolean getAudio(String user_name) throws SQLException, NoItemFoundException {
-        String select = "SELECT audio FROM system_users WHERE user_name = '"+user_name+"'";
-        ResultSet res = stmt.executeQuery(select);
-        if (res.next()) {
-            return res.getBoolean(1);
-        } else
-            throw new NoItemFoundException("getAudio " + user_name + " not found.");
-    }
-    @SuppressWarnings("unchecked")
-    public List<UnitPosition> getLastPositionsByUserName(String user_name) throws SQLException {
-        return (List<UnitPosition>) generateObjectList(new UnitPosition(), getLastPositionsByUserNameRes(user_name));
-    }
-    
-    @Deprecated
-    public String getRole(String user_name) throws SQLException, NoItemFoundException{
-        String query = "SELECT user_role FROM rights, system_users WHERE " +
-                "system_users.user_name = '"+user_name + "' AND "+
-                "system_users.rights_id = rights.rights_id";
-        ResultSet res = stmt.executeQuery(query);
-        if (res.next()) {
-            return res.getString(1);
-        } else
-            throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
-    }
-    
-    /**
-     * Method select groupId of given user
-     * @return groupId as int or null if there is not any user with given userName
-     */
-    public static Integer getUserGroupId(String userName) throws SQLException{
-        String query = "SELECT group_id FROM system_users WHERE user_name ='"+userName+"';";
-        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
-        return res.next() ? res.getInt(1) : null;
-    }
-
-    @SuppressWarnings("unchecked")
-    public List<LastPosition> getLastPositionWithStatus(String user_name) throws SQLException {
-        List<LastPosition> lastPositions = new ArrayList<>();
-        List<UnitPosition> positions = (List<UnitPosition>) generateObjectList(
-                new UnitPosition(), getLastPositionsByUserNameRes(user_name));
-
-        for (UnitPosition pos : positions) {
-            lastPositions.add((new UnitUtil()).getLastPositionWithStatus(pos));
-        }
-        return lastPositions;
-    }
-
-    public ResultSet getLastPositionsByUserNameRes(String user_name) throws SQLException {
-        /**
-         * select last_units_positions.gid, st_astext(the_geom),
-         * last_units_positions.unit_id, last_units_positions.time_stamp from
-         * last_units_positions, units_to_groups,system_users WHERE
-         * system_users.user_name = 'pepa' AND system_users.group_id=
-         * units_to_groups.group_id AND units_to_groups.unit_id =
-         * last_units_positions.unit_id ;
-         */
-        String last_pos_table = SQLExecutor.getUnitsLastPositions_table();
-        String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
-                + last_pos_table
-                + ".unit_id, time_stamp, units_to_groups.group_id "
-                + "FROM "
-                + last_pos_table
-                + ", "
-                + "units_to_groups "
-                + " WHERE ("
-                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
-                + ") AND units_to_groups.unit_id = "
-                + last_pos_table
-                + ".unit_id; ";
-        return stmt.executeQuery(queryObservations);
-    }
-
-    public ResultSet getLastPositionsByUserNameRes(String user_name, Long unit_id) throws SQLException {
-
-        if (unit_id == null) {
-            return getLastPositionsByUserNameRes(user_name);
-        } else {
-            String last_pos_table = SQLExecutor
-                    .getUnitsLastPositions_table();
-            String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
-                    + last_pos_table
-                    + ".unit_id, time_stamp, units_to_groups.group_id "
-                    + "FROM "
-                    + last_pos_table
-                    + ", "
-                    + "units_to_groups "
-                    + " WHERE ("
-                    + this.getWhereStatemant(user_name,
-                            "units_to_groups.group_id")
-                    + ") AND units_to_groups.unit_id = "
-                    + last_pos_table
-                    + ".unit_id AND "
-                    + last_pos_table
-                    + ".unit_id = "
-                    + unit_id;
-
-            return stmt.executeQuery(queryObservations);
-        }
-    }
-
-    /** Get Positions by user name */
-    public ResultSet getPositionsByUserName(String user_name, Integer limit) throws SQLException {
-
-        String sqlLimit = "";
-        if (limit != null) {
-            if (limit == 1) {
-                return getLastPositionsByUserNameRes(user_name);
-            }
-            sqlLimit = "LIMIT " + limit;
-        }
-        String pos_table =  SQLExecutor.getUnitsPositions_table();
-        String queryObservations = "select gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
-                + pos_table
-                + ".unit_id, time_stamp, units_to_groups.group_id  " + "from  "
-                + pos_table + ", units_to_groups " + "WHERE ("
-                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
-                + ") AND units_to_groups.unit_id = " + pos_table + ".unit_id "
-                + " ORDER BY time_stamp DESC " + sqlLimit + " ;";
-
-        return stmt.executeQuery(queryObservations);
-    }
-
-    public ResultSet getTracksByUserName(String user_name, int limit) throws SQLException {
-        /**
-         * select gid, st_astext(the_geom) from units_tracks, units_to_groups,
-         * system_users WHERE system_users.user_name = 'pepa' AND
-         * system_users.group_id= units_to_groups.group_id AND
-         * units_to_groups.unit_id = units_tracks.unit_id ;
-         */
-
-        String tracks_table =  SQLExecutor.getUnitsTracks_table();
-        String queryObservations = "select gid, st_astext(the_geom), "
-                + tracks_table
-                + ".unit_id, track_start, track_end, units_to_groups.group_id "
-                + "from  " + tracks_table + "," + " units_to_groups"
-                + " WHERE ("
-                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
-                + ") AND units_to_groups.unit_id = " + tracks_table
-                + ".unit_id order by track_end desc limit " + limit + "; ";
-
-        return stmt.executeQuery(queryObservations);
-    }
-
-    public String getUserPassword(String user_name) throws SQLException, NoItemFoundException {
-        String queryObservations = "select user_password from system_users WHERE user_name='" + user_name + "';";
-
-        ResultSet res = stmt.executeQuery(queryObservations);
-        if (res.next()) {
-            return res.getString(1);
-        } else
-            throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
-    }
-
-    public int insertUser(String user_name, String pass) throws SQLException {
-        String insert = "insert into system_users(user_name, user_password) Values('" + user_name + "','" + pass + "');";
-        return SQLExecutor.executeUpdate(insert);
-    }
-
-    public int deleteUser(String user_name) throws SQLException {
-        String del = "DELETE FROM system_users WHERE user_name='" + user_name + "';";
-        return SQLExecutor.executeUpdate(del);
-    }
-
-    public int setUserSession(String user_name, String session_id, String IP) throws SQLException {
-        /* try to delete session if exists */
-        delUserSession(session_id);
-        
-        String getUsID = "SELECT user_id FROM system_users WHERE user_name = '" + user_name + "'";
-        ResultSet res = stmt.executeQuery(getUsID);
-        res.next();
-        int user_id = res.getInt(1);
-
-        String insert = "INSERT INTO sessions(session_id, system_user_id, ip) VALUES ("
-                + "'" + session_id + "'," + user_id + ",'" + IP + "')";
-        return SQLExecutor.executeUpdate(insert);
-    }
-
-    public int delUserSession(String session_id) throws SQLException {
-        String insert = "DELETE FROM sessions WHERE session_id ='" + session_id + "'";
-        return SQLExecutor.executeUpdate(insert);
-    }
-    
-    @SuppressWarnings("unchecked")
-    public List<Unit> getUnitsByUser(String user_name) throws SQLException{
-        String query = "SELECT u.unit_id, u.holder_id, u.description " +
-                "FROM units u, units_to_groups utg, system_users su " +
-                "WHERE su.user_name = '"+user_name+"' " +
-                "AND su.group_id = utg.group_id " +
-                "AND utg.unit_id = u.unit_id;";
-        ResultSet res = stmt.executeQuery(query);
-        return (List<Unit>)generateObjectList(new Unit(), res);
-    }
-
-    public SimpleDateFormat getDateFormater() {
-        return FORMATTER;
-    }
-
-    /**
-     * Method returns positions of units in all groups for defined user collected in day defined by timeStamp parameter
-     * @param user_name is String username of logged user 
-     * @param timeStamp is day for which positions should be found
-     * @return ResultSet object with positions during one defined day
-     * @throws SQLException 
-     */
-    public ResultSet getPositionsByUserNameInDay2(String user_name, String timeStamp) throws SQLException {
-        if(timeStamp !=null){
-            String pos_table =  SQLExecutor.getUnitsPositions_table();
-            String query = "SELECT gid, "+pos_table+".unit_id, units_to_groups.group_id, "
-                    + "time_stamp, speed, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
-                    + "FROM "+pos_table+", units_to_groups "
-                    + "WHERE ("+this.getWhereStatemant(user_name, "units_to_groups.group_id")+") "
-                        + "AND units_to_groups.unit_id = "+pos_table+".unit_id "
-                        + "AND time_stamp > '"+timeStamp+"' AND time_stamp < timestamp '"+timeStamp+"' + INTERVAL '1 day' "
-                        + "ORDER BY time_stamp DESC;";
-            return stmt.executeQuery(query);
-        } else{
-            throw new SQLException("Parameter timestamp was not defined!");
-        }
-    }
-    
-    /**
-     * Method returns positions of units in all groups for defined user collected from defined timestamp parameter
-     * @param user_name is String username of logged user 
-     * @param fromTime is timestamp of the beginning
-     * @param unitId is identifier of unit
-     * @param ordering is order direction for results, can be ASC or DESC only
-     * @return ResultSet object with positions from defined timestamp, number is limited by range of 1 day!!!
-     * @throws SQLException
-     */
-    public ResultSet getPositionsByUserNameInDay(String user_name, String fromTime, long unitId, String ordering) throws SQLException {
-        if(fromTime != null){
-            String pos_table =  SQLExecutor.getUnitsPositions_table();
-            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
-                    + "FROM "+pos_table+" "
-                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
-                        + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+fromTime+"'::timestamp + '1 day'::interval "
-                        + "ORDER BY time_stamp "+ordering+";";
-
-            return stmt.executeQuery(query);
-        } else{
-            throw new SQLException("Parameter fromTime was not defined!");
-        }
-    }
-    
-    /**
-     * Method returns positions of units in all groups for defined user collected to defined timestamp parameter
-     * @param user_name is String username of logged user 
-     * @param toTime is timestamp of the end of range
-     * @param unitId is identifier of unit
-     * @param ordering is order direction for results, can be ASC or DESC only
-     * @return ResultSet object with positions to defined timestamp, number is limited by range of 1 day ago!!!
-     * @throws SQLException
-     */
-    public ResultSet getPositionsByUserNameDayBefore(String user_name, String toTime, long unitId, String ordering) throws SQLException {
-        if(toTime !=null){
-            String pos_table =  SQLExecutor.getUnitsPositions_table();
-            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
-                    + "FROM "+pos_table+" "
-                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
-                        + "AND time_stamp >= '"+toTime+"'::timestamp - '1 day'::interval AND time_stamp < '"+toTime+"' "
-                        + "ORDER BY time_stamp "+ordering+";";
-
-            return stmt.executeQuery(query);
-        } else{
-            throw new SQLException("Parameter toTime was not defined!");
-        }
-    }
-    
-    /**
-     * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
-     * @param user_name is String username of logged user 
-     * @param fromTime is timestamp of the beginning
-     * @param toTime is timestamp of the end of range
-     * @param unitId is identifier of unit
-     * @param ordering is order direction for results, can be ASC or DESC only
-     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
-     * @throws SQLException
-     */
-    public ResultSet getPositionsByUserNameDuringRange(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
-        if(fromTime !=null && toTime !=null){
-            String pos_table =  SQLExecutor.getUnitsPositions_table();
-            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
-                    + "FROM "+pos_table+" "
-                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
-                        + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"' "
-                        + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
-
-            return stmt.executeQuery(query);
-        } else{
-            throw new SQLException("Parameters fromTime and toTime were not defined!");
-        }
-    }
-    
-    /**
-     * Method returns positions of given unit for defined user collected during defined timestamp parameter, 
-     * modified for case of identical fromTime and toTime value
-     * @param user_name is String username of logged user 
-     * @param fromTime is timestamp of the beginning of range
-     * @param toTime is timestamp of the end of range
-     * @param unitId is identifier of unit
-     * @param ordering is order direction for results, can be ASC or DESC only
-     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
-     * @throws SQLException
-     */
-    public ResultSet getPositionsByUserNameDuringDay(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
-        if(fromTime !=null && toTime !=null){
-            if(fromTime.equalsIgnoreCase(toTime)){
-                String pos_table =  SQLExecutor.getUnitsPositions_table();
-                String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
-                        + "FROM "+pos_table+" "
-                        + "WHERE "+pos_table+".unit_id = " + unitId + " "
-                            + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"'::timestamp + '1 day'::interval "
-                            + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
-                return stmt.executeQuery(query);
-            } else{
-                throw new SQLException("Parameters was not correctly defined!");
-            }
-        } else{
-            throw new SQLException("Parameter toTime was not defined!");
-        }
-    }
-    
-    /**
-     * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
-     * @param user_name user_name is String username of logged user 
-     * @param fromTime is timestamp of the beginning
-     * @param toTime is timestamp of the end of range
-     * @param unitId is identifier of unit
-     * @param ordering is order direction for results, can be ASC or DESC only
-     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows or to 1 day of collecting!!!
-     * @throws SQLException
-     */
-    public ResultSet getPositionsTimeRangeByUserName(String user_name, String fromTime, String toTime, Long unitId, String ordering) throws SQLException{
-        ResultSet res;
-        if(fromTime != null && toTime == null && unitId != null){
-            if(!fromTime.isEmpty()){
-                res = getPositionsByUserNameInDay(user_name, fromTime, unitId, ordering);
-            } else{
-                throw new SQLException("Wrong content of parameter from!");
-            }
-        } else if(fromTime == null && toTime != null && unitId != null){
-            if(!toTime.isEmpty()){
-                res = getPositionsByUserNameDayBefore(user_name, toTime, unitId, ordering);
-            } else{
-                throw new SQLException("Wrong content of parameter to!");
-            }
-        } else if(fromTime != null && toTime != null && unitId != null){
-            if(!fromTime.isEmpty() && !toTime.isEmpty()){
-                if(fromTime.equalsIgnoreCase(toTime)){
-                    res = getPositionsByUserNameDuringDay(user_name, fromTime, toTime, unitId, ordering);
-                } else{
-                    res = getPositionsByUserNameDuringRange(user_name, fromTime, toTime, unitId, ordering);
-                }
-            } else{
-                throw new SQLException("Wrong content of parameters from and to!");
-            }
-        } else{
-            throw new SQLException("Wrong combination of parameters from and to!");
-        }
-        return res;
-    }
+package cz.hsrs.db.util;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+import cz.hsrs.db.model.NoItemFoundException;
+import cz.hsrs.db.model.Unit;
+import cz.hsrs.db.model.UnitPosition;
+import cz.hsrs.db.model.composite.LastPosition;
+import cz.hsrs.db.pool.SQLExecutor;
+
+/**
+ * @author jezekjan
+ */
+public class UserUtil extends GroupUtil {
+
+    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
+
+    public UserUtil() {}
+
+    public String getUserLanguage(String user_name) throws SQLException, NoItemFoundException {
+        String select = "SELECT lang FROM system_users WHERE user_name = '"+user_name+"'";
+        ResultSet res = stmt.executeQuery(select);
+        if (res.next()) {
+            return res.getString(1);
+        } else
+            throw new NoItemFoundException("getUserLanguage " + user_name + " not found.");
+    }
+
+    public int getUserId(String userName) throws NoItemFoundException, SQLException{
+        String query = "SELECT user_id FROM system_users WHERE user_name = '"+userName+"';";
+        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+        if(res.next()){
+            return res.getInt(1);
+        } else{
+            throw new NoItemFoundException("User with given " + userName + " was not found.");
+        }
+    }
+
+    public int setUserLanguage(String user_name, String newLang) throws SQLException{
+        String query = "UPDATE system_users SET lang = '"+newLang+"' WHERE user_name = '"+user_name+"';";
+        return SQLExecutor.executeUpdate(query);
+    }
+    
+    public boolean getAudio(String user_name) throws SQLException, NoItemFoundException {
+        String select = "SELECT audio FROM system_users WHERE user_name = '"+user_name+"'";
+        ResultSet res = stmt.executeQuery(select);
+        if (res.next()) {
+            return res.getBoolean(1);
+        } else
+            throw new NoItemFoundException("getAudio " + user_name + " not found.");
+    }
+    @SuppressWarnings("unchecked")
+    public List<UnitPosition> getLastPositionsByUserName(String user_name) throws SQLException {
+        return (List<UnitPosition>) generateObjectList(new UnitPosition(), getLastPositionsByUserNameRes(user_name));
+    }
+    
+    @Deprecated
+    public String getRole(String user_name) throws SQLException, NoItemFoundException{
+        String query = "SELECT user_role FROM rights, system_users WHERE " +
+                "system_users.user_name = '"+user_name + "' AND "+
+                "system_users.rights_id = rights.rights_id";
+        ResultSet res = stmt.executeQuery(query);
+        if (res.next()) {
+            return res.getString(1);
+        } else
+            throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
+    }
+    
+    /**
+     * Method select groupId of given user
+     * @return groupId as int or null if there is not any user with given userName
+     */
+    public static Integer getUserGroupId(String userName) throws SQLException{
+        String query = "SELECT group_id FROM system_users WHERE user_name ='"+userName+"';";
+        ResultSet res = SQLExecutor.getInstance().executeQuery(query);
+        return res.next() ? res.getInt(1) : null;
+    }
+
+    @SuppressWarnings("unchecked")
+    public List<LastPosition> getLastPositionWithStatus(String user_name) throws SQLException {
+        List<LastPosition> lastPositions = new ArrayList<>();
+        List<UnitPosition> positions = (List<UnitPosition>) generateObjectList(
+                new UnitPosition(), getLastPositionsByUserNameRes(user_name));
+
+        for (UnitPosition pos : positions) {
+            lastPositions.add((new UnitUtil()).getLastPositionWithStatus(pos));
+        }
+        return lastPositions;
+    }
+
+    /**
+     * Methods selects last positions of units for given user
+     * @param user_name - name of user
+     * @return ResultSet containing lastUnitPositions
+     * @throws SQLException
+     */
+    public ResultSet getLastPositionsByUserNameRes(String user_name) throws SQLException {
+        /** 
+         * SELECT last_units_positions.gid, st_astext(the_geom), last_units_positions.unit_id, last_units_positions.time_stamp
+         * FROM last_units_positions, units_to_groups, system_users 
+         * WHERE system_users.user_name = 'pepa' 
+         * AND system_users.group_id=units_to_groups.group_id 
+         * AND units_to_groups.unit_id =last_units_positions.unit_id ;
+         */
+        String last_pos_table = SQLExecutor.getUnitsLastPositions_table();
+        String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
+                + last_pos_table
+                + ".unit_id, time_stamp, units_to_groups.group_id "
+                + "FROM "
+                + last_pos_table
+                + ", "
+                + "units_to_groups "
+                + " WHERE ("
+                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
+                + ") AND units_to_groups.unit_id = "
+                + last_pos_table
+                + ".unit_id; ";
+        return stmt.executeQuery(queryObservations);
+    }
+
+    /**
+     * Methods selects last positions of given unit for given user
+     * @param user_name - name of user
+     * @param unit_id - ID of unit
+     * @return ResultSet containing lastUnitPosition
+     * @throws SQLException
+     */
+    public ResultSet getLastPositionsByUserNameRes(String user_name, Long unit_id) throws SQLException {
+
+        if (unit_id == null) {
+            return getLastPositionsByUserNameRes(user_name);
+        } else {
+            String last_pos_table = SQLExecutor.getUnitsLastPositions_table();
+            String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
+                    + last_pos_table
+                    + ".unit_id, time_stamp, units_to_groups.group_id "
+                    + "FROM "
+                    + last_pos_table
+                    + ", "
+                    + "units_to_groups "
+                    + " WHERE ("
+                    + this.getWhereStatemant(user_name,
+                            "units_to_groups.group_id")
+                    + ") AND units_to_groups.unit_id = "
+                    + last_pos_table
+                    + ".unit_id AND "
+                    + last_pos_table
+                    + ".unit_id = "
+                    + unit_id;
+
+            return stmt.executeQuery(queryObservations);
+        }
+    }
+
+    /**
+     * Method gets UnitsPositions by user name
+     * @param user_name - name of user
+     * @param limit - limit of positions
+     * @return
+     * @throws SQLException
+     */
+    public ResultSet getPositionsByUserName(String user_name, Integer limit) throws SQLException {
+
+        String sqlLimit = "";
+        if (limit != null) {
+            if (limit == 1) {
+                return getLastPositionsByUserNameRes(user_name);
+            }
+            sqlLimit = "LIMIT " + limit;
+        }
+        String pos_table =  SQLExecutor.getUnitsPositions_table();
+        String queryObservations = "select gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
+                + pos_table
+                + ".unit_id, time_stamp, units_to_groups.group_id  " + "from  "
+                + pos_table + ", units_to_groups " + "WHERE ("
+                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
+                + ") AND units_to_groups.unit_id = " + pos_table + ".unit_id "
+                + " ORDER BY time_stamp DESC " + sqlLimit + " ;";
+
+        return stmt.executeQuery(queryObservations);
+    }
+
+    public ResultSet getTracksByUserName(String user_name, int limit) throws SQLException {
+        /**
+         * select gid, st_astext(the_geom) from units_tracks, units_to_groups,
+         * system_users WHERE system_users.user_name = 'pepa' AND
+         * system_users.group_id= units_to_groups.group_id AND
+         * units_to_groups.unit_id = units_tracks.unit_id ;
+         */
+
+        String tracks_table =  SQLExecutor.getUnitsTracks_table();
+        String queryObservations = "select gid, st_astext(the_geom), "
+                + tracks_table
+                + ".unit_id, track_start, track_end, units_to_groups.group_id "
+                + "from  " + tracks_table + "," + " units_to_groups"
+                + " WHERE ("
+                + this.getWhereStatemant(user_name, "units_to_groups.group_id")
+                + ") AND units_to_groups.unit_id = " + tracks_table
+                + ".unit_id order by track_end desc limit " + limit + "; ";
+
+        return stmt.executeQuery(queryObservations);
+    }
+
+    public String getUserPassword(String user_name) throws SQLException, NoItemFoundException {
+        String queryObservations = "select user_password from system_users WHERE user_name='" + user_name + "';";
+
+        ResultSet res = stmt.executeQuery(queryObservations);
+        if (res.next()) {
+            return res.getString(1);
+        } else
+            throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
+    }
+
+    public int insertUser(String user_name, String pass) throws SQLException {
+        String insert = "insert into system_users(user_name, user_password) Values('" + user_name + "','" + pass + "');";
+        return SQLExecutor.executeUpdate(insert);
+    }
+
+    public int deleteUser(String user_name) throws SQLException {
+        String del = "DELETE FROM system_users WHERE user_name='" + user_name + "';";
+        return SQLExecutor.executeUpdate(del);
+    }
+
+    public int setUserSession(String user_name, String session_id, String IP) throws SQLException {
+        /* try to delete session if exists */
+        delUserSession(session_id);
+        
+        String getUsID = "SELECT user_id FROM system_users WHERE user_name = '" + user_name + "'";
+        ResultSet res = stmt.executeQuery(getUsID);
+        res.next();
+        int user_id = res.getInt(1);
+
+        String insert = "INSERT INTO sessions(session_id, system_user_id, ip) VALUES ("
+        + "'" + session_id + "'," + user_id + ",'" + IP + "')";
+        return SQLExecutor.executeUpdate(insert);
+    }
+
+    public int delUserSession(String session_id) throws SQLException {
+        String insert = "DELETE FROM sessions WHERE session_id ='" + session_id + "'";
+        return SQLExecutor.executeUpdate(insert);
+    }
+    
+    @SuppressWarnings("unchecked")
+    public List<Unit> getUnitsByUser(String user_name) throws SQLException{
+        String query = "SELECT u.unit_id, u.holder_id, u.description " +
+                "FROM units u, units_to_groups utg, system_users su " +
+                "WHERE su.user_name = '"+user_name+"' " +
+                "AND su.group_id = utg.group_id " +
+                "AND utg.unit_id = u.unit_id;";
+        ResultSet res = stmt.executeQuery(query);
+        return (List<Unit>)generateObjectList(new Unit(), res);
+    }
+
+    public SimpleDateFormat getDateFormater() {
+        return FORMATTER;
+    }
+
+    /**
+     * Method returns positions of units in all groups for defined user collected in day defined by timeStamp parameter
+     * @param user_name is String username of logged user 
+     * @param timeStamp is day for which positions should be found
+     * @return ResultSet object with positions during one defined day
+     * @throws SQLException 
+     */
+    public ResultSet getPositionsByUserNameInDay2(String user_name, String timeStamp) throws SQLException {
+        if(timeStamp !=null){
+            String pos_table =  SQLExecutor.getUnitsPositions_table();
+            String query = "SELECT gid, "+pos_table+".unit_id, units_to_groups.group_id, "
+                    + "time_stamp, speed, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
+                    + "FROM "+pos_table+", units_to_groups "
+                    + "WHERE ("+this.getWhereStatemant(user_name, "units_to_groups.group_id")+") "
+                        + "AND units_to_groups.unit_id = "+pos_table+".unit_id "
+                        + "AND time_stamp > '"+timeStamp+"' AND time_stamp < timestamp '"+timeStamp+"' + INTERVAL '1 day' "
+                        + "ORDER BY time_stamp DESC;";
+            return stmt.executeQuery(query);
+        } else{
+            throw new SQLException("Parameter timestamp was not defined!");
+        }
+    }
+    
+    /**
+     * Method returns positions of units in all groups for defined user collected from defined timestamp parameter
+     * @param user_name is String username of logged user 
+     * @param fromTime is timestamp of the beginning
+     * @param unitId is identifier of unit
+     * @param ordering is order direction for results, can be ASC or DESC only
+     * @return ResultSet object with positions from defined timestamp, number is limited by range of 1 day!!!
+     * @throws SQLException
+     */
+    public ResultSet getPositionsByUserNameInDay(String user_name, String fromTime, long unitId, String ordering) throws SQLException {
+        if(fromTime != null){
+            String pos_table =  SQLExecutor.getUnitsPositions_table();
+            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
+                    + "FROM "+pos_table+" "
+                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
+                        + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+fromTime+"'::timestamp + '1 day'::interval "
+                        + "ORDER BY time_stamp "+ordering+";";
+
+            return stmt.executeQuery(query);
+        } else{
+            throw new SQLException("Parameter fromTime was not defined!");
+        }
+    }
+    
+    /**
+     * Method returns positions of units in all groups for defined user collected to defined timestamp parameter
+     * @param user_name is String username of logged user 
+     * @param toTime is timestamp of the end of range
+     * @param unitId is identifier of unit
+     * @param ordering is order direction for results, can be ASC or DESC only
+     * @return ResultSet object with positions to defined timestamp, number is limited by range of 1 day ago!!!
+     * @throws SQLException
+     */
+    public ResultSet getPositionsByUserNameDayBefore(String user_name, String toTime, long unitId, String ordering) throws SQLException {
+        if(toTime !=null){
+            String pos_table =  SQLExecutor.getUnitsPositions_table();
+            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
+                    + "FROM "+pos_table+" "
+                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
+                        + "AND time_stamp >= '"+toTime+"'::timestamp - '1 day'::interval AND time_stamp < '"+toTime+"' "
+                        + "ORDER BY time_stamp "+ordering+";";
+
+            return stmt.executeQuery(query);
+        } else{
+            throw new SQLException("Parameter toTime was not defined!");
+        }
+    }
+    
+    /**
+     * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
+     * @param user_name is String username of logged user 
+     * @param fromTime is timestamp of the beginning
+     * @param toTime is timestamp of the end of range
+     * @param unitId is identifier of unit
+     * @param ordering is order direction for results, can be ASC or DESC only
+     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
+     * @throws SQLException
+     */
+    public ResultSet getPositionsByUserNameDuringRange(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
+        if(fromTime !=null && toTime !=null){
+            String pos_table =  SQLExecutor.getUnitsPositions_table();
+            String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
+                    + "FROM "+pos_table+" "
+                    + "WHERE "+pos_table+".unit_id = " + unitId + " "
+                        + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"' "
+                        + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
+
+            return stmt.executeQuery(query);
+        } else{
+            throw new SQLException("Parameters fromTime and toTime were not defined!");
+        }
+    }
+    
+    /**
+     * Method returns positions of given unit for defined user collected during defined timestamp parameter, 
+     * modified for case of identical fromTime and toTime value
+     * @param user_name is String username of logged user 
+     * @param fromTime is timestamp of the beginning of range
+     * @param toTime is timestamp of the end of range
+     * @param unitId is identifier of unit
+     * @param ordering is order direction for results, can be ASC or DESC only
+     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
+     * @throws SQLException
+     */
+    public ResultSet getPositionsByUserNameDuringDay(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
+        if(fromTime !=null && toTime !=null){
+            if(fromTime.equalsIgnoreCase(toTime)){
+                String pos_table =  SQLExecutor.getUnitsPositions_table();
+                String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
+                        + "FROM "+pos_table+" "
+                        + "WHERE "+pos_table+".unit_id = " + unitId + " "
+                            + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"'::timestamp + '1 day'::interval "
+                            + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
+                return stmt.executeQuery(query);
+            } else{
+                throw new SQLException("Parameters was not correctly defined!");
+            }
+        } else{
+            throw new SQLException("Parameter toTime was not defined!");
+        }
+    }
+    
+    /**
+     * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
+     * @param user_name user_name is String username of logged user 
+     * @param fromTime is timestamp of the beginning
+     * @param toTime is timestamp of the end of range
+     * @param unitId is identifier of unit
+     * @param ordering is order direction for results, can be ASC or DESC only
+     * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows or to 1 day of collecting!!!
+     * @throws SQLException
+     */
+    public ResultSet getPositionsTimeRangeByUserName(String user_name, String fromTime, String toTime, Long unitId, String ordering) throws SQLException{
+        ResultSet res;
+        if(fromTime != null && toTime == null && unitId != null){
+            if(!fromTime.isEmpty()){
+                res = getPositionsByUserNameInDay(user_name, fromTime, unitId, ordering);
+            } else{
+                throw new SQLException("Wrong content of parameter from!");
+            }
+        } else if(fromTime == null && toTime != null && unitId != null){
+            if(!toTime.isEmpty()){
+                res = getPositionsByUserNameDayBefore(user_name, toTime, unitId, ordering);
+            } else{
+                throw new SQLException("Wrong content of parameter to!");
+            }
+        } else if(fromTime != null && toTime != null && unitId != null){
+            if(!fromTime.isEmpty() && !toTime.isEmpty()){
+                if(fromTime.equalsIgnoreCase(toTime)){
+                    res = getPositionsByUserNameDuringDay(user_name, fromTime, toTime, unitId, ordering);
+                } else{
+                    res = getPositionsByUserNameDuringRange(user_name, fromTime, toTime, unitId, ordering);
+                }
+            } else{
+                throw new SQLException("Wrong content of parameters from and to!");
+            }
+        } else{
+            throw new SQLException("Wrong combination of parameters from and to!");
+        }
+        return res;
+    }
 }

+ 21 - 13
src/main/java/cz/hsrs/rest/vgi/VgiObservationRest.java

@@ -1,25 +1,33 @@
 package cz.hsrs.rest.vgi;
 
-import com.sun.jersey.core.header.FormDataContentDisposition;
-import com.sun.jersey.multipart.FormDataParam;
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.model.vgi.VgiMedia;
-import cz.hsrs.db.model.vgi.VgiObservation;
-import cz.hsrs.db.vgi.util.VgiParams;
-import cz.hsrs.rest.util.VgiObservationRestUtil;
-import net.sf.json.JSONObject;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.List;
 
 import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.sql.SQLException;
-import java.util.List;
+
+import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
+import org.glassfish.jersey.media.multipart.FormDataParam;
+
+import cz.hsrs.db.model.vgi.VgiMedia;
+import cz.hsrs.db.model.vgi.VgiObservation;
+import cz.hsrs.db.vgi.util.VgiParams;
+import cz.hsrs.rest.util.VgiObservationRestUtil;
+import net.sf.json.JSONObject;
 
 /**
  * Class with services managing VgiObservation objects

+ 18 - 11
src/main/java/cz/hsrs/rest/vgi/VgiRest.java

@@ -1,22 +1,29 @@
 package cz.hsrs.rest.vgi;
 
-import com.sun.jersey.core.header.FormDataContentDisposition;
-import com.sun.jersey.multipart.FormDataParam;
-import cz.hsrs.db.model.vgi.VgiObservation;
-import cz.hsrs.rest.util.BasicAuth;
-import cz.hsrs.rest.util.RestUtil;
-import cz.hsrs.rest.util.VgiObservationRestUtil;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.util.Arrays;
 
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.util.Arrays;
+
+import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
+import org.glassfish.jersey.media.multipart.FormDataParam;
+
+import cz.hsrs.db.model.vgi.VgiObservation;
+import cz.hsrs.rest.util.BasicAuth;
+import cz.hsrs.rest.util.RestUtil;
+import cz.hsrs.rest.util.VgiObservationRestUtil;
 
 @Path("/vgi")
 public class VgiRest {

+ 176 - 171
src/main/java/cz/hsrs/servlet/provider/DBServlet.java

@@ -1,172 +1,177 @@
-package cz.hsrs.servlet.provider;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.sql.SQLException;
-import java.util.Properties;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-import java.util.logging.Level;
-import java.util.logging.LogManager;
-import java.util.logging.Logger;
-
-import javax.naming.AuthenticationException;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import cz.hsrs.db.pool.SQLExecutor;
-import cz.hsrs.db.util.UserUtil;
-import cz.hsrs.servlet.security.JSPHelper;
-import cz.hsrs.servlet.security.LoginUser;
-
-public abstract class DBServlet extends HttpServlet {
-
-    private static final long serialVersionUID = 1L;
-    public static String VERSION;
-    public static String BUILD;
-
-    protected static Logger logger = Logger.getLogger(SQLExecutor.LOGGER_ID);
-
-    @Override
-    public void destroy() {
-        try {
-             SQLExecutor.close();
-        } catch (Exception e) {
-            logger.log(Level.SEVERE, e.getMessage(), e);
-        }
-        super.destroy();
-    }
-
-    public void solveGetException(Exception e, PrintWriter out) throws ServletException {
-        if (e instanceof SQLException) {
-            out.print(e.getMessage());
-        }
-        
-        logger.log(Level.WARNING, e.getMessage(), e);
-        
-        try {
-            logger.log(Level.WARNING, "Going to destroy connections...");
-            logger.log(Level.WARNING,e.getMessage(), e);
-            throw new ServletException("Wrong request ", e);
-        } catch (Exception e1) {
-            e.printStackTrace();
-            logger.log(Level.WARNING, e.getMessage(), e);
-            throw new ServletException(e);
-        }
-    }
-
-    @Override
-    public void init() throws ServletException {
-        setDataBaseConnection();
-
-        try {
-            String conffile = "logging.properties";
-            if (SQLExecutor.getConfigFile()!=null) {
-                conffile  = SQLExecutor.getConfigFile();
-            }
-            FileInputStream fstrem = new FileInputStream(
-                new File(getServletContext().getRealPath("WEB-INF/"+conffile)));
-            LogManager.getLogManager().readConfiguration(fstrem);
-            LogManager.getLogManager().addLogger(logger);
-        
-        } catch (SecurityException | IOException e1) {
-            logger.log(Level.INFO, e1.getMessage());
-        }
-        
-        logger.log(Level.INFO, "Logging inialized Succesefully!");
-        
-        /* get version number */
-        try {
-            String appServerHome = getServletContext().getRealPath("/");
-            File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
-
-            Manifest mf = new Manifest();
-            mf.read(new FileInputStream(manifestFile));
-
-            Attributes atts = mf.getMainAttributes();
-
-            VERSION = atts.getValue("Implementation-Version");
-            BUILD = atts.getValue("Implementation-Build");
-        } catch (IOException e) {
-            logger.log(Level.INFO, e.getMessage());
-        }
-
-        super.init();
-    }
-
-    @Override
-    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
-            throws ServletException, IOException {
-        // TODO Auto-generated method stub
-        req.setCharacterEncoding("UTF-8");
-        resp.setCharacterEncoding("UTF-8");
-    }
-
-    protected void setDataBaseConnection() {
-        String propFile = getServletContext().getRealPath("WEB-INF/database.properties");
-        Properties prop = new Properties();
-        try {
-            prop.load(new FileInputStream(propFile));
-            SQLExecutor.setProperties(prop);
-        } catch (Exception e) {
-            logger.log(Level.SEVERE, e.getMessage(), e);
-        }
-    }
-
-    @Deprecated
-    protected String getAuthenticatedUser(HttpServletRequest request) throws AuthenticationException {
-        LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
-        if (user == null) {
-            if (request.getRemoteHost().equals("127.0.0.1")
-                    && request.getParameter("user") != null) {
-                return request.getParameter("user");
-            } else
-                throw new AuthenticationException(
-                        "Authentication fairlure for request "
-                                + request.getQueryString());
-        }
-        if (user.isAuthenticated()) {
-            return user.getUserName();
-        } else {
-            throw new AuthenticationException(
-                    "Authentication fairlure for request "
-                            + request.getQueryString());
-        }
-    }
-
-    protected LoginUser getAuthenticatedLoginUser(HttpServletRequest request) throws AuthenticationException {
-        LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
-        if(user != null){
-            if (user.isAuthenticated()) {
-                return user;
-            } else {
-                throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
-            }
-        }
-        else{
-            String remoteHost = request.getRemoteHost();
-            if ((remoteHost.equals("127.0.0.1") || remoteHost.equals("localhost")) && request.getParameter("user") != null) {
-                try {
-                    UserUtil uUtil = new UserUtil();
-                    String userName = request.getParameter(JSPHelper.USERATTRIBUTE);
-                    String pass = uUtil.getUserPassword(userName);
-                    LoginUser userLocal = new LoginUser(request);
-
-                    if(userLocal.athenticate(userName, pass)){
-                        return userLocal;
-                    } else{
-                        throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
-                    }
-                } catch (Exception e) {
-                    throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
-                }
-            } else{
-                throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
-            }
-        }
-    }
+package cz.hsrs.servlet.provider;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.SQLException;
+import java.util.Properties;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.Logger;
+
+import javax.naming.AuthenticationException;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cz.hsrs.db.pool.SQLExecutor;
+import cz.hsrs.db.util.UserUtil;
+import cz.hsrs.servlet.security.JSPHelper;
+import cz.hsrs.servlet.security.LoginUser;
+
+public abstract class DBServlet extends HttpServlet {
+
+    private static final long serialVersionUID = 1L;
+    public static String VERSION;
+    public static String BUILD;
+
+    protected static Logger logger = Logger.getLogger(SQLExecutor.LOGGER_ID);
+
+    @Override
+    public void destroy() {
+        try {
+             SQLExecutor.close();
+        } catch (Exception e) {
+            logger.log(Level.SEVERE, e.getMessage(), e);
+        }
+        super.destroy();
+    }
+
+    public void solveGetException(Exception e, PrintWriter out) throws ServletException {
+        if (e instanceof SQLException) {
+            out.print(e.getMessage());
+        }
+        
+        logger.log(Level.WARNING, e.getMessage(), e);
+        
+        try {
+            logger.log(Level.WARNING, "Going to destroy connections...");
+            logger.log(Level.WARNING,e.getMessage(), e);
+            throw new ServletException("Wrong request ", e);
+        } catch (Exception e1) {
+            e.printStackTrace();
+            logger.log(Level.WARNING, e.getMessage(), e);
+            throw new ServletException(e);
+        }
+    }
+
+    @Override
+    public void init() throws ServletException {
+        setDataBaseConnection();
+
+        try {
+            String conffile = "logging.properties";
+            if (SQLExecutor.getConfigFile()!=null) {
+                conffile  = SQLExecutor.getConfigFile();
+            }
+            FileInputStream fstrem = new FileInputStream(
+                new File(getServletContext().getRealPath("WEB-INF/"+conffile)));
+            LogManager.getLogManager().readConfiguration(fstrem);
+            LogManager.getLogManager().addLogger(logger);
+        
+        } catch (SecurityException | IOException e1) {
+            logger.log(Level.INFO, e1.getMessage());
+        }
+        
+        logger.log(Level.INFO, "Logging inialized Succesefully!");
+        
+        /* get version number */
+        try {
+            String appServerHome = getServletContext().getRealPath("/");
+            File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
+
+            Manifest mf = new Manifest();
+            mf.read(new FileInputStream(manifestFile));
+
+            Attributes atts = mf.getMainAttributes();
+
+            VERSION = atts.getValue("Implementation-Version");
+            BUILD = atts.getValue("Implementation-Build");
+        } catch (IOException e) {
+            logger.log(Level.INFO, e.getMessage());
+        }
+
+        super.init();
+    }
+
+    @Override
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
+            throws ServletException, IOException {
+        // TODO Auto-generated method stub
+        req.setCharacterEncoding("UTF-8");
+        resp.setCharacterEncoding("UTF-8");
+    }
+
+    protected void setDataBaseConnection() {
+        String propFile = getServletContext().getRealPath("WEB-INF/database.properties");
+        Properties prop = new Properties();
+        try {
+            prop.load(new FileInputStream(propFile));
+            SQLExecutor.setProperties(prop);
+        } catch (Exception e) {
+            logger.log(Level.SEVERE, e.getMessage(), e);
+        }
+    }
+
+    @Deprecated
+    protected String getAuthenticatedUser(HttpServletRequest request) throws AuthenticationException {
+        LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
+        if (user == null) {
+            if (request.getRemoteHost().equals("127.0.0.1")
+                    && request.getParameter("user") != null) {
+                return request.getParameter("user");
+            } else
+                throw new AuthenticationException(
+                        "Authentication fairlure for request "
+                                + request.getQueryString());
+        }
+        if (user.isAuthenticated()) {
+            return user.getUserName();
+        } else {
+            throw new AuthenticationException(
+                    "Authentication fairlure for request "
+                            + request.getQueryString());
+        }
+    }
+
+    /**
+     * Method provides info about logged user by SessionId in HTTPRequest
+     * @param request - HTTP request containing SESSIONID
+     *
+     */
+    protected LoginUser getAuthenticatedLoginUser(HttpServletRequest request) throws AuthenticationException {
+        LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
+        if(user != null){
+            if (user.isAuthenticated()) {
+                return user;
+            } else {
+                throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
+            }
+        }
+        else{
+            String remoteHost = request.getRemoteHost();
+            if ((remoteHost.equals("127.0.0.1") || remoteHost.equals("localhost")) && request.getParameter("user") != null) {
+                try {
+                    UserUtil uUtil = new UserUtil();
+                    String userName = request.getParameter(JSPHelper.USERATTRIBUTE);
+                    String pass = uUtil.getUserPassword(userName);
+                    LoginUser userLocal = new LoginUser(request);
+
+                    if(userLocal.athenticate(userName, pass)){
+                        return userLocal;
+                    } else{
+                        throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
+                    }
+                } catch (Exception e) {
+                    throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
+                }
+            } else{
+                throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
+            }
+        }
+    }
 }

+ 243 - 235
src/main/java/cz/hsrs/servlet/provider/DataService.java

@@ -1,236 +1,244 @@
-package cz.hsrs.servlet.provider;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.sql.SQLException;
-import java.util.List;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import cz.hsrs.db.DBJsonUtils;
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.model.UnitPosition;
-import cz.hsrs.db.model.UnitTrack;
-import cz.hsrs.db.model.composite.LastPosition;
-import cz.hsrs.db.model.composite.RealUnit;
-import cz.hsrs.db.model.custom.UnitPositionSimple;
-import cz.hsrs.db.util.UtilFactory;
-import cz.hsrs.servlet.feeder.ServiceParameters;
-
-/**
- * Servlet implementation class DataService
- * 
- * http://localhost:8080/DBService/DataService?Operation=GetDataByUserName&user=
- * pepa&limit=100
- */
-public class DataService extends DBServlet {
-
-    private static final long serialVersionUID = 1L;
-
-    private static final String ASC = "ASC";
-    private static final String DESC = "DESC";
-
-    public static final String GET_TRACK = "GetTracks";
-    public static final String GET_LAST_POSTION = "GetLastPositions";
-    public static final String GET_LAST_POSTION_WITH_STATUS = "GetLastPositionsWithStatus";
-    public static final String GET_UNITS = "GetUnits";
-    public static final String GET_RECENT_TRACK = "GetRecentTracks";
-    public static final String GET_POSITIONS = "GetPositions";
-    public static final String GET_POSITIONS_RANGE = "GetPositionsDay";
-    public static final String GET_UNITS_LIST = "GetUnitsList";
-
-    private UtilFactory db;
-
-    public DataService() {
-        super();
-    }
-
-
-    protected void doGet(HttpServletRequest request,
-            HttpServletResponse response) throws ServletException, IOException {
-        super.doGet(request, response);
-        RequestParameters params = new RequestParameters(request);
-        
-        /* For FarmTelemetry purpose only temporary */
-       
-        String user = params.getUser();
-        if(user == null){
-            throw new ServletException("Authentication failure, no user specified for request: "+ request.getQueryString());
-        }
-        else{
-            try {
-                String testLang = db.userUtil.getUserLanguage(user);
-                if(testLang.isEmpty()){
-                    throw new ServletException("Authentication failure for request "+ request.getQueryString());
-                }
-            } catch (SQLException | NoItemFoundException e1) {
-                throw new ServletException("Authentication failure for request "+ request.getQueryString());
-            }
-        }
-
-
-        response.addHeader("Access-Control-Allow-Origin", "*");
-        /*
-         * /DataService?Operation=GetUnits&user=telemetry&unit_id=356173060488215
-         * /DataService?Operation=GetTracks&user=telemetry&limit=500
-         * /DataService?Operation=GetLastPositions&user=telemetry
-         * /DataService?Operation=GetLastPositionsWithStatus&user=telemetry
-         * /DataService?Operation=GetRecentTracks&user=telemetry
-         * /DataService?Operation=GetPositions&user=telemetry&limit=500
-         * /DataService?Operation=GetPositionsDay&user=telemetry&unit_id=356173060488215&fromTime=2016-02-01&toTime=2016-02-04&ordering=desc
-         * /DataService?Operation=GetUnitsList&user=telemetry
-         */
-        PrintWriter out = response.getWriter();
-        try {
-            switch (request.getParameter(ServiceParameters.OPERATION)) {
-                case GET_UNITS: {
-                    DBJsonUtils.writeJSON(out, new RealUnit(), db.userUtil.getLastPositionsByUserNameRes(params.getUser(), params.getUnitId()));
-                } break;
-                case GET_TRACK: {
-                    DBJsonUtils.writeJSON(out, new UnitTrack(), db.userUtil.getTracksByUserName(params.getUser(), params.limit));
-                } break;
-                case GET_LAST_POSTION: {
-                    DBJsonUtils.writeJSON(out, db.userUtil.getLastPositionsByUserName(params.getUser()));
-                } break;
-                case GET_LAST_POSTION_WITH_STATUS: {
-                    List<LastPosition> posList = db.userUtil.getLastPositionWithStatus(params.getUser());
-                    DBJsonUtils.writeJSON(out, posList);
-                } break;
-                case GET_RECENT_TRACK: {
-                    DBJsonUtils.writeJSON(out, new UnitTrack(), db.userUtil.getTracksByUserName(params.getUser(), 1000));
-                } break;
-                case GET_POSITIONS: {
-                    DBJsonUtils.writeJSON(out, new UnitPosition(), db.userUtil.getPositionsByUserName(params.getUser(), params.limit));
-                } break;
-                case GET_POSITIONS_RANGE: {
-                    DBJsonUtils.writeJSON(out, new UnitPositionSimple(), db.userUtil.getPositionsTimeRangeByUserName(params.getUser(), params.fromTime, params.toTime, params.getUnitId(), params.getOrdering()));
-                } break;
-                case GET_UNITS_LIST: {
-                    DBJsonUtils.writeJSON(out, db.userUtil.getUnitsByUser(params.getUser()));
-                } break;
-                default:
-                    throw new NullPointerException("No operation specified.");
-            }
-        } catch (SQLException e) {
-            solveGetException(e, out);
-        }
-    }
-
-    @Override
-    public void init() throws ServletException {
-        super.init();
-        
-        try {
-            db = new UtilFactory();
-        } catch (Exception e) {
-            throw new ServletException(e);
-        }
-    }
-    
-
-    /**
-     * Request Parameter subclass
-     * Parses parameter from the request
-     * @author jezekjan
-     *
-     */
-    static class RequestParameters {
-        private String user;
-        private String fromTime;
-        private String toTime;
-        private Integer limit;
-        private Long unitId;
-        private String ordering;
-
-        RequestParameters(HttpServletRequest request) throws NullPointerException{
-            Object userO = request.getParameter("user");
-            if(userO != null){
-                user = userO.toString();
-            }
-            Object limO = request.getParameter("limit");
-            if (limO != null) {
-                limit = Integer.parseInt(limO.toString());
-            }
-
-            Object fromTimeO = request.getParameter("fromTime");
-            if (fromTimeO != null) {
-                fromTime = fromTimeO.toString();
-            }
-            Object toTimeO = request.getParameter("toTime");
-            if (toTimeO != null) {
-                toTime = toTimeO.toString();
-            }
-            Object orderingO = request.getParameter("ordering");
-            if (orderingO != null) {
-                String orderingS = orderingO.toString();
-                if(orderingS.isEmpty()){
-                    ordering = ASC;
-                } else{
-                    ordering = orderingS.equalsIgnoreCase(DESC) ? DESC : ASC;
-                }
-            }else{
-                ordering = ASC;
-            }
-            Object unitO = request.getParameter("unit_id");
-            unitId = unitO != null ? Long.parseLong(unitO.toString()) : null;
-        }
-
-        public Long getUnitId() {
-            return unitId;
-        }
-
-        public void setUnitId(long unitId) {
-            this.unitId = unitId;
-        }
-        
-        public String getUser() {
-            return user;
-        }
-
-        public void setUser(String user) {
-            this.user = user;
-        }
-
-        public Integer getLimit() {
-            return limit;
-        }
-
-        public void setLimit(Integer limit) {
-            this.limit = limit;
-        }
-
-        public String getFromTime() {
-            return fromTime;
-        }
-
-        public void setFromTime(String fromTime) {
-            this.fromTime = fromTime;
-        }
-
-        public String getToTime() {
-            return toTime;
-        }
-
-        public void setToTime(String toTime) {
-            this.toTime = toTime;
-        }
-
-        public String getOrdering() {
-            return ordering;
-        }
-
-        public void setOrdering(String ordering) {
-            this.ordering = ordering;
-        }
-
-        @Override
-        public String toString() {
-            return "RequestParameters [user=" + user + ", fromTime=" + fromTime
-                    + ", toTime=" + toTime + ", limit=" + limit + ", unit_id="
-                    + unitId + ", ordering=" + ordering + "]";
-        }
-    }
+package cz.hsrs.servlet.provider;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.SQLException;
+import java.util.List;
+
+import javax.naming.AuthenticationException;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cz.hsrs.db.DBJsonUtils;
+import cz.hsrs.db.model.UnitPosition;
+import cz.hsrs.db.model.UnitTrack;
+import cz.hsrs.db.model.composite.LastPosition;
+import cz.hsrs.db.model.composite.RealUnit;
+import cz.hsrs.db.model.custom.UnitPositionSimple;
+import cz.hsrs.db.util.UtilFactory;
+import cz.hsrs.servlet.feeder.ServiceParameters;
+import cz.hsrs.servlet.security.LoginUser;
+
+/**
+ * Servlet implementation class DataService
+ * 
+ * /DataService?Operation=GetDataByUserName&user=pepa&limit=100
+ */
+public class DataService extends DBServlet {
+
+    private static final long serialVersionUID = 1L;
+
+    private static final String ASC = "ASC";
+    private static final String DESC = "DESC";
+
+    public static final String GET_TRACK = "GetTracks";
+    public static final String GET_LAST_POSTION = "GetLastPositions";
+    public static final String GET_LAST_POSTION_WITH_STATUS = "GetLastPositionsWithStatus";
+    public static final String GET_UNITS = "GetUnits";
+    public static final String GET_RECENT_TRACK = "GetRecentTracks";
+    public static final String GET_POSITIONS = "GetPositions";
+    public static final String GET_POSITIONS_RANGE = "GetPositionsDay";
+    public static final String GET_UNITS_LIST = "GetUnitsList";
+
+    private UtilFactory db;
+
+    public DataService() {
+        super();
+    }
+
+
+    protected void doGet(HttpServletRequest request,
+            HttpServletResponse response) throws ServletException, IOException {
+        super.doGet(request, response);
+        RequestParameters params = new RequestParameters(request);
+        
+        /* For FarmTelemetry purpose only temporary */
+/*       
+        String user = params.getUser();
+        if(user == null){
+            throw new ServletException("Authentication failure, no user specified for request: "+ request.getQueryString());
+        }
+        else{
+            try {
+                String testLang = db.userUtil.getUserLanguage(user);
+                if(testLang.isEmpty()){
+                    throw new ServletException("Authentication failure for request "+ request.getQueryString());
+                }
+            } catch (SQLException | NoItemFoundException e1) {
+                throw new ServletException("Authentication failure for request "+ request.getQueryString());
+            }
+        }
+*/
+        /* session login method */
+        LoginUser loggedUser;
+        try {
+            loggedUser = getAuthenticatedLoginUser(request);
+            String userName = loggedUser.getUserName();
+            params.setUser(userName);
+        } catch (AuthenticationException e1) {
+            throw new ServletException("Authentication failure for request "+ request.getQueryString());
+        }
+
+        response.addHeader("Access-Control-Allow-Origin", "*");
+        /*
+         * /DataService?Operation=GetUnits&user=telemetry&unit_id=356173060488215
+         * /DataService?Operation=GetTracks&user=telemetry&limit=500
+         * /DataService?Operation=GetLastPositions&user=telemetry
+         * /DataService?Operation=GetLastPositionsWithStatus&user=telemetry
+         * /DataService?Operation=GetRecentTracks&user=telemetry
+         * /DataService?Operation=GetPositions&user=telemetry&limit=500
+         * /DataService?Operation=GetPositionsDay&user=telemetry&unit_id=356173060488215&fromTime=2016-02-01&toTime=2016-02-04&ordering=desc
+         * /DataService?Operation=GetUnitsList&user=telemetry
+         */
+        PrintWriter out = response.getWriter();
+        try {
+            switch (request.getParameter(ServiceParameters.OPERATION)) {
+                case GET_UNITS: {
+                    DBJsonUtils.writeJSON(out, new RealUnit(), db.userUtil.getLastPositionsByUserNameRes(params.getUser(), params.getUnitId()));
+                } break;
+                case GET_TRACK: {
+                    DBJsonUtils.writeJSON(out, new UnitTrack(), db.userUtil.getTracksByUserName(params.getUser(), params.limit));
+                } break;
+                case GET_LAST_POSTION: {
+                    DBJsonUtils.writeJSON(out, db.userUtil.getLastPositionsByUserName(params.getUser()));
+                } break;
+                case GET_LAST_POSTION_WITH_STATUS: {
+                    List<LastPosition> posList = db.userUtil.getLastPositionWithStatus(params.getUser());
+                    DBJsonUtils.writeJSON(out, posList);
+                } break;
+                case GET_RECENT_TRACK: {
+                    DBJsonUtils.writeJSON(out, new UnitTrack(), db.userUtil.getTracksByUserName(params.getUser(), 1000));
+                } break;
+                case GET_POSITIONS: {
+                    DBJsonUtils.writeJSON(out, new UnitPosition(), db.userUtil.getPositionsByUserName(params.getUser(), params.limit));
+                } break;
+                case GET_POSITIONS_RANGE: {
+                    DBJsonUtils.writeJSON(out, new UnitPositionSimple(), db.userUtil.getPositionsTimeRangeByUserName(params.getUser(), params.fromTime, params.toTime, params.getUnitId(), params.getOrdering()));
+                } break;
+                case GET_UNITS_LIST: {
+                    DBJsonUtils.writeJSON(out, db.userUtil.getUnitsByUser(params.getUser()));
+                } break;
+                default:
+                    throw new NullPointerException("No operation specified.");
+            }
+        } catch (SQLException e) {
+            solveGetException(e, out);
+        }
+    }
+
+    @Override
+    public void init() throws ServletException {
+        super.init();
+        
+        try {
+            db = new UtilFactory();
+        } catch (Exception e) {
+            throw new ServletException(e);
+        }
+    }
+    
+
+    /**
+     * Request Parameter subclass
+     * Parses parameter from the request
+     * @author jezekjan
+     *
+     */
+    static class RequestParameters {
+        private String user;
+        private String fromTime;
+        private String toTime;
+        private Integer limit;
+        private Long unitId;
+        private String ordering;
+
+        RequestParameters(HttpServletRequest request) throws NullPointerException{
+            Object userO = request.getParameter("user");
+            if(userO != null){
+                user = userO.toString();
+            }
+            Object limO = request.getParameter("limit");
+            if (limO != null) {
+                limit = Integer.parseInt(limO.toString());
+            }
+
+            Object fromTimeO = request.getParameter("fromTime");
+            if (fromTimeO != null) {
+                fromTime = fromTimeO.toString();
+            }
+            Object toTimeO = request.getParameter("toTime");
+            if (toTimeO != null) {
+                toTime = toTimeO.toString();
+            }
+            Object orderingO = request.getParameter("ordering");
+            if (orderingO != null) {
+                String orderingS = orderingO.toString();
+                if(orderingS.isEmpty()){
+                    ordering = ASC;
+                } else{
+                    ordering = orderingS.equalsIgnoreCase(DESC) ? DESC : ASC;
+                }
+            }else{
+                ordering = ASC;
+            }
+            Object unitO = request.getParameter("unit_id");
+            unitId = unitO != null ? Long.parseLong(unitO.toString()) : null;
+        }
+
+        public Long getUnitId() {
+            return unitId;
+        }
+
+        public void setUnitId(long unitId) {
+            this.unitId = unitId;
+        }
+        
+        public String getUser() {
+            return user;
+        }
+
+        public void setUser(String user) {
+            this.user = user;
+        }
+
+        public Integer getLimit() {
+            return limit;
+        }
+
+        public void setLimit(Integer limit) {
+            this.limit = limit;
+        }
+
+        public String getFromTime() {
+            return fromTime;
+        }
+
+        public void setFromTime(String fromTime) {
+            this.fromTime = fromTime;
+        }
+
+        public String getToTime() {
+            return toTime;
+        }
+
+        public void setToTime(String toTime) {
+            this.toTime = toTime;
+        }
+
+        public String getOrdering() {
+            return ordering;
+        }
+
+        public void setOrdering(String ordering) {
+            this.ordering = ordering;
+        }
+
+        @Override
+        public String toString() {
+            return "RequestParameters [user=" + user + ", fromTime=" + fromTime
+                    + ", toTime=" + toTime + ", limit=" + limit + ", unit_id="
+                    + unitId + ", ordering=" + ordering + "]";
+        }
+    }
 }

+ 21 - 11
src/main/java/cz/hsrs/servlet/provider/ManagementService.java

@@ -3,15 +3,17 @@ package cz.hsrs.servlet.provider;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.sql.SQLException;
 
+import javax.naming.AuthenticationException;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.core.HttpHeaders;
 
-import cz.hsrs.db.DBJsonUtils;
-import cz.hsrs.db.model.UnitTrack;
+import cz.hsrs.db.model.insert.UnitInsert;
+import cz.hsrs.db.util.UtilFactory;
+import cz.hsrs.servlet.feeder.ServiceParameters;
+import cz.hsrs.servlet.security.LoginUser;
 import net.sf.json.JSON;
 import net.sf.json.JSONException;
 import net.sf.json.JSONObject;
@@ -19,11 +21,6 @@ import net.sf.json.JSONSerializer;
 import net.sf.json.JsonConfig;
 import net.sf.json.util.CycleDetectionStrategy;
 
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.model.insert.UnitInsert;
-import cz.hsrs.db.util.UtilFactory;
-import cz.hsrs.servlet.feeder.ServiceParameters;
-
 /**
  * @author mkepka
  *
@@ -56,7 +53,7 @@ public class ManagementService extends DBServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
         RequestParameters params = new RequestParameters(request);
-        String user = params.getUSER();
+        /*
         if(user == null){
             throw new ServletException("Authentication failure, no user specified for request: "+ request.getQueryString());
         }
@@ -69,8 +66,18 @@ public class ManagementService extends DBServlet {
             } catch (SQLException | NoItemFoundException e1) {
                 throw new ServletException("Authentication failure for request "+ request.getQueryString());
             }
-        }
+        }*/
         
+        /* session login method */
+        LoginUser loggedUser;
+        try {
+            loggedUser = getAuthenticatedLoginUser(request);
+            String userName = loggedUser.getUserName();
+            params.setUser(userName);
+        } catch (AuthenticationException e1) {
+            throw new ServletException("Authentication failure for request "+ request.getQueryString());
+        }
+        String user = params.getUSER();
         /* Setting response headers */
         response.addHeader("Access-Control-Allow-Origin", "*");
         
@@ -123,7 +130,7 @@ public class ManagementService extends DBServlet {
 
 
     static class RequestParameters {
-        private final String user;
+        private String user;
         
         RequestParameters(HttpServletRequest request) throws NullPointerException{
             Object userO = request.getParameter("user");
@@ -133,5 +140,8 @@ public class ManagementService extends DBServlet {
         public String getUSER() {
             return user;
         }
+        public void setUser(String user) {
+            this.user = user;
+        }
     }
 }

+ 209 - 187
src/main/java/cz/hsrs/servlet/provider/SensorService.java

@@ -1,188 +1,210 @@
-package cz.hsrs.servlet.provider;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.sql.SQLException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.HttpHeaders;
-
-import cz.hsrs.db.DBJsonUtils;
-import cz.hsrs.db.model.NoItemFoundException;
-import cz.hsrs.db.util.UtilFactory;
-import cz.hsrs.servlet.feeder.ServiceParameters;
-
-public class SensorService extends DBServlet {
-
-    private static final long serialVersionUID = 1L;
-
-    public static final String GET_SENSORS = "GetSensors";
-    public static final String GET_OBSERVATIONS = "GetObservations";
-    public static final String GET_LAST_OBSERVATIONS = "GetLastObservations";
-
-    private UtilFactory db;
-
-    public void init() throws ServletException {
-        super.init();
-        
-        try {
-            db = new UtilFactory();
-        } catch (Exception e) {
-            throw new ServletException(e);
-        }
-    }
-
-    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-        super.doGet(request, response);
-        RequestParameters params = new RequestParameters(request);
-
-        if(params.getUser() == null){
-            throw new ServletException("Authentication failure, no user specified for request: "+ request.getQueryString());
-        } else{
-            try {
-                String testLang = db.userUtil.getUserLanguage(params.getUser());
-                if(testLang.isEmpty()){
-                    throw new ServletException("Authentication failure for request "+ request.getQueryString());
-                }
-            } catch (SQLException | NoItemFoundException e1) {
-                throw new ServletException("Authentication failure for request "+ request.getQueryString());
-            }
-        }
-        response.addHeader("Access-Control-Allow-Origin", "*");
-        response.addHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
-
-        /*
-         * /SensorService?Operation=GetSensors&user=meteor&unit_id=104200002
-         * /SensorService?Operation=GetObservations&user=meteor&unit_id=104200002&sensor_id=&fromTime=2016-02-01&toTime=2016-02-04&trunc=day
-         * /SensorService?Operation=GetObservations&user=meteor&unit_id=104200002&sensor_id=&fromTime=2016-02-01&toTime=2016-02-04
-         * /SensorService?Operation=GetLastObservations&user=meteor&unit_id=104200002&sensor_id=690020001
-         * /SensorService?Operation=GetLastObservations&user=meteor&unit_id=104200002
-         * /SensorService?Operation=GetLastObservations&user=meteor&group=meteo2
-         * /SensorService?Operation=GetLastObservations&user=meteor&group=meteo2&sensor_id=690020001
-         */
-        PrintWriter out = response.getWriter();
-        try {
-            /* GetSensors */
-            if (request.getParameter(ServiceParameters.OPERATION).equals(GET_SENSORS)) {
-                boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
-                if(isAffiliated){
-                    DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensors(params.getUnitId()));
-                } else{
-                    throw new SQLException("Specified unit does not exist in any group of given user!");
-                }
-            /* GetObservations */
-            } else if (request.getParameter(ServiceParameters.OPERATION).equals(GET_OBSERVATIONS)) {
-                boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
-                if(isAffiliated){
-                    /* Pokud je dan trunc */
-                    if (params.trunc != null) {
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorObservationsTrunc(
-                                params.getUnitId(), params.getSensorId(), params.from, params.to, params.trunc));
-                    } else {
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorObservations(
-                                params.getUnitId(), params.getSensorId(), params.from, params.to));
-                    }
-                } else{
-                    throw new SQLException("Specified unit does not exist in any group of given user!");
-                }
-            /* GetLastObservations */
-            } else if(request.getParameter(ServiceParameters.OPERATION).equals(GET_LAST_OBSERVATIONS)){
-                if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() != 0){
-                    boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
-                    if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorLastObservation(params.getUnitId(), params.getSensorId()));
-                    } else{
-                        throw new SQLException("Specified unit does not exist in any group of given user!");
-                    }
-                } else if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() == 0){
-                    boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
-                    if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitSensorsLastObservations(params.getUnitId()));
-                    } else{
-                        throw new SQLException("Specified unit does not exist in any group of given user!");
-                    }
-                } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() == 0){
-                    boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
-                    if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup()));
-                    } else{
-                        throw new SQLException("Specified unit does not exist in any group of given user!");
-                    }
-                } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() != 0){
-                    boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
-                    if(isAffiliated){
-                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup(), params.getSensorId()));
-                    } else{
-                        throw new SQLException("Specified unit does not exist in any group of given user!");
-                    }
-                } else{
-                    throw new ServletException("Wrong combination of parameters "+ request.getQueryString());
-                }
-            } else {
-                throw new ServletException("Wrong request "+ request.getQueryString());
-            }
-        } catch (SQLException e) {
-            super.solveGetException(e, out);
-        }
-    }
-
-    static class RequestParameters {
-        private String user;
-        private final String group;
-        private final long unitId;
-        private final long sensorId;
-        private final String from;
-        private final String to;
-        private final String trunc;
-
-        RequestParameters(HttpServletRequest request) throws NullPointerException {
-            Object uid = request.getParameter("unit_id");
-            this.unitId = uid != null ? Long.parseLong(uid.toString()) : 0;
-
-            Object sid = request.getParameter("sensor_id");
-            this.sensorId = sid != null ? Long.parseLong(sid.toString()) : 0;
-
-            Object tr = request.getParameter("trunc");
-            this.trunc = tr != null ? tr.toString() : null;
-
-            Object fro =  request.getParameter("from");
-            this.from = fro != null ? fro.toString() : "1900-01-01 00:00:00+01";
-
-            Object too =  request.getParameter("to");
-            this.to = too != null ? too.toString() : "3000-01-01 00:00:00+01";
-
-            Object userO = request.getParameter("user");
-            this.user = userO != null ? userO.toString() : null;
-
-            Object groupO = request.getParameter("group");
-            this.group = groupO != null ? groupO.toString() : null;
-        }
-
-        public long getUnitId() {
-            return unitId;
-        }
-        public long getSensorId() {
-            return sensorId;
-        }
-        public String getFromTime() {
-            return from;
-        }
-        public String getToTime() {
-            return to;
-        }
-        public String getTrunc() {
-            return trunc;
-        }
-        public String getUser() {
-            return user;
-        }
-        public void setUser(String user) {
-            this.user = user;
-        }
-        public String getGroup() {
-            return group;
-        }
-    }
+package cz.hsrs.servlet.provider;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.SQLException;
+
+import javax.naming.AuthenticationException;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.HttpHeaders;
+
+import cz.hsrs.db.DBJsonUtils;
+import cz.hsrs.db.util.UtilFactory;
+import cz.hsrs.servlet.feeder.ServiceParameters;
+import cz.hsrs.servlet.security.LoginUser;
+
+public class SensorService extends DBServlet {
+
+    private static final long serialVersionUID = 1L;
+
+    public static final String GET_SENSORS = "GetSensors";
+    public static final String GET_ALL_SENSORS = "GetAllSensors";
+    public static final String GET_ALL_PHENOMENONS = "GetAllPhenomenons";
+    public static final String GET_OBSERVATIONS = "GetObservations";
+    public static final String GET_LAST_OBSERVATIONS = "GetLastObservations";
+
+    private UtilFactory db;
+
+    public void init() throws ServletException {
+        super.init();
+        
+        try {
+            db = new UtilFactory();
+        } catch (Exception e) {
+            throw new ServletException(e);
+        }
+    }
+
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        super.doGet(request, response);
+        RequestParameters params = new RequestParameters(request);
+        
+        /* session login method */
+        LoginUser loggedUser;
+        try {
+            loggedUser = getAuthenticatedLoginUser(request);
+            String userName = loggedUser.getUserName();
+            params.setUser(userName);
+        } catch (AuthenticationException e1) {
+            throw new ServletException("Authentication failure for request "+ request.getQueryString());
+        }
+        
+        /* Simple TESTING auth method */
+        /*
+        if(params.getUser() == null){
+            throw new ServletException("Authentication failure, no user specified for request: "+ request.getQueryString());
+        } else{
+            try {
+                String testLang = db.userUtil.getUserLanguage(params.getUser());
+                if(testLang.isEmpty()){
+                    throw new ServletException("Authentication failure for request "+ request.getQueryString());
+                }
+            } catch (SQLException | NoItemFoundException e1) {
+                throw new ServletException("Authentication failure for request "+ request.getQueryString());
+            }
+        }
+        */
+        response.addHeader("Access-Control-Allow-Origin", "*");
+        response.addHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
+
+        /*
+         * /SensorService?Operation=GetSensors&user=meteor&unit_id=104200002
+         * /SensorService?Operation=GetObservations&user=meteor&unit_id=104200002&sensor_id=&fromTime=2016-02-01&toTime=2016-02-04&trunc=day
+         * /SensorService?Operation=GetObservations&user=meteor&unit_id=104200002&sensor_id=&fromTime=2016-02-01&toTime=2016-02-04
+         * /SensorService?Operation=GetLastObservations&user=meteor&unit_id=104200002&sensor_id=690020001
+         * /SensorService?Operation=GetLastObservations&user=meteor&unit_id=104200002
+         * /SensorService?Operation=GetLastObservations&user=meteor&group=meteo2
+         * /SensorService?Operation=GetLastObservations&user=meteor&group=meteo2&sensor_id=690020001
+         */
+        PrintWriter out = response.getWriter();
+        try {
+            /* GetSensors */
+            if (request.getParameter(ServiceParameters.OPERATION).equals(GET_SENSORS)) {
+                boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
+                if(isAffiliated){
+                    DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensors(params.getUnitId()));
+                } else{
+                    throw new SQLException("Specified unit does not exist in any group of given user!");
+                }
+                /* Get All Sensors */
+            } else if (request.getParameter(ServiceParameters.OPERATION).equalsIgnoreCase(GET_ALL_SENSORS)) {
+            	DBJsonUtils.writeJSON(out,db.sensorUtil.getSensors());
+            /* GetAllPhenomenons */
+            } else if (request.getParameter(ServiceParameters.OPERATION).equalsIgnoreCase(GET_ALL_PHENOMENONS)) {
+            	DBJsonUtils.writeJSON(out,db.sensorUtil.getPhenomenons());
+            /* GetObservations */
+            } else if (request.getParameter(ServiceParameters.OPERATION).equals(GET_OBSERVATIONS)) {
+                boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
+                if(isAffiliated){
+                    /* Pokud je dan trunc */
+                    if (params.trunc != null) {
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorObservationsTrunc(
+                                params.getUnitId(), params.getSensorId(), params.from, params.to, params.trunc));
+                    } else {
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorObservations(
+                                params.getUnitId(), params.getSensorId(), params.from, params.to));
+                    }
+                } else{
+                    throw new SQLException("Specified unit does not exist in any group of given user!");
+                }
+            /* GetLastObservations */
+            } else if(request.getParameter(ServiceParameters.OPERATION).equals(GET_LAST_OBSERVATIONS)){
+                if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() != 0){
+                    boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
+                    if(isAffiliated){
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getSensorLastObservation(params.getUnitId(), params.getSensorId()));
+                    } else{
+                        throw new SQLException("Specified unit does not exist in any group of given user!");
+                    }
+                } else if(params.getGroup() == null && params.getUnitId() != 0 && params.getSensorId() == 0){
+                    boolean isAffiliated = db.analystUtil.checkUnitAffiliation2User(params.getUser(), params.getUnitId());
+                    if(isAffiliated){
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitSensorsLastObservations(params.getUnitId()));
+                    } else{
+                        throw new SQLException("Specified unit does not exist in any group of given user!");
+                    }
+                } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() == 0){
+                    boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
+                    if(isAffiliated){
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup()));
+                    } else{
+                        throw new SQLException("Specified unit does not exist in any group of given user!");
+                    }
+                } else if(params.getGroup() != null && params.getUnitId() == 0 && params.getSensorId() != 0){
+                    boolean isAffiliated = db.groupUtil.checkGroupAffiliation2User(params.getUser(), params.getGroup());
+                    if(isAffiliated){
+                        DBJsonUtils.writeJSON(out, db.sensorUtil.getUnitsSensorsLastObservations(params.getGroup(), params.getSensorId()));
+                    } else{
+                        throw new SQLException("Specified unit does not exist in any group of given user!");
+                    }
+                } else{
+                    throw new ServletException("Wrong combination of parameters "+ request.getQueryString());
+                }
+            } else {
+                throw new ServletException("Wrong request "+ request.getQueryString());
+            }
+        } catch (SQLException e) {
+            super.solveGetException(e, out);
+        }
+    }
+
+    static class RequestParameters {
+        private String user;
+        private final String group;
+        private final long unitId;
+        private final long sensorId;
+        private final String from;
+        private final String to;
+        private final String trunc;
+
+        RequestParameters(HttpServletRequest request) throws NullPointerException {
+            Object uid = request.getParameter("unit_id");
+            this.unitId = uid != null ? Long.parseLong(uid.toString()) : 0;
+
+            Object sid = request.getParameter("sensor_id");
+            this.sensorId = sid != null ? Long.parseLong(sid.toString()) : 0;
+
+            Object tr = request.getParameter("trunc");
+            this.trunc = tr != null ? tr.toString() : null;
+
+            Object fro =  request.getParameter("from");
+            this.from = fro != null ? fro.toString() : "1900-01-01 00:00:00+01";
+
+            Object too =  request.getParameter("to");
+            this.to = too != null ? too.toString() : "3000-01-01 00:00:00+01";
+
+            Object userO = request.getParameter("user");
+            this.user = userO != null ? userO.toString() : null;
+
+            Object groupO = request.getParameter("group");
+            this.group = groupO != null ? groupO.toString() : null;
+        }
+
+        public long getUnitId() {
+            return unitId;
+        }
+        public long getSensorId() {
+            return sensorId;
+        }
+        public String getFromTime() {
+            return from;
+        }
+        public String getToTime() {
+            return to;
+        }
+        public String getTrunc() {
+            return trunc;
+        }
+        public String getUser() {
+            return user;
+        }
+        public void setUser(String user) {
+            this.user = user;
+        }
+        public String getGroup() {
+            return group;
+        }
+    }
 }

+ 33 - 71
src/main/webapp/WEB-INF/database.properties

@@ -1,72 +1,34 @@
-#Address = jdbc:postgresql://git.zcu.cz:5433/sosdb2
-#Address = jdbc:postgresql://localhost:5432/sosdb
-#Address = jdbc:postgresql://maplog.lesprojekt.cz:5432/maplog
-#Address = jdbc:postgresql://localhost:5432/maplog
-#Address = jdbc:postgresql://sensors.lesprojekt.cz:5432/maplog
-
-#test server:
-#Address = jdbc:postgresql://88.86.113.248:5432/maplog
-#Username = ami4
-#Password = ami4for
-
-#Maplog for CZ
-#UnitsLastPositions_table = sjtsk_last_positions
-#UnitsTracks_table= sjtsk_units_tracks
-#UnitsPositions_table= sjtsk_positions
-
-#Maplog for FT
-#UnitsLastPositions_table = last_units_positions
-#UnitsTracks_table= units_tracks
-#UnitsPositions_table= units_positions
-
-#Maplog for EU
-UnitsLastPositions_table = mercator_last_positions
-UnitsTracks_table= mercator_units_tracks
-UnitsPositions_table= mercator_positions
-
-# sensor server
-#Address=jdbc:postgresql://85.254.250.61:5432/maplog
-#Username = maploguser
-#Password = cm1415
-
-# foodie server
-Address=jdbc:postgresql://foodie.lesprojekt.cz:5432/foodie
-Username = maplog
-Password = map.LOG_16
-
-# Maplog dev server
-#Address=jdbc:postgresql://liferay.ccss.cz:5432/foodie
-#Username = foodie
-#Password = keaG3eek
-
-# foodie server - Poland
-#Address=jdbc:postgresql://localhost:5432/senslog
-#Username = senslog
-#Password = f00die
-
-# test server Brno
-#Address=jdbc:postgresql://147.251.253.250:5432/foodie
-#Username = foodie
-#Password = keaG3eek
-
-# test server Brno - maplog_test
-#Address=jdbc:postgresql://147.251.253.250:5432/maplog_test
-#Username = foodie
-#Password = keaG3eek
-
-# farmtelemetry server
-#Address=jdbc:postgresql://ft.lesprojekt.cz:5432/foodie
-#Username = foodie
-#Password = keaG3eek
-
-# otn server
-#Address=jdbc:postgresql://otn.bnhelp.cz:5432/senslog
-#Username = senslog
-#Password = keaG3eek
-
-# picture for head of all pages (height ca. 75px)
-#Brand_picture = logo-OTN.png
-Brand_picture = logo-foodie.png
-#Brand_picture = logo-farmtelemetry.png
-
+#Maplog for CZ
+#UnitsLastPositions_table = sjtsk_last_positions
+#UnitsTracks_table= sjtsk_units_tracks
+#UnitsPositions_table= sjtsk_positions
+
+#Maplog for FT
+#UnitsLastPositions_table = last_units_positions
+#UnitsTracks_table= units_tracks
+#UnitsPositions_table= units_positions
+
+#Maplog for EU
+UnitsLastPositions_table = mercator_last_positions
+UnitsTracks_table= mercator_units_tracks
+UnitsPositions_table= mercator_positions
+
+
+# foodie server
+#Address=jdbc:postgresql://foodie.lesprojekt.cz:5432/foodie
+#Username = maplog
+#Password = map.LOG_16
+
+# FIE20 - tunnel
+Address=jdbc:postgresql://localhost:5433/senslog1
+# FIE20 - local
+#Address=jdbc:postgresql://localhost:5432/senslog1
+Username = senslog_app
+Password = SENSlog
+
+# picture for head of all pages (height ca. 75px)
+#Brand_picture = logo-OTN.png
+Brand_picture = logo-foodie.png
+#Brand_picture = logo-farmtelemetry.png
+
 Port = 5432

+ 14 - 14
src/main/webapp/WEB-INF/local_logging.properties

@@ -1,15 +1,15 @@
-handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
-formatters=java.util.logging.SimpleFormatter
-
-.level = ALL
-java.util.logging.ConsoleHandler.level = FINEST
-java.util.logging.FileHandler.level = FINEST
-
-java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
-
-java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
-#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/medlov/log.log
-#java.util.logging.FileHandler.pattern = /data/www/foodie.lesprojekt.cz/log/DBService.log
-java.util.logging.FileHandler.pattern = d://tmp//DBService.log
-#java.util.logging.FileHandler.pattern = /usr/share/tomcat5.5/webapps/DBService/maplog.log
+handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
+formatters=java.util.logging.SimpleFormatter
+
+.level = ALL
+java.util.logging.ConsoleHandler.level = FINEST
+java.util.logging.FileHandler.level = FINEST
+
+java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
+
+java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
+#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/medlov/log.log
+#java.util.logging.FileHandler.pattern = /data/www/foodie.lesprojekt.cz/log/DBService.log
+java.util.logging.FileHandler.pattern = d://tmp//senslog15.log
+#java.util.logging.FileHandler.pattern = /usr/share/tomcat5.5/webapps/DBService/maplog.log
 #java.util.logging.FileHandler.pattern = ./maplog.log

+ 15 - 14
src/main/webapp/WEB-INF/logging.properties

@@ -1,14 +1,15 @@
-handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
-formatters=java.util.logging.SimpleFormatter
-
-.level = ALL
-java.util.logging.ConsoleHandler.level = SEVERE
-java.util.logging.FileHandler.level = FINEST
-
-java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
-
-java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
-#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/medlov/log.log
-#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/DBService/DBService.log
-#java.util.logging.FileHandler.pattern = /usr/share/tomcat5.5/webapps/DBService/maplog.log
-java.util.logging.FileHandler.pattern = /var/log/maplog_ot.log
+handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
+formatters=java.util.logging.SimpleFormatter
+
+.level = ALL
+java.util.logging.ConsoleHandler.level = SEVERE
+java.util.logging.FileHandler.level = FINEST
+
+java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
+
+java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
+#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/medlov/log.log
+#java.util.logging.FileHandler.pattern = /data/tomcat/webapps/DBService/DBService.log
+#java.util.logging.FileHandler.pattern = /usr/share/tomcat5.5/webapps/DBService/maplog.log
+#java.util.logging.FileHandler.pattern = /var/log/maplog_ot.log
+java.util.logging.FileHandler.pattern = d://tmp//senslog15.log

+ 201 - 179
src/main/webapp/WEB-INF/web.xml

@@ -1,180 +1,202 @@
-<!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
-<web-app>
-    <display-name>Archetype Created Web Application</display-name>
-    <!--
-        The WicketSesionFilter can be used to provide thread local access to
-        servlets/ JSPs/ etc
-    -->
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            FeederServlet</display-name>
-        <servlet-name>FeederServlet</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.feeder.FeederServlet</servlet-class>
-    </servlet>
-    <servlet-mapping>
-        <servlet-name>FeederServlet</servlet-name>
-        <url-pattern>/FeederServlet</url-pattern>
-    </servlet-mapping>
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            ChartServlet</display-name>
-        <servlet-name>ChartServlet</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.ChartServlet</servlet-class>
-    </servlet>
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            SensorService</display-name>
-        <servlet-name>SensorService</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.SensorService</servlet-class>
-    </servlet>
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            AlertService</display-name>
-        <servlet-name>AlertService</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.AlertService</servlet-class>
-    </servlet>
-    
-    <servlet>
-        <description>
-        </description>
-        <display-name>AnalystService</display-name>
-        <servlet-name>AnalystService</servlet-name>
-        <servlet-class>cz.hsrs.servlet.provider.AnalystService</servlet-class>
-    </servlet>
-    
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            MMService</display-name>
-        <servlet-name>MMService</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.MMService</servlet-class>
-    </servlet>
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            DataService</display-name>
-        <servlet-name>DataService</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.DataService</servlet-class>
-    </servlet>
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            GroupService</display-name>
-        <servlet-name>GroupService</servlet-name>
-        <servlet-class>
-            cz.hsrs.servlet.provider.GroupService</servlet-class>
-    </servlet>
-
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            ControllerServlet</display-name>
-        <servlet-name>ControllerServlet</servlet-name>
-        <servlet-class>cz.hsrs.servlet.security.ControllerServlet</servlet-class>
-    </servlet>
-    <servlet>
-        <description>
-        </description>
-        <display-name>
-            Logout</display-name>
-        <servlet-name>Logout</servlet-name>
-        <servlet-class>cz.hsrs.servlet.security.LogoutServlet</servlet-class>
-    </servlet>
-    <servlet>
-        <description>
-        </description>
-        <display-name>ChangeLang</display-name>
-        <servlet-name>ChangeLang</servlet-name>
-        <servlet-class>cz.hsrs.servlet.lang.ChangeLangServlet</servlet-class>
-    </servlet>
-    
-
-    <servlet-mapping>
-        <servlet-name>Logout</servlet-name>
-        <url-pattern>/Logout</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>ChangeLang</servlet-name>
-        <url-pattern>/ChangeLang</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>ControllerServlet</servlet-name>
-        <url-pattern>/ControllerServlet</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>ChartServlet</servlet-name>
-        <url-pattern>/ChartServlet</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>DataService</servlet-name>
-        <url-pattern>/DataService</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>GroupService</servlet-name>
-        <url-pattern>/GroupService</url-pattern>
-    </servlet-mapping>
-    <servlet-mapping>
-        <servlet-name>SensorService</servlet-name>
-        <url-pattern>/SensorService</url-pattern>
-    </servlet-mapping>
-
-    <servlet-mapping>
-        <servlet-name>AlertService</servlet-name>
-        <url-pattern>/AlertService</url-pattern>
-    </servlet-mapping>
-    
-    <servlet-mapping>
-        <servlet-name>AnalystService</servlet-name>
-        <url-pattern>/AnalystService</url-pattern>
-    </servlet-mapping>
-    
-    <servlet-mapping>
-        <servlet-name>MMService</servlet-name>
-        <url-pattern>/MMService</url-pattern>
-    </servlet-mapping>
-
-    <init-param>
-        <param-name>development</param-name>
-        <param-value>false</param-value>
-    </init-param>
-
-    <welcome-file-list>
-        <welcome-file>crossroad.jsp</welcome-file>
-    </welcome-file-list>
-
-    <listener>
-        <description>sessionListener</description>
-        <listener-class>cz.hsrs.servlet.security.SessionListener</listener-class>
-    </listener>
-
-    <session-config>
-        <session-timeout>240</session-timeout>
-    </session-config>
-
+<!DOCTYPE web-app PUBLIC
+ "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
+ "http://java.sun.com/dtd/web-app_2_3.dtd" >
+
+<web-app>
+    <display-name>Archetype Created Web Application</display-name>
+    <!--
+        The WicketSesionFilter can be used to provide thread local access to
+        servlets/ JSPs/ etc
+    -->
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>FeederServlet</display-name>
+        <servlet-name>FeederServlet</servlet-name>
+        <servlet-class>cz.hsrs.servlet.feeder.FeederServlet</servlet-class>
+    </servlet>
+    <servlet-mapping>
+        <servlet-name>FeederServlet</servlet-name>
+        <url-pattern>/FeederServlet</url-pattern>
+    </servlet-mapping>
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>ChartServlet</display-name>
+        <servlet-name>ChartServlet</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.ChartServlet</servlet-class>
+    </servlet>
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>SensorService</display-name>
+        <servlet-name>SensorService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.SensorService</servlet-class>
+    </servlet>
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>AlertService</display-name>
+        <servlet-name>AlertService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.AlertService</servlet-class>
+    </servlet>
+    
+    <servlet>
+        <description>
+        </description>
+        <display-name>AnalystService</display-name>
+        <servlet-name>AnalystService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.AnalystService</servlet-class>
+    </servlet>
+    
+    <servlet>
+        <description>
+        </description>
+        <display-name>MMService</display-name>
+        <servlet-name>MMService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.MMService</servlet-class>
+    </servlet>
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>DataService</display-name>
+        <servlet-name>DataService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.DataService</servlet-class>
+    </servlet>
+    <servlet>
+        <description>
+        </description>
+        <display-name>GroupService</display-name>
+        <servlet-name>GroupService</servlet-name>
+        <servlet-class>cz.hsrs.servlet.provider.GroupService</servlet-class>
+    </servlet>
+
+    <servlet>
+        <description>
+        </description>
+        <display-name>ControllerServlet</display-name>
+        <servlet-name>ControllerServlet</servlet-name>
+        <servlet-class>cz.hsrs.servlet.security.ControllerServlet</servlet-class>
+    </servlet>
+    <servlet>
+        <description>
+        </description>
+        <display-name>Logout</display-name>
+        <servlet-name>Logout</servlet-name>
+        <servlet-class>cz.hsrs.servlet.security.LogoutServlet</servlet-class>
+    </servlet>
+    <servlet>
+        <description>
+        </description>
+        <display-name>ChangeLang</display-name>
+        <servlet-name>ChangeLang</servlet-name>
+        <servlet-class>cz.hsrs.servlet.lang.ChangeLangServlet</servlet-class>
+    </servlet>
+    
+<!-- Jersey 1.x REST -->
+  <servlet>
+      <servlet-name>Jersey REST Service</servlet-name>
+      <!-- <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>-->
+       <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
+      <init-param>
+        <!-- <param-name>com.sun.jersey.config.property.packages</param-name>-->
+        <param-name>jersey.config.server.provider.packages</param-name>
+        <param-value>cz.hsrs.rest, cz.hsrs.rest.vgi, cz.hsrs.rest.provider</param-value>
+      </init-param>
+      <init-param>
+          <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
+          <param-value>true</param-value>
+      </init-param>
+      <init-param>
+          <param-name>jersey.config.server.provider.classnames</param-name>
+          <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
+      </init-param>
+      <init-param>
+          <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
+          <param-value>cz.hsrs.rest.util.CorsFilter</param-value>
+      </init-param>
+<!--     <init-param> -->
+<!--       <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name> -->
+<!--       <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value> -->
+<!--       <param-value>com.sun.jersey.api.container.filter.LoggingFilter;cz.hsrs.hsformserver.rest.AuthFilter</param-value> -->
+<!--       <param-value>cz.hsrs.hsformserver.rest.AuthFilter</param-value> -->
+<!--     </init-param> -->
+      <load-on-startup>1</load-on-startup>
+  </servlet>
+
+    <servlet-mapping>
+        <servlet-name>Logout</servlet-name>
+        <url-pattern>/Logout</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>ChangeLang</servlet-name>
+        <url-pattern>/ChangeLang</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>ControllerServlet</servlet-name>
+        <url-pattern>/ControllerServlet</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>ChartServlet</servlet-name>
+        <url-pattern>/ChartServlet</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>DataService</servlet-name>
+        <url-pattern>/DataService</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>GroupService</servlet-name>
+        <url-pattern>/GroupService</url-pattern>
+    </servlet-mapping>
+    <servlet-mapping>
+        <servlet-name>SensorService</servlet-name>
+        <url-pattern>/SensorService</url-pattern>
+    </servlet-mapping>
+
+    <servlet-mapping>
+        <servlet-name>AlertService</servlet-name>
+        <url-pattern>/AlertService</url-pattern>
+    </servlet-mapping>
+    
+    <servlet-mapping>
+        <servlet-name>AnalystService</servlet-name>
+        <url-pattern>/AnalystService</url-pattern>
+    </servlet-mapping>
+    
+    <servlet-mapping>
+        <servlet-name>MMService</servlet-name>
+        <url-pattern>/MMService</url-pattern>
+    </servlet-mapping>
+
+    <servlet-mapping>
+      <servlet-name>Jersey REST Service</servlet-name>
+      <url-pattern>/rest/*</url-pattern>
+    </servlet-mapping>
+
+    <init-param>
+        <param-name>development</param-name>
+        <param-value>false</param-value>
+    </init-param>
+
+    <welcome-file-list>
+        <welcome-file>crossroad.jsp</welcome-file>
+    </welcome-file-list>
+
+    <listener>
+        <description>sessionListener</description>
+        <listener-class>cz.hsrs.servlet.security.SessionListener</listener-class>
+    </listener>
+    <listener>
+        <listener-class>cz.hsrs.rest.SCListener</listener-class>
+    </listener>
+
+    <session-config>
+        <session-timeout>240</session-timeout>
+    </session-config>
+
 </web-app>