Changeset 13cbe66


Ignore:
Timestamp:
May 25, 2019, 5:40:08 PM (8 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
70f328b
Parents:
28198a1
git-author:
Joachim Langenbach <joachim.langenbach@…> (05/22/19 18:20:13)
git-committer:
Joachim Langenbach <joachim.langenbach@…> (05/25/19 17:40:08)
Message:

Gauges could be added now

Location:
src
Files:
12 added
10 deleted
33 edited

Legend:

Unmodified
Added
Removed
  • src/mapservice-webclient/src-gen/gnuboat-mapservice/api/users.service.ts

    r28198a1 r13cbe66  
    148148        let headers = this.defaultHeaders;
    149149
    150         // authentication (apiKeyAuth) required
    151         if (this.configuration.apiKeys && this.configuration.apiKeys["X-API-KEY"]) {
    152             headers = headers.set('X-API-KEY', this.configuration.apiKeys["X-API-KEY"]);
    153         }
    154 
    155150        // authentication (basicAuth) required
    156151        if (this.configuration.username || this.configuration.password) {
    … …  
    197192        let headers = this.defaultHeaders;
    198193
    199         // authentication (apiKeyAuth) required
    200         if (this.configuration.apiKeys && this.configuration.apiKeys["X-API-KEY"]) {
    201             headers = headers.set('X-API-KEY', this.configuration.apiKeys["X-API-KEY"]);
    202         }
    203 
    204194        // authentication (basicAuth) required
    205195        if (this.configuration.username || this.configuration.password) {
    … …  
    231221    /**
    232222     * Returns info of a user
    233      * Returns information for a user
     223     * Returns information of current/authorized user
    234224     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
    235225     * @param reportProgress flag to report request and response progress.
  • src/mapservice-webclient/src-gen/gnuboat-mapservice/api/waters.service.ts

    r28198a1 r13cbe66  
    1919import { Observable }                                        from 'rxjs/Observable';
    2020
     21import { Gauge } from '../model/gauge';
     22import { GaugeCreation } from '../model/gaugeCreation';
    2123import { HttpError } from '../model/httpError';
    2224import { Water } from '../model/water';
    … …  
    6163
    6264    /**
    63      * Represents a water
    64      * Returns the water identified by id
    65      * @param id Item ID
    66      * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
    67      * @param reportProgress flag to report request and response progress.
    68      */
    69     public waterGetById(id: number, observe?: 'body', reportProgress?: boolean): Observable<Water>;
    70     public waterGetById(id: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Water>>;
    71     public waterGetById(id: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Water>>;
    72     public waterGetById(id: number, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
    73         if (id === null || id === undefined) {
    74             throw new Error('Required parameter id was null or undefined when calling waterGetById.');
    75         }
    76 
    77         let headers = this.defaultHeaders;
    78 
    79         // to determine the Accept header
    80         const httpHeaderAccepts: string[] = [
    81             'application/json'
    82         ];
    83         const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
    84         if (httpHeaderAcceptSelected !== undefined) {
    85             headers = headers.set('Accept', httpHeaderAcceptSelected);
    86         }
    87 
    88         // to determine the Content-Type header
    89         const consumes: string[] = [
    90         ];
    91 
    92         return this.httpClient.get<Water>(`${this.configuration.basePath}/waters/${encodeURIComponent(String(id))}`,
    93             {
    94                 withCredentials: this.configuration.withCredentials,
    95                 headers: headers,
    96                 observe: observe,
    97                 reportProgress: reportProgress
    98             }
    99         );
    100     }
    101 
    102     /**
    10365     * Add a new water
    10466     * Adds a new water to the database
    … …  
    144106            waterCreation,
    145107            {
     108                withCredentials: this.configuration.withCredentials,
     109                headers: headers,
     110                observe: observe,
     111                reportProgress: reportProgress
     112            }
     113        );
     114    }
     115
     116    /**
     117     * Add a new water
     118     * Adds a new gauge for water waterId to the database
     119     * @param waterId Water ID
     120     * @param gaugeCreation
     121     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     122     * @param reportProgress flag to report request and response progress.
     123     */
     124    public watersGaugeCreate(waterId: number, gaugeCreation?: GaugeCreation, observe?: 'body', reportProgress?: boolean): Observable<Gauge>;
     125    public watersGaugeCreate(waterId: number, gaugeCreation?: GaugeCreation, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Gauge>>;
     126    public watersGaugeCreate(waterId: number, gaugeCreation?: GaugeCreation, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Gauge>>;
     127    public watersGaugeCreate(waterId: number, gaugeCreation?: GaugeCreation, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
     128        if (waterId === null || waterId === undefined) {
     129            throw new Error('Required parameter waterId was null or undefined when calling watersGaugeCreate.');
     130        }
     131
     132        let headers = this.defaultHeaders;
     133
     134        // authentication (apiKeyAuth) required
     135        if (this.configuration.apiKeys && this.configuration.apiKeys["X-API-KEY"]) {
     136            headers = headers.set('X-API-KEY', this.configuration.apiKeys["X-API-KEY"]);
     137        }
     138
     139        // authentication (basicAuth) required
     140        if (this.configuration.username || this.configuration.password) {
     141            headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
     142        }
     143        // to determine the Accept header
     144        const httpHeaderAccepts: string[] = [
     145            'application/json',
     146            'application/geo+json'
     147        ];
     148        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
     149        if (httpHeaderAcceptSelected !== undefined) {
     150            headers = headers.set('Accept', httpHeaderAcceptSelected);
     151        }
     152
     153        // to determine the Content-Type header
     154        const consumes: string[] = [
     155            'application/json'
     156        ];
     157        const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
     158        if (httpContentTypeSelected !== undefined) {
     159            headers = headers.set('Content-Type', httpContentTypeSelected);
     160        }
     161
     162        return this.httpClient.post<Gauge>(`${this.configuration.basePath}/waters/${encodeURIComponent(String(waterId))}/gauges`,
     163            gaugeCreation,
     164            {
     165                withCredentials: this.configuration.withCredentials,
     166                headers: headers,
     167                observe: observe,
     168                reportProgress: reportProgress
     169            }
     170        );
     171    }
     172
     173    /**
     174     * Represents a gauge
     175     * Returns the gauge identified by id
     176     * @param waterId Water ID
     177     * @param gaugeId Gauge ID
     178     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     179     * @param reportProgress flag to report request and response progress.
     180     */
     181    public watersGaugeGetById(waterId: number, gaugeId: number, observe?: 'body', reportProgress?: boolean): Observable<Gauge>;
     182    public watersGaugeGetById(waterId: number, gaugeId: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Gauge>>;
     183    public watersGaugeGetById(waterId: number, gaugeId: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Gauge>>;
     184    public watersGaugeGetById(waterId: number, gaugeId: number, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
     185        if (waterId === null || waterId === undefined) {
     186            throw new Error('Required parameter waterId was null or undefined when calling watersGaugeGetById.');
     187        }
     188        if (gaugeId === null || gaugeId === undefined) {
     189            throw new Error('Required parameter gaugeId was null or undefined when calling watersGaugeGetById.');
     190        }
     191
     192        let headers = this.defaultHeaders;
     193
     194        // to determine the Accept header
     195        const httpHeaderAccepts: string[] = [
     196            'application/json',
     197            'application/geo+json'
     198        ];
     199        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
     200        if (httpHeaderAcceptSelected !== undefined) {
     201            headers = headers.set('Accept', httpHeaderAcceptSelected);
     202        }
     203
     204        // to determine the Content-Type header
     205        const consumes: string[] = [
     206        ];
     207
     208        return this.httpClient.get<Gauge>(`${this.configuration.basePath}/waters/${encodeURIComponent(String(waterId))}/gauges/${encodeURIComponent(String(gaugeId))}`,
     209            {
     210                withCredentials: this.configuration.withCredentials,
     211                headers: headers,
     212                observe: observe,
     213                reportProgress: reportProgress
     214            }
     215        );
     216    }
     217
     218    /**
     219     * Find gauges of water waterId by gaugeId
     220     * Returns all gauges of water waterId
     221     * @param waterId Water ID
     222     * @param name
     223     * @param manager
     224     * @param orderBy Order by field: name
     225     * @param offset Skip over a number of elements by specifying an offset value for the query
     226     * @param limit Limit the number of elements on the response
     227     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     228     * @param reportProgress flag to report request and response progress.
     229     */
     230    public watersGaugesGet(waterId: number, name?: string, manager?: string, orderBy?: string, offset?: number, limit?: number, observe?: 'body', reportProgress?: boolean): Observable<Array<Gauge>>;
     231    public watersGaugesGet(waterId: number, name?: string, manager?: string, orderBy?: string, offset?: number, limit?: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<Gauge>>>;
     232    public watersGaugesGet(waterId: number, name?: string, manager?: string, orderBy?: string, offset?: number, limit?: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<Gauge>>>;
     233    public watersGaugesGet(waterId: number, name?: string, manager?: string, orderBy?: string, offset?: number, limit?: number, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
     234        if (waterId === null || waterId === undefined) {
     235            throw new Error('Required parameter waterId was null or undefined when calling watersGaugesGet.');
     236        }
     237
     238        let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()});
     239        if (name !== undefined && name !== null) {
     240            queryParameters = queryParameters.set('name', <any>name);
     241        }
     242        if (manager !== undefined && manager !== null) {
     243            queryParameters = queryParameters.set('manager', <any>manager);
     244        }
     245        if (orderBy !== undefined && orderBy !== null) {
     246            queryParameters = queryParameters.set('orderBy', <any>orderBy);
     247        }
     248        if (offset !== undefined && offset !== null) {
     249            queryParameters = queryParameters.set('offset', <any>offset);
     250        }
     251        if (limit !== undefined && limit !== null) {
     252            queryParameters = queryParameters.set('limit', <any>limit);
     253        }
     254
     255        let headers = this.defaultHeaders;
     256
     257        // to determine the Accept header
     258        const httpHeaderAccepts: string[] = [
     259            'application/json',
     260            'application/geo+json'
     261        ];
     262        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
     263        if (httpHeaderAcceptSelected !== undefined) {
     264            headers = headers.set('Accept', httpHeaderAcceptSelected);
     265        }
     266
     267        // to determine the Content-Type header
     268        const consumes: string[] = [
     269        ];
     270
     271        return this.httpClient.get<Array<Gauge>>(`${this.configuration.basePath}/waters/${encodeURIComponent(String(waterId))}/gauges`,
     272            {
     273                params: queryParameters,
    146274                withCredentials: this.configuration.withCredentials,
    147275                headers: headers,
    … …  
    211339    }
    212340
     341    /**
     342     * Represents a water
     343     * Returns the water identified by id
     344     * @param id Item ID
     345     * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
     346     * @param reportProgress flag to report request and response progress.
     347     */
     348    public watersGetById(id: number, observe?: 'body', reportProgress?: boolean): Observable<Water>;
     349    public watersGetById(id: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Water>>;
     350    public watersGetById(id: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Water>>;
     351    public watersGetById(id: number, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {
     352        if (id === null || id === undefined) {
     353            throw new Error('Required parameter id was null or undefined when calling watersGetById.');
     354        }
     355
     356        let headers = this.defaultHeaders;
     357
     358        // to determine the Accept header
     359        const httpHeaderAccepts: string[] = [
     360            'application/json'
     361        ];
     362        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
     363        if (httpHeaderAcceptSelected !== undefined) {
     364            headers = headers.set('Accept', httpHeaderAcceptSelected);
     365        }
     366
     367        // to determine the Content-Type header
     368        const consumes: string[] = [
     369        ];
     370
     371        return this.httpClient.get<Water>(`${this.configuration.basePath}/waters/${encodeURIComponent(String(id))}`,
     372            {
     373                withCredentials: this.configuration.withCredentials,
     374                headers: headers,
     375                observe: observe,
     376                reportProgress: reportProgress
     377            }
     378        );
     379    }
     380
    213381}
  • src/mapservice-webclient/src-gen/gnuboat-mapservice/model/models.ts

    r28198a1 r13cbe66  
     1export * from './gauge';
     2export * from './gaugeCreation';
     3export * from './gaugeGeoJson';
     4export * from './gaugeGeoJsonProperties';
     5export * from './geoJsonPoint';
     6export * from './geoJsonType';
    17export * from './httpError';
    28export * from './order';
  • src/mapservice-webclient/src-gen/gnuboat-mapservice/model/water.ts

    r28198a1 r13cbe66  
    1010 * Do not edit the class manually.
    1111 */
     12import { Gauge } from './gauge';
    1213import { OsmType } from './osmType';
    1314
    … …  
    1920    osmId?: number;
    2021    osmType?: OsmType;
     22    gauges?: Array<Gauge>;
    2123}
    2224
  • src/mapservice-webclient/src/app/app.component.html

    r28198a1 r13cbe66  
    88          <li class="pure-menu-item"><a class="pure-menu-link" routerLink="water">Waters</a></li>
    99          <li class="pure-menu-heading">My GNUBoat</li>
     10          <li class="pure-menu-item"><a class="pure-menu-link" routerLink="mygnuboat" fragment="logfiles">Logfiles</a></li>
    1011          <li class="pure-menu-item"><a class="pure-menu-link" routerLink="mygnuboat" fragment="waters">Waters</a></li>
    11           <li class="pure-menu-item"><a class="pure-menu-link" routerLink="mygnuboat" fragment="logfiles">Logfiles</a></li>
    1212          <li class="pure-menu-item"><a class="pure-menu-link" routerLink="mygnuboat" fragment="profile">Profile</a></li>
    1313          <li class="pure-menu-item" *ngIf="currentUser"><a class="pure-menu-link" (click)="logout()">Logout</a></li>
  • src/mapservice-webclient/src/app/app.module.ts

    r28198a1 r13cbe66  
    1414import { HomeComponent } from './home/';
    1515import { LoginComponent, RegisterComponent } from './user';
    16 import { WatersComponent, WaterComponent, WaterDetailsComponent } from './water';
     16import { WatersComponent, WaterComponent, WaterDetailsComponent, GaugesComponent } from './water';
    1717import { MapComponent } from './map';
    18 import { UserComponent, WaterAddComponent } from './mygnuboat';
     18import { UserComponent, WaterAddComponent, GaugeEditComponent } from './mygnuboat';
    1919
    2020
    … …  
    3737    WaterComponent,
    3838    WaterDetailsComponent,
     39    GaugesComponent,
    3940    WaterAddComponent,
     41    GaugeEditComponent,
    4042    MapComponent,
    4143  ],
  • src/mapservice-webclient/src/app/map/map.component.ts

    r28198a1 r13cbe66  
    1 import { Component, OnInit, OnDestroy, Input, ViewChild, Output, EventEmitter } from '@angular/core';
     1import { Component, OnInit, OnDestroy, Input, ViewChild, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
    22
    33declare let L;
    44
    5 import { OsmType } from '../../../src-gen/gnuboat-mapservice';
     5import { OsmType, Water, Gauge, GaugeGeoJson, GeoJsonPoint, GaugeGeoJsonProperties } from '../../../src-gen/gnuboat-mapservice';
    66import { OsmOverpassService } from '../services';
    77import { GeoPoint } from '../model';
    … …  
    1212  providers: [OsmOverpassService],
    1313})
    14 export class MapComponent implements OnInit, OnDestroy {
     14export class MapComponent implements OnInit, OnDestroy, OnChanges {
    1515  private _mapViewportStyleClass:string;
    1616  private map;
    1717  private mapControl;
    18   private geoJsonLayer;
     18  private osmLayer;
     19  private gaugesLayer;
     20  @Input() water: Water = undefined;
    1921  @Input() controlsShow = true;
    2022  @ViewChild('mapElement') mapElement;
    21   @Output() clicked = new EventEmitter<GeoPoint>();
     23  @Output() clickedRight = new EventEmitter<GeoPoint>();
    2224
    2325  constructor(private osmOverpassService: OsmOverpassService) {
    … …  
    2931
    3032  ngOnDestroy() {
     33  }
     34
     35  ngOnChanges(changes: SimpleChanges): void {
     36    if('water' in changes && this.water && this.map){
     37      this.addWaterToMap(this.water);
     38    }
    3139  }
    3240
    … …  
    5159    });
    5260
    53     this.map.on('click', event => {
     61    this.map.on('contextmenu', event => {
    5462      var point = {} as GeoPoint;
    5563      point.latitude = event.latlng.lat;
    5664      point.longitude = event.latlng.lng;
    57       this.clicked.emit(point);
     65      this.clickedRight.emit(point);
     66      return event;
    5867    });
    5968
    … …  
    95104      L.control.scale().addTo(this.map);
    96105    }
     106
     107    if(this.water){
     108      this.addWaterToMap(this.water);
     109    }
    97110  }
    98111
    99112  addOsmElement(id: number, osmType: OsmType){
    100     if(!this.geoJsonLayer){
    101       this.geoJsonLayer = L.geoJSON().addTo(this.map);
     113    if(!this.osmLayer){
     114      this.osmLayer = this.addGeoJsonLayer();
    102115    }
     116    this.osmLayer.clearLayers();
    103117    this.osmOverpassService.getElement(id, osmType).subscribe(res => {
    104       this.geoJsonLayer.addData(res);
    105       this.map.fitBounds(this.geoJsonLayer.getBounds());
     118      this.osmLayer.addData(res);
     119      this.map.fitBounds(this.osmLayer.getBounds());
    106120    });
    107121  }
     122
     123  addGeoJsonLayer(options = {}){
     124    return L.geoJSON(undefined, options).addTo(this.map);
     125  }
     126
     127  addWaterToMap(water:Water){
     128    this.addOsmElement(water.osmId, water.osmType);
     129    if('gauges' in water){
     130      this.addGaugesToMap(water.gauges);
     131    }
     132  }
     133
     134  addGaugesToMap(gauges:Gauge[]){
     135    /* currently openapi-generators typescript-angular plugin isn't able to handle content types, which are not plain json
     136       therefore we convert the gauges here and add them to the map. The API as defined, supports geo+json format already
     137     */
     138    if(this.gaugesLayer){
     139      this.gaugesLayer.clearLayers();
     140    }
     141    if(gauges && gauges.length < 1){
     142      return;
     143    }
     144    if(!this.gaugesLayer){
     145      this.gaugesLayer = this.addGeoJsonLayer({
     146        onEachFeature: this.gaugesMarkerPopup,
     147        pointToLayer: this.gaugesMarker
     148      });
     149    }
     150    gauges.forEach(gauge => {
     151      var gaugeGeoJson = {} as GaugeGeoJson;
     152      gaugeGeoJson.type = "Feature";
     153      gaugeGeoJson.geometry = {} as GeoJsonPoint;
     154      gaugeGeoJson.geometry.type = "Point";
     155      gaugeGeoJson.geometry.coordinates = [];
     156      gaugeGeoJson.geometry.coordinates.push(gauge.location[0]);
     157      gaugeGeoJson.geometry.coordinates.push(gauge.location[1]);
     158      gaugeGeoJson.properties = {} as GaugeGeoJsonProperties;
     159      gaugeGeoJson.properties.name = gauge.name;
     160      gaugeGeoJson.properties.manager = gauge.manager;
     161      gaugeGeoJson.properties.comment = gauge.comment;
     162      this.gaugesLayer.addData(gaugeGeoJson);
     163    });
     164  }
     165
     166  gaugesMarker(feature, latlng){
     167    var markerOptions = {
     168      radius: 8,
     169      fillColor: "#ff7800",
     170      color: "#000",
     171      weight: 1,
     172      opacity: 1,
     173      fillOpacity: 0.8
     174    };
     175    return L.circleMarker(latlng, markerOptions);
     176  }
     177
     178  gaugesMarkerPopup(feature, layer) {
     179    if (feature.properties && feature.properties.name) {
     180        layer.bindPopup(feature.properties.name);
     181    }
     182  }
    108183}
  • src/mapservice-webclient/src/app/mygnuboat/index.ts

    r28198a1 r13cbe66  
    11export * from './user.component';
    22export * from './wateradd.component';
     3export * from './gaugeedit.component';
  • src/mapservice-webclient/src/app/mygnuboat/wateradd.component.html

    r28198a1 r13cbe66  
    11<div class="header">
    2   <h1>Add a new Water to GNUBoat</h1>
     2  <h1 i18n="@@wateraddTitle">Add a new Water to GNUBoat</h1>
    33  <alert></alert>
    44</div>
    … …  
    99        <fieldset>
    1010          <div class="pure-control-group">
    11             <label for="name">Name:</label>
    12             <input #waterNameInput id="waterNameAutocomplete" formControlName='name' type="text" placeholder="Name of Water" required>
     11            <label for="name" i18n="@@waterAddName">Name:</label>
     12            <input #waterNameInput id="waterNameAutocomplete" formControlName='name' type="text" i18n-placeholder placeholder="Name of Water" required>
    1313            <img *ngIf="isProcessingGnuBoat || isProcessingOverpass" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
    14             <span *ngIf="submitted && watersForm.name.errors" class="pure-form-message-inline">Watername is required.</span>
     14            <span *ngIf="submitted && watersForm.name.errors" class="pure-form-message-inline" i18n="@@waterNameRequired">Watername is required.</span>
    1515          </div>
    1616          <div class="pure-controls">
    17             <button [disabled]="!waterChoosen || !currentUser" *ngIf="!waterChoosen || waterChoosen.origin!=Origin.GNUBOAT" class="pure-button pure-button-primary">Add</button>
    18             <button [disabled]="!waterChoosen || !currentUser" *ngIf="waterChoosen && waterChoosen.origin==Origin.GNUBOAT" class="pure-button pure-button-primary">Choose</button>
     17            <button [disabled]="!waterChoosen || !currentUser" *ngIf="!waterChoosen || waterChoosen.origin!=Origin.GNUBOAT" class="pure-button pure-button-primary" i18n="@@waterButtonAdd">Add</button>
     18            <button [disabled]="!waterChoosen || !currentUser" *ngIf="waterChoosen && waterChoosen.origin==Origin.GNUBOAT" class="pure-button pure-button-primary" i18n="@@waterButtonChoose">Choose</button>
    1919          </div>
    2020        </fieldset>
  • src/mapservice-webclient/src/app/mygnuboat/wateradd.component.ts

    r28198a1 r13cbe66  
    201201    }
    202202    if(this.waterChoosen.origin == Origin.OSM){
    203       console.log("GNUBOAT --> OSM");
    204203      var water = {} as WaterCreation;
    205204      water.name = this.waterChoosen.value;
    … …  
    207206      water.osmType = this.waterChoosen.osmType;
    208207      this.watersService.watersCreate(water).pipe(first()).subscribe(result => {
    209         console.log([water.name, result.name]);
    210208        if(water.name == result.name){
    211209          this.router.navigate(['/water', result.waterId]);
  • src/mapservice-webclient/src/app/water/index.ts

    r28198a1 r13cbe66  
    22export * from './water.component';
    33export * from './waterdetails.component';
     4export * from './gauges.component';
  • src/mapservice-webclient/src/app/water/water.component.html

    r28198a1 r13cbe66  
    11<div class="water">
    22        <div class="water-background">
    3                 <gnuboat-map #mapComponent [viewportStyleClass]='mapViewportStyleClass' [controlsShow]='mapControlsShow'></gnuboat-map>
     3                <gnuboat-map #mapComponent [viewportStyleClass]='mapViewportStyleClass' [controlsShow]='mapControlsShow' [water]='water'></gnuboat-map>
    44        </div>
    55        <div class="water-content">
    6                 <h2>{{water.name}}</h2>
     6                <a [routerLink]="['/water', water.waterId]"><h2>{{water.name}}</h2></a>
    77                <ul>
    8                 <li>Managed by {{water.manager}}</li>
     8                <li *ngIf="water.gauges; else noGauges">{{water.gauges.length}} Gauges</li>
     9                <ng-template #noGauges><li>No Gauges</li></ng-template>
    910                <li><button class="button-add pure-button">Upload Logfile</button></li>
    1011                <li><a class="pure-button water-edit" [routerLink]="['/water', water.waterId]"><span *ngIf="user">Edit / </span>Details</a></li>
  • src/mapservice-webclient/src/app/water/water.component.ts

    r28198a1 r13cbe66  
    1 import { Component, OnInit, OnDestroy, AfterViewInit, Input, ViewChild } from '@angular/core';
     1import { Component, OnInit, OnDestroy, Input, ViewChild } from '@angular/core';
    22import { Subscription } from 'rxjs';
    33import { first } from 'rxjs/operators';
    … …  
    1212  templateUrl: 'water.component.html',
    1313})
    14 export class WaterComponent implements OnInit, OnDestroy, AfterViewInit {
     14export class WaterComponent implements OnInit, OnDestroy {
    1515  @Input() water: Water;
    1616  @Input() user: User;
    … …  
    2525  }
    2626
    27   ngAfterViewInit() {
    28     this.mapComponent.addOsmElement(this.water.osmId, this.water.osmType);
    29   }
    30 
    3127  ngOnDestroy() {
    3228  }
  • src/mapservice-webclient/src/app/water/waterdetails.component.html

    r28198a1 r13cbe66  
    44</div>
    55<div class="content">
    6   <p *ngIf="currentUser">Click on Map to add new Levels</p>
    7   <gnuboat-map #mapComponent [viewportStyleClass]='mapViewportStyleClass' [controlsShow]='mapControlsShow' (clicked)='mapClicked($event)'></gnuboat-map>
    8   <h2 class="content-subhead">Levels</h2>
    9 
     6  <p *ngIf="currentUser">Right click on Map to add new Gauges</p>
     7  <gnuboat-map #mapComponent [viewportStyleClass]='mapViewportStyleClass' [controlsShow]='mapControlsShow' (clickedRight)='mapClicked($event)' [water]='water'></gnuboat-map>
     8  <gnuboat-gauge-edit *ngIf="gaugeEditing" [water]="water" [gauge]="gaugeEditing" (cancel)='gaugeEditingCanceled()' (gaugeCreated)='gaugeCreated($event)'></gnuboat-gauge-edit>
     9  <gnuboat-gauges [water]="water" [mapComponent]="mapComponent"></gnuboat-gauges>
    1010</div>
    1111
  • src/mapservice-webclient/src/app/water/waterdetails.component.ts

    r28198a1 r13cbe66  
    1 import { Component, OnInit, OnDestroy, AfterViewInit, Input, ViewChild } from '@angular/core';
     1import { Component, OnInit, OnDestroy, Input, ViewChild } from '@angular/core';
    22import { Router, ActivatedRoute, ParamMap } from '@angular/router';
    33import { switchMap, first } from 'rxjs/operators';
    44import { Observable, Subscription } from 'rxjs';
    55
    6 import { User, Water, WatersService } from '../../../src-gen/gnuboat-mapservice';
     6import { User, Water, Gauge, GaugeCreation, WatersService } from '../../../src-gen/gnuboat-mapservice';
    77import { MapComponent } from '../map';
    88import { GeoPoint } from '../model';
    … …  
    1212  templateUrl: 'waterdetails.component.html',
    1313})
    14 export class WaterDetailsComponent implements OnInit, OnDestroy, AfterViewInit {
     14export class WaterDetailsComponent implements OnInit, OnDestroy {
    1515  @Input() water: Water;
    1616  mapViewportStyleClass:string = "water-edit-map";
    … …  
    1818  @ViewChild('mapComponent') mapComponent: MapComponent;
    1919  currentUser: User = undefined;
     20  gaugeEditing: GaugeCreation = undefined;
    2021
    2122  private currentUserSubscription: Subscription;
    … …  
    3839      }
    3940    });
    40   }
    41 
    42   ngAfterViewInit() {
    4341    const id = Number(this.route.snapshot.paramMap.get('id'));
    44     this.watersService.waterGetById(id).subscribe(water => {
     42    this.watersService.watersGetById(id).subscribe(water => {
    4543      this.water = water;
    46       this.mapComponent.addOsmElement(water.osmId, water.osmType);
    4744    },
    4845    error => {
    … …  
    5552
    5653  mapClicked(point: GeoPoint){
    57     console.log(point);
     54    if(!this.currentUser){
     55      return;
     56    }
     57    if(this.gaugeEditing){
     58      this.alertService.error("Please finish or abort your currently edited gauge before creating a new one!");
     59      return;
     60    }
     61    this.gaugeEditing = {} as GaugeCreation;
     62    this.gaugeEditing.location = [];
     63    this.gaugeEditing.location.push(point.longitude);
     64    this.gaugeEditing.location.push(point.latitude);
     65    this.gaugeEditing.comment = "";
     66  }
     67
     68  gaugeEditingCanceled(){
     69    this.gaugeEditing = undefined;
     70  }
     71
     72  gaugeCreated(gauge: Gauge){
     73    this.water.gauges.push(gauge);
     74    this.water = Object.assign({}, this.water);
     75    this.gaugeEditing = undefined;
    5876  }
    5977}
  • src/mapservice-webclient/src/app/water/waters.component.ts

    r28198a1 r13cbe66  
    33import { first } from 'rxjs/operators';
    44
     5import { WaterDetailsComponent } from './';
    56import { User, UsersService, Water, WatersService } from '../../../src-gen/gnuboat-mapservice';
    67import { AuthenticationService } from '../services';
    … …  
    89@Component({
    910  selector: 'gnuboat-waters',
    10   templateUrl: 'waters.component.html'
     11  templateUrl: 'waters.component.html',
    1112})
    1213export class WatersComponent implements OnInit, OnDestroy {
  • src/mapservice-webclient/src/css/GnuBoat.Mapservice.Webclient.css

    r28198a1 r13cbe66  
    123123}
    124124
    125 .water h2 {
     125.water a, .water a:link, .water a:visited, .water a:hover, .water a:active {
     126  text-decoration: None;
     127  color: inherit;
     128}
     129
     130.water a h2 {
    126131  padding: 0.8em;
    127132  margin: 0;
  • src/mapservice-webclient/src/tsconfig.app.json

    r28198a1 r13cbe66  
    1111        "app/*"
    1212      ]
    13     }
     13    },
    1414    "outDir": "../out-tsc/app",
    1515    "types": []
  • src/mapservice/codegen/code_generator

    r28198a1 r13cbe66  
    22
    33DIR=`dirname "$0"`
     4TARGET="${DIR}/../src-gen/openapi_server/"
    45
    56echo "Preparing symlinks"
    6 cd ${DIR}/../src-gen/openapi_server/
     7mkdir -p "${TARGET}"
     8cd "${TARGET}"
    79if [ ! -L server_impl ]; then
    810        ln -s ../../src/server_impl/
  • src/mapservice/codegen/templates/__main__.mustache

    r28198a1 r13cbe66  
    88import connexion
    99from flask_cors import CORS
    10 from flask import render_template
     10#from flask import render_template
     11import flask
     12from sqlalchemy import event
    1113
    1214from {{packageName}} import encoder
    1315
    1416from {{packageName}}.server_impl.database.Model import db, User, ApiKey, db_test_setup
     17
     18from {{packageName}}.server_impl.ValidatorWorkaround import ValidatorWorkaround
    1519
    1620app = connexion.App(__name__, specification_dir='./openapi/')
    … …  
    2024@application.before_first_request
    2125def create_database():
     26        @event.listens_for(db.engine, "connect")
     27        def load_spatialite(dbapi_conn, connection_record):
     28                if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
     29                        # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
     30                        dbapi_conn.enable_load_extension(True)
     31                        dbapi_conn.load_extension('/usr/local/lib64/mod_spatialite')
     32
    2233        db_test_setup()
    2334
    … …  
    2839def main():
    2940        application.json_encoder = encoder.JSONEncoder
    30         app.add_api('openapi.yaml', arguments={'title': '{{appName}}'}, validate_responses=True)
     41        app.add_api('openapi.yaml', arguments={'title': '{{appName}}'}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
    3142        application.config.from_object('{{packageName}}.server_impl.Config.DevelopmentConfig')
    3243
  • src/mapservice/codegen/templates/requirements.mustache

    r28198a1 r13cbe66  
    1 connexion == 2.0.2
     1connexion == 2.2.0
    22swagger-ui-bundle == 0.0.2
    33python_dateutil == 2.6.0
    … …  
    88flask-sqlalchemy
    99flask-cors
     10shapely
  • src/mapservice/openapi.yaml

    r28198a1 r13cbe66  
    8181          description: CORS prefilght requests should return 200 as status code
    8282          content:
    83            application/json: {}
     83            application/json: {}
    8484  '/user/apikey_create':
    8585    get:
    … …  
    9898              schema:
    9999                $ref: '#/components/schemas/apiKeys'
    100               example: 'NewApiKey4711'
     100              example: NewApiKey4711
    101101        '400':
    102102          $ref: '#/components/responses/BadRequest'
    … …  
    119119          schema:
    120120            $ref: '#/components/schemas/apiKey'
    121           example: 'DelApiKey4711'
     121          example: DelApiKey4711
    122122      responses:
    123123        '200':
    … …  
    127127              schema:
    128128                $ref: '#/components/schemas/apiKeys'
    129               example: 'ApiKey4711'
     129              example: ApiKey4711
    130130        '400':
    131131          $ref: '#/components/responses/BadRequest'
    132132        '401':
    133133          $ref: '#/components/responses/Unauthorized'
     134        '404':
     135          $ref: '#/components/responses/NotFound'
    134136  '/user/activate/{activation_code}':
    135137    get:
    … …  
    146148          schema:
    147149            $ref: '#/components/schemas/activationCode'
    148           example: 'dac9630aec642a428cd73f4be0a03569'
     150          example: dac9630aec642a428cd73f4be0a03569
    149151      responses:
    150152        '302':
    … …  
    154156              schema:
    155157                type: string
    156               description: URL to the website, showing the result of the activation
    157   /waters:
     158              description: 'URL to the website, showing the result of the activation'
     159  '/waters':
    158160    get:
    159161      description: Returns all waters
    … …  
    167169          schema:
    168170            $ref: '#/components/schemas/itemName'
    169           example: 'Missi'
     171          example: Missi
    170172        - name: manager
    171173          in: query
    172174          schema:
    173175            $ref: '#/components/schemas/username'
    174           example: 'jane'
     176          example: jane
    175177        - $ref: '#/components/parameters/orderBy'
    176178        - $ref: '#/components/parameters/offset'
    … …  
    186188                Waters:
    187189                  $ref: '#/components/examples/waters'
     190        '404':
     191          $ref: '#/components/responses/NotFound'
    188192    post:
    189193      description: Adds a new water to the database
    … …  
    200204            schema:
    201205              $ref: '#/components/schemas/WaterCreation'
    202             example: 
     206            example:
    203207              name: Rhein
    204208              osmId: 1756854
    205               osmType: 'Relation'
     209              osmType: Relation
    206210      responses:
    207211        '201':
    … …  
    224228        - waters
    225229      summary: Represents a water
    226       operationId: waterGetById
     230      operationId: watersGetById
    227231      parameters:
    228232        - name: id
    … …  
    242246                Water:
    243247                  $ref: '#/components/examples/Water'
     248        '404':
     249          $ref: '#/components/responses/NotFound'
     250  '/waters/{water_id}/gauges':
     251    get:
     252      description: Returns all gauges of water waterId
     253      tags:
     254        - waters
     255      summary: Find gauges of water waterId by gaugeId
     256      operationId: watersGaugesGet
     257      parameters:
     258        - name: water_id
     259          in: path
     260          description: Water ID
     261          required: true
     262          schema:
     263            $ref: '#/components/schemas/itemId'
     264        - name: name
     265          in: query
     266          schema:
     267            $ref: '#/components/schemas/itemName'
     268          example: Missi
     269        - name: manager
     270          in: query
     271          schema:
     272            $ref: '#/components/schemas/username'
     273          example: jane
     274        - $ref: '#/components/parameters/orderBy'
     275        - $ref: '#/components/parameters/offset'
     276        - $ref: '#/components/parameters/limit'
     277      responses:
     278        '200':
     279          description: OK
     280          content:
     281            application/json:
     282              schema:
     283                $ref: '#/components/schemas/Gauges'
     284              examples:
     285                Gauges:
     286                  $ref: '#/components/examples/Gauges'
     287            application/geo+json:
     288              schema:
     289                $ref: '#/components/schemas/GaugesGeoJson'
     290              examples:
     291                Gauge:
     292                  $ref: '#/components/examples/GaugesGeoJson'
     293    post:
     294      description: Adds a new gauge for water waterId to the database
     295      tags:
     296        - waters
     297      summary: Add a new water
     298      operationId: watersGaugeCreate
     299      parameters:
     300        - name: water_id
     301          in: path
     302          description: Water ID
     303          required: true
     304          schema:
     305            $ref: '#/components/schemas/itemId'
     306      security:
     307        - basicAuth: []
     308        - apiKeyAuth: []
     309      requestBody:
     310        content:
     311          application/json:
     312            schema:
     313              $ref: '#/components/schemas/GaugeCreation'
     314            example:
     315              name: New Orleans
     316              location:
     317                - 90.136111
     318                - 29.934722
     319      responses:
     320        '201':
     321          description: Gauge created
     322          content:
     323            application/json:
     324              schema:
     325                $ref: '#/components/schemas/Gauge'
     326              examples:
     327                Gauge:
     328                  $ref: '#/components/examples/Gauge'
     329            application/geo+json:
     330              schema:
     331                $ref: '#/components/schemas/GaugeGeoJson'
     332              examples:
     333                Gauge:
     334                  $ref: '#/components/examples/GaugeGeoJson'
     335        '400':
     336          $ref: '#/components/responses/BadRequest'
     337        '401':
     338          $ref: '#/components/responses/Unauthorized'
     339  '/waters/{water_id}/gauges/{gauge_id}':
     340    get:
     341      description: Returns the gauge identified by id
     342      tags:
     343        - waters
     344      summary: Represents a gauge
     345      operationId: watersGaugeGetById
     346      parameters:
     347        - name: water_id
     348          in: path
     349          description: Water ID
     350          required: true
     351          schema:
     352            $ref: '#/components/schemas/itemId'
     353        - name: gauge_id
     354          in: path
     355          description: Gauge ID
     356          required: true
     357          schema:
     358            $ref: '#/components/schemas/itemId'
     359      responses:
     360        '200':
     361          description: OK
     362          content:
     363            application/json:
     364              schema:
     365                $ref: '#/components/schemas/Gauge'
     366              examples:
     367                Gauge:
     368                  $ref: '#/components/examples/Gauge'
     369            application/geo+json:
     370              schema:
     371                $ref: '#/components/schemas/GaugeGeoJson'
     372              examples:
     373                Gauge:
     374                  $ref: '#/components/examples/GaugeGeoJson'
     375        '400':
     376          $ref: '#/components/responses/BadRequest'
    244377        '404':
    245378          $ref: '#/components/responses/NotFound'
    … …  
    277410      title: Item Name
    278411      type: string
     412    order:
     413      title: order
     414      enum:
     415        - desc
     416        - asc
     417      type: string
     418      default: asc
     419      description: |
     420        Sort order:
     421          * `asc` - Ascending, from A to Z
     422          * `desc` - Descending, from Z to A
     423      example: asc
    279424    osmType:
    280425      title: OSM type of item (N|W|R)
    … …  
    284429        - Way
    285430        - Relation
     431    comment:
     432      title: Comment of an item
     433      type: string
     434    point:
     435      title: 'Point of type [longitude, latitude]'
     436      type: array
     437      maxItems: 2
     438      minItems: 2
     439      items:
     440        type: number
     441    geoJsonType:
     442      title: Type of GeoJSON objects
     443      type: string
     444      enum:
     445        - Feature
     446        - Point
     447    geoJsonPoint:
     448      type: object
     449      description: GeoJSon geometry
     450      externalDocs:
     451        url: 'http://geojson.org/geojson-spec.html#id2'
     452      properties:
     453        type:
     454          type: string
     455        coordinates:
     456          $ref: '#/components/schemas/point'
    286457    User:
    287458      title: User
    … …  
    334505        osmType:
    335506          $ref: '#/components/schemas/osmType'
     507        gauges:
     508          $ref: '#/components/schemas/Gauges'
    336509      required:
    337510        - waterId
    … …  
    354527      items:
    355528        $ref: '#/components/schemas/Water'
    356     order:
    357       title: order
    358       enum:
    359         - desc
    360         - asc
    361       type: string
    362       default: asc
    363       description: |
    364         Sort order:
    365           * `asc` - Ascending, from A to Z
    366           * `desc` - Descending, from Z to A
    367       example: asc
     529    Gauge:
     530      title: Gauge
     531      type: object
     532      properties:
     533        gaugeId:
     534          $ref: '#/components/schemas/itemId'
     535        name:
     536          $ref: '#/components/schemas/itemName'
     537        manager:
     538          $ref: '#/components/schemas/username'
     539        location:
     540          $ref: '#/components/schemas/point'
     541        comment:
     542          $ref: '#/components/schemas/comment'
     543      required:
     544        - gaugeId
     545        - name
     546        - location
     547    GaugeCreation:
     548      title: Gauge for Creation
     549      type: object
     550      properties:
     551        name:
     552          $ref: '#/components/schemas/itemName'
     553        location:
     554          $ref: '#/components/schemas/point'
     555        comment:
     556          $ref: '#/components/schemas/comment'
     557      required:
     558        - name
     559        - location
     560    Gauges:
     561      title: Gauges
     562      type: array
     563      items:
     564        $ref: '#/components/schemas/Gauge'
     565    GaugeGeoJson:
     566      title: Gauge
     567      type: object
     568      properties:
     569        type:
     570          $ref: '#/components/schemas/geoJsonType'
     571        geometry:
     572          $ref: '#/components/schemas/geoJsonPoint'
     573        properties:
     574          type: object
     575          properties:
     576            name:
     577              $ref: '#/components/schemas/itemName'
     578            manager:
     579              $ref: '#/components/schemas/username'
     580            comment:
     581              $ref: '#/components/schemas/comment'
     582          required:
     583            - name
     584      required:
     585        - type
     586        - geometry
     587        - properties
     588    GaugesGeoJson:
     589      title: Gauges in GeoJson format
     590      type: array
     591      items:
     592        $ref: '#/components/schemas/GaugeGeoJson'
    368593    HttpError:
    369594      title: HTTP Error Response Object
    … …  
    385610        type: string
    386611        default: name
    387         example: 'name'
     612        example: name
    388613    order:
    389614      name: order
    … …  
    443668        name: Mississippi
    444669        osmId: 1756854
    445         osmType: 'Relation'
     670        osmType: Relation
    446671      summary: A water example object for creation of a water
    447672    waters:
    448673      value:
    449674        - waterId: 1
    450           name: 'Mississippi'
     675          name: Mississippi
    451676          osmId: 1756854
    452           osmType: 'Relation'
     677          osmType: Relation
    453678        - waterId: 2
    454           name: 'Bodensee'
     679          name: Bodensee
    455680      summary: A sample list with waters
     681    Gauge:
     682      value:
     683        gaugeId: 1
     684        name: New Orleans
     685        manager: jane
     686        location:
     687          - 90.136111
     688          - 29.934722
     689        comment: Gauge for Mississippi in New Orleans
     690    Gauges:
     691      value:
     692        - gaugeId: 1
     693          name: New Orleans
     694          manager: jane
     695          location:
     696            - 90.136111
     697            - 29.934722
     698      summary: A sample list of gauges
     699    GaugeGeoJson:
     700      value:
     701        type: Feature
     702        geometry:
     703          type: Point
     704          coordinates:
     705            - 90.136111
     706            - 29.934722
     707          properties:
     708            name: New Orleans
     709            manager: jane
     710            comment: Gauge for Mississippi in New Orleans
     711    GaugesGeoJson:
     712      value:
     713        - type: Feature
     714          geometry:
     715            type: Point
     716            coordinates:
     717              - 90.136111
     718              - 29.934722
     719            properties:
     720              name: New Orleans
     721              manager: jane
     722              comment: Gauge for Mississippi in New Orleans
     723      summary: A sample list of gauges in GeoJson format
    456724    HttpError:
    457725      value:
    … …  
    492760      Sea)
    493761  - name: users
    494     description: >-
    495       All actions used to manage users and api keys
     762    description: All actions used to manage users and api keys
  • src/mapservice/src-gen/.openapi-generator/VERSION

    r28198a1 r13cbe66  
    1 3.3.4
     14.0.0
  • src/mapservice/src-gen/openapi_server/__main__.py

    r28198a1 r13cbe66  
    33import connexion
    44from flask_cors import CORS
    5 from flask import render_template
     5#from flask import render_template
     6import flask
     7from sqlalchemy import event
    68
    79from openapi_server import encoder
    810
    911from openapi_server.server_impl.database.Model import db, User, ApiKey, db_test_setup
     12
     13from openapi_server.server_impl.ValidatorWorkaround import ValidatorWorkaround
    1014
    1115app = connexion.App(__name__, specification_dir='./openapi/')
    … …  
    1519@application.before_first_request
    1620def create_database():
     21        @event.listens_for(db.engine, "connect")
     22        def load_spatialite(dbapi_conn, connection_record):
     23                if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
     24                        # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
     25                        dbapi_conn.enable_load_extension(True)
     26                        dbapi_conn.load_extension('/usr/local/lib64/mod_spatialite')
     27
    1728        db_test_setup()
    1829
    … …  
    2334def main():
    2435        application.json_encoder = encoder.JSONEncoder
    25         app.add_api('openapi.yaml', arguments={'title': 'GNUBoat Mapservice API'}, validate_responses=True)
     36        app.add_api('openapi.yaml', arguments={'title': 'GNUBoat Mapservice API'}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
    2637        application.config.from_object('openapi_server.server_impl.Config.DevelopmentConfig')
    2738
  • src/mapservice/src-gen/openapi_server/controllers/waters_controller.py

    r28198a1 r13cbe66  
    22import six
    33
     4from openapi_server.models.gauge import Gauge  # noqa: E501
     5from openapi_server.models.gauge_creation import GaugeCreation  # noqa: E501
    46from openapi_server.models.http_error import HttpError  # noqa: E501
    57from openapi_server.models.water import Water  # noqa: E501
    68from openapi_server.models.water_creation import WaterCreation  # noqa: E501
    79from openapi_server import util
    8 
    9 from openapi_server.server_impl.controllers import WatersController
    10 
    11 def water_get_by_id(id):  # noqa: E501
    12     """Represents a water
    13 
    14     Returns the water identified by id # noqa: E501
    15 
    16     :param id: Item ID
    17     :type id: int
    18 
    19     :rtype: Water
    20     """
    21     return WatersController.water_get_by_id(id)
    2210
    2311from openapi_server.server_impl.controllers import WatersController
    … …  
    3624        water_creation = WaterCreation.from_dict(connexion.request.get_json())  # noqa: E501
    3725    return WatersController.waters_create(water_creation=water_creation)
     26
     27from openapi_server.server_impl.controllers import WatersController
     28
     29def waters_gauge_create(water_id, gauge_creation=None):  # noqa: E501
     30    """Add a new water
     31
     32    Adds a new gauge for water waterId to the database # noqa: E501
     33
     34    :param water_id: Water ID
     35    :type water_id: int
     36    :param gauge_creation:
     37    :type gauge_creation: dict | bytes
     38
     39    :rtype: Gauge
     40    """
     41    if connexion.request.is_json:
     42        gauge_creation = GaugeCreation.from_dict(connexion.request.get_json())  # noqa: E501
     43    return WatersController.waters_gauge_create(water_id, gauge_creation=gauge_creation)
     44
     45from openapi_server.server_impl.controllers import WatersController
     46
     47def waters_gauge_get_by_id(water_id, gauge_id):  # noqa: E501
     48    """Represents a gauge
     49
     50    Returns the gauge identified by id # noqa: E501
     51
     52    :param water_id: Water ID
     53    :type water_id: int
     54    :param gauge_id: Gauge ID
     55    :type gauge_id: int
     56
     57    :rtype: Gauge
     58    """
     59    return WatersController.waters_gauge_get_by_id(water_id, gauge_id)
     60
     61from openapi_server.server_impl.controllers import WatersController
     62
     63def waters_gauges_get(water_id, name=None, manager=None, order_by=None, offset=None, limit=None):  # noqa: E501
     64    """Find gauges of water waterId by gaugeId
     65
     66    Returns all gauges of water waterId # noqa: E501
     67
     68    :param water_id: Water ID
     69    :type water_id: int
     70    :param name:
     71    :type name: str
     72    :param manager:
     73    :type manager: str
     74    :param order_by: Order by field: name
     75    :type order_by: str
     76    :param offset: Skip over a number of elements by specifying an offset value for the query
     77    :type offset: int
     78    :param limit: Limit the number of elements on the response
     79    :type limit: int
     80
     81    :rtype: List[Gauge]
     82    """
     83    return WatersController.waters_gauges_get(water_id, name=name, manager=manager, order_by=order_by, offset=offset, limit=limit)
    3884
    3985from openapi_server.server_impl.controllers import WatersController
    … …  
    58104    """
    59105    return WatersController.waters_get(name=name, manager=manager, order_by=order_by, offset=offset, limit=limit)
     106
     107from openapi_server.server_impl.controllers import WatersController
     108
     109def waters_get_by_id(id):  # noqa: E501
     110    """Represents a water
     111
     112    Returns the water identified by id # noqa: E501
     113
     114    :param id: Item ID
     115    :type id: int
     116
     117    :rtype: Water
     118    """
     119    return WatersController.waters_get_by_id(id)
  • src/mapservice/src-gen/openapi_server/models/__init__.py

    r28198a1 r13cbe66  
    44from __future__ import absolute_import
    55# import models into model package
     6from openapi_server.models.gauge import Gauge
     7from openapi_server.models.gauge_creation import GaugeCreation
     8from openapi_server.models.gauge_geo_json import GaugeGeoJson
     9from openapi_server.models.gauge_geo_json_properties import GaugeGeoJsonProperties
     10from openapi_server.models.geo_json_point import GeoJsonPoint
     11from openapi_server.models.geo_json_type import GeoJsonType
    612from openapi_server.models.http_error import HttpError
    713from openapi_server.models.order import Order
  • src/mapservice/src-gen/openapi_server/models/water.py

    r28198a1 r13cbe66  
    77
    88from openapi_server.models.base_model_ import Model
     9from openapi_server.models.gauge import Gauge
     10from openapi_server.models.osm_type import OsmType
    911from openapi_server import util
    1012
     13from openapi_server.models.gauge import Gauge  # noqa: E501
    1114from openapi_server.models.osm_type import OsmType  # noqa: E501
    1215
    … …  
    1720    """
    1821
    19     def __init__(self, water_id=None, name=None, manager=None, osm_id=None, osm_type=None):  # noqa: E501
     22    def __init__(self, water_id=None, name=None, manager=None, osm_id=None, osm_type=None, gauges=None):  # noqa: E501
    2023        """Water - a model defined in OpenAPI
    2124
    … …  
    3033        :param osm_type: The osm_type of this Water.  # noqa: E501
    3134        :type osm_type: OsmType
     35        :param gauges: The gauges of this Water.  # noqa: E501
     36        :type gauges: List[Gauge]
    3237        """
    3338        self.openapi_types = {
    … …  
    3641            'manager': str,
    3742            'osm_id': int,
    38             'osm_type': OsmType
     43            'osm_type': OsmType,
     44            'gauges': List[Gauge]
    3945        }
    4046
    … …  
    4450            'manager': 'manager',
    4551            'osm_id': 'osmId',
    46             'osm_type': 'osmType'
     52            'osm_type': 'osmType',
     53            'gauges': 'gauges'
    4754        }
    4855
    … …  
    5259        self._osm_id = osm_id
    5360        self._osm_type = osm_type
     61        self._gauges = gauges
    5462
    5563    @classmethod
    … …  
    172180
    173181        self._osm_type = osm_type
     182
     183    @property
     184    def gauges(self):
     185        """Gets the gauges of this Water.
     186
     187
     188        :return: The gauges of this Water.
     189        :rtype: List[Gauge]
     190        """
     191        return self._gauges
     192
     193    @gauges.setter
     194    def gauges(self, gauges):
     195        """Sets the gauges of this Water.
     196
     197
     198        :param gauges: The gauges of this Water.
     199        :type gauges: List[Gauge]
     200        """
     201
     202        self._gauges = gauges
  • src/mapservice/src-gen/openapi_server/models/water_creation.py

    r28198a1 r13cbe66  
    77
    88from openapi_server.models.base_model_ import Model
     9from openapi_server.models.osm_type import OsmType
    910from openapi_server import util
    1011
  • src/mapservice/src-gen/openapi_server/openapi/openapi.yaml

    r28198a1 r13cbe66  
    2323      default: v1
    2424tags:
    25 - description: A water is a river (like Mississippi, lake (Lake Ontario), or a sea (North Sea)
     25- description: A water is a river (like Mississippi, lake (Lake Ontario), or a sea
     26    (North Sea)
    2627  name: waters
    2728- description: All actions used to manage users and api keys
    … …  
    3031  /user:
    3132    get:
    32       description: Returns information for a user
     33      description: Returns information of current/authorized user
    3334      operationId: users_get
    3435      responses:
    … …  
    112113      - users
    113114      x-openapi-router-controller: openapi_server.controllers.users_controller
     115  /user/activate/{activation_code}:
     116    get:
     117      description: Activates a user account
     118      operationId: users_activate
     119      parameters:
     120      - description: Activation code
     121        example: dac9630aec642a428cd73f4be0a03569
     122        explode: false
     123        in: path
     124        name: activation_code
     125        required: true
     126        schema:
     127          $ref: '#/components/schemas/activationCode'
     128        style: simple
     129      responses:
     130        302:
     131          description: OK or not OK
     132          headers:
     133            Location:
     134              description: URL to the website, showing the result of the activation
     135              explode: false
     136              schema:
     137                type: string
     138              style: simple
     139      summary: Activates a user account
     140      tags:
     141      - users
     142      x-openapi-router-controller: openapi_server.controllers.users_controller
    114143  /user/apikey_create:
    115144    get:
    … …  
    144173      security:
    145174      - basicAuth: []
    146       - apiKeyAuth: []
    147175      summary: Returns a new API key
    148176      tags:
    … …  
    189217                $ref: '#/components/schemas/HttpError'
    190218          description: Unauthorized (401) acces to resource
     219        404:
     220          content:
     221            application/json:
     222              examples:
     223                HttpError:
     224                  $ref: '#/components/examples/HttpError'
     225              schema:
     226                $ref: '#/components/schemas/HttpError'
     227          description: Water with given Id not found
    191228      security:
    192229      - basicAuth: []
    193       - apiKeyAuth: []
    194230      summary: Deletes API key
    195       tags:
    196       - users
    197       x-openapi-router-controller: openapi_server.controllers.users_controller
    198   /user/activate/{activation_code}:
    199     get:
    200       description: Activates a user account
    201       operationId: users_activate
    202       parameters:
    203       - description: Activation code
    204         example: dac9630aec642a428cd73f4be0a03569
    205         explode: false
    206         in: path
    207         name: activation_code
    208         required: true
    209         schema:
    210           $ref: '#/components/schemas/activationCode'
    211         style: simple
    212       responses:
    213         302:
    214           description: OK or not OK
    215           headers:
    216             Location:
    217               description: URL to the website, showing the result of the activation
    218               explode: false
    219               schema:
    220                 type: string
    221               style: simple
    222       summary: Activates a user account
    223231      tags:
    224232      - users
    … …  
    255263          type: string
    256264        style: form
    257       - description: Skip over a number of elements by specifying an offset value for the query
     265      - description: Skip over a number of elements by specifying an offset value
     266          for the query
    258267        explode: true
    259268        in: query
    … …  
    287296                $ref: '#/components/schemas/waters'
    288297          description: OK
     298        404:
     299          content:
     300            application/json:
     301              examples:
     302                HttpError:
     303                  $ref: '#/components/examples/HttpError'
     304              schema:
     305                $ref: '#/components/schemas/HttpError'
     306          description: Water with given Id not found
    289307      summary: Find waters by id
    290308      tags:
    … …  
    341359    get:
    342360      description: Returns the water identified by id
    343       operationId: water_get_by_id
     361      operationId: waters_get_by_id
    344362      parameters:
    345363      - description: Item ID
    … …  
    371389          description: Water with given Id not found
    372390      summary: Represents a water
     391      tags:
     392      - waters
     393      x-openapi-router-controller: openapi_server.controllers.waters_controller
     394  /waters/{water_id}/gauges:
     395    get:
     396      description: Returns all gauges of water waterId
     397      operationId: waters_gauges_get
     398      parameters:
     399      - description: Water ID
     400        explode: false
     401        in: path
     402        name: water_id
     403        required: true
     404        schema:
     405          $ref: '#/components/schemas/itemId'
     406        style: simple
     407      - example: Missi
     408        explode: true
     409        in: query
     410        name: name
     411        required: false
     412        schema:
     413          $ref: '#/components/schemas/itemName'
     414        style: form
     415      - example: jane
     416        explode: true
     417        in: query
     418        name: manager
     419        required: false
     420        schema:
     421          $ref: '#/components/schemas/username'
     422        style: form
     423      - description: 'Order by field: name'
     424        explode: true
     425        in: query
     426        name: orderBy
     427        required: false
     428        schema:
     429          default: name
     430          example: name
     431          type: string
     432        style: form
     433      - description: Skip over a number of elements by specifying an offset value
     434          for the query
     435        explode: true
     436        in: query
     437        name: offset
     438        required: false
     439        schema:
     440          default: 0
     441          example: 0
     442          format: int32
     443          type: integer
     444        style: form
     445      - description: Limit the number of elements on the response
     446        explode: true
     447        in: query
     448        name: limit
     449        required: false
     450        schema:
     451          default: 10
     452          example: 10
     453          format: int32
     454          type: integer
     455        style: form
     456      responses:
     457        200:
     458          content:
     459            application/json:
     460              examples:
     461                Gauges:
     462                  $ref: '#/components/examples/Gauges'
     463              schema:
     464                $ref: '#/components/schemas/Gauges'
     465            application/geo+json:
     466              examples:
     467                Gauge:
     468                  $ref: '#/components/examples/GaugesGeoJson'
     469              schema:
     470                $ref: '#/components/schemas/GaugesGeoJson'
     471          description: OK
     472      summary: Find gauges of water waterId by gaugeId
     473      tags:
     474      - waters
     475      x-openapi-router-controller: openapi_server.controllers.waters_controller
     476    post:
     477      description: Adds a new gauge for water waterId to the database
     478      operationId: waters_gauge_create
     479      parameters:
     480      - description: Water ID
     481        explode: false
     482        in: path
     483        name: water_id
     484        required: true
     485        schema:
     486          $ref: '#/components/schemas/itemId'
     487        style: simple
     488      requestBody:
     489        content:
     490          application/json:
     491            example:
     492              name: New Orleans
     493              location:
     494              - 90.136111
     495              - 29.934722
     496            schema:
     497              $ref: '#/components/schemas/GaugeCreation'
     498      responses:
     499        201:
     500          content:
     501            application/json:
     502              examples:
     503                Gauge:
     504                  $ref: '#/components/examples/Gauge'
     505              schema:
     506                $ref: '#/components/schemas/Gauge'
     507            application/geo+json:
     508              examples:
     509                Gauge:
     510                  $ref: '#/components/examples/GaugeGeoJson'
     511              schema:
     512                $ref: '#/components/schemas/GaugeGeoJson'
     513          description: Gauge created
     514        400:
     515          content:
     516            application/json:
     517              examples:
     518                HttpError:
     519                  $ref: '#/components/examples/HttpError'
     520              schema:
     521                $ref: '#/components/schemas/HttpError'
     522          description: Bad Request (400)
     523        401:
     524          content:
     525            application/json:
     526              examples:
     527                HttpError:
     528                  $ref: '#/components/examples/HttpError'
     529              schema:
     530                $ref: '#/components/schemas/HttpError'
     531          description: Unauthorized (401) acces to resource
     532      security:
     533      - basicAuth: []
     534      - apiKeyAuth: []
     535      summary: Add a new water
     536      tags:
     537      - waters
     538      x-openapi-router-controller: openapi_server.controllers.waters_controller
     539  /waters/{water_id}/gauges/{gauge_id}:
     540    get:
     541      description: Returns the gauge identified by id
     542      operationId: waters_gauge_get_by_id
     543      parameters:
     544      - description: Water ID
     545        explode: false
     546        in: path
     547        name: water_id
     548        required: true
     549        schema:
     550          $ref: '#/components/schemas/itemId'
     551        style: simple
     552      - description: Gauge ID
     553        explode: false
     554        in: path
     555        name: gauge_id
     556        required: true
     557        schema:
     558          $ref: '#/components/schemas/itemId'
     559        style: simple
     560      responses:
     561        200:
     562          content:
     563            application/json:
     564              examples:
     565                Gauge:
     566                  $ref: '#/components/examples/Gauge'
     567              schema:
     568                $ref: '#/components/schemas/Gauge'
     569            application/geo+json:
     570              examples:
     571                Gauge:
     572                  $ref: '#/components/examples/GaugeGeoJson'
     573              schema:
     574                $ref: '#/components/schemas/GaugeGeoJson'
     575          description: OK
     576        400:
     577          content:
     578            application/json:
     579              examples:
     580                HttpError:
     581                  $ref: '#/components/examples/HttpError'
     582              schema:
     583                $ref: '#/components/schemas/HttpError'
     584          description: Bad Request (400)
     585        404:
     586          content:
     587            application/json:
     588              examples:
     589                HttpError:
     590                  $ref: '#/components/examples/HttpError'
     591              schema:
     592                $ref: '#/components/schemas/HttpError'
     593          description: Water with given Id not found
     594      summary: Represents a gauge
    373595      tags:
    374596      - waters
    … …  
    414636      - waterId: 2
    415637        name: Bodensee
     638    Gauge:
     639      value:
     640        gaugeId: 1
     641        name: New Orleans
     642        manager: jane
     643        location:
     644        - 90.136111
     645        - 29.934722
     646        comment: Gauge for Mississippi in New Orleans
     647    Gauges:
     648      summary: A sample list of gauges
     649      value:
     650      - gaugeId: 1
     651        name: New Orleans
     652        manager: jane
     653        location:
     654        - 90.136111
     655        - 29.934722
     656    GaugeGeoJson:
     657      value:
     658        type: Feature
     659        geometry:
     660          type: Point
     661          coordinates:
     662          - 90.136111
     663          - 29.934722
     664          properties:
     665            name: New Orleans
     666            manager: jane
     667            comment: Gauge for Mississippi in New Orleans
     668    GaugesGeoJson:
     669      summary: A sample list of gauges in GeoJson format
     670      value:
     671      - type: Feature
     672        geometry:
     673          type: Point
     674          coordinates:
     675          - 90.136111
     676          - 29.934722
     677          properties:
     678            name: New Orleans
     679            manager: jane
     680            comment: Gauge for Mississippi in New Orleans
    416681    HttpError:
    417682      value:
    … …  
    440705      style: form
    441706    offset:
    442       description: Skip over a number of elements by specifying an offset value for the query
     707      description: Skip over a number of elements by specifying an offset value for
     708        the query
    443709      explode: true
    444710      in: query
    … …  
    513779      title: Item Name
    514780      type: string
     781    order:
     782      default: asc
     783      description: |
     784        Sort order:
     785          * `asc` - Ascending, from A to Z
     786          * `desc` - Descending, from Z to A
     787      enum:
     788      - desc
     789      - asc
     790      example: asc
     791      title: order
     792      type: string
    515793    osmType:
    516794      enum:
    … …  
    520798      title: OSM type of item (N|W|R)
    521799      type: string
     800    comment:
     801      title: Comment of an item
     802      type: string
     803    point:
     804      items:
     805        type: number
     806      maxItems: 2
     807      minItems: 2
     808      title: Point of type [longitude, latitude]
     809      type: array
     810    geoJsonType:
     811      enum:
     812      - Feature
     813      - Point
     814      title: Type of GeoJSON objects
     815      type: string
     816    geoJsonPoint:
     817      description: GeoJSon geometry
     818      externalDocs:
     819        url: http://geojson.org/geojson-spec.html#id2
     820      properties:
     821        type:
     822          type: string
     823        coordinates:
     824          items:
     825            type: number
     826          maxItems: 2
     827          minItems: 2
     828          title: Point of type [longitude, latitude]
     829          type: array
     830      type: object
    522831    User:
    523832      example:
    … …  
    581890        osmId: 6
    582891        name: name
     892        gauges:
     893        - manager: manager
     894          name: name
     895          location:
     896          - 5.962133916683182
     897          - 5.962133916683182
     898          comment: comment
     899          gaugeId: 1
     900        - manager: manager
     901          name: name
     902          location:
     903          - 5.962133916683182
     904          - 5.962133916683182
     905          comment: comment
     906          gaugeId: 1
    583907        waterId: 0
    584908      properties:
    … …  
    599923        osmType:
    600924          $ref: '#/components/schemas/osmType'
     925        gauges:
     926          items:
     927            $ref: '#/components/schemas/Gauge'
     928          title: Gauges
     929          type: array
    601930      required:
    602931      - name
    … …  
    627956      title: waters
    628957      type: array
    629     order:
    630       default: asc
    631       description: |
    632         Sort order:
    633           * `asc` - Ascending, from A to Z
    634           * `desc` - Descending, from Z to A
    635       enum:
    636       - desc
    637       - asc
    638       example: asc
    639       title: order
    640       type: string
     958    Gauge:
     959      example:
     960        manager: manager
     961        name: name
     962        location:
     963        - 5.962133916683182
     964        - 5.962133916683182
     965        comment: comment
     966        gaugeId: 1
     967      properties:
     968        gaugeId:
     969          format: int32
     970          title: Item ID
     971          type: integer
     972        name:
     973          title: Item Name
     974          type: string
     975        manager:
     976          title: Username
     977          type: string
     978        location:
     979          items:
     980            type: number
     981          maxItems: 2
     982          minItems: 2
     983          title: Point of type [longitude, latitude]
     984          type: array
     985        comment:
     986          title: Comment of an item
     987          type: string
     988      required:
     989      - gaugeId
     990      - location
     991      - name
     992      title: Gauge
     993      type: object
     994    GaugeCreation:
     995      example:
     996        name: name
     997        location:
     998        - 0.8008281904610115
     999        - 0.8008281904610115
     1000        comment: comment
     1001      properties:
     1002        name:
     1003          title: Item Name
     1004          type: string
     1005        location:
     1006          items:
     1007            type: number
     1008          maxItems: 2
     1009          minItems: 2
     1010          title: Point of type [longitude, latitude]
     1011          type: array
     1012        comment:
     1013          title: Comment of an item
     1014          type: string
     1015      required:
     1016      - location
     1017      - name
     1018      title: Gauge for Creation
     1019      type: object
     1020    Gauges:
     1021      items:
     1022        $ref: '#/components/schemas/Gauge'
     1023      title: Gauges
     1024      type: array
     1025    GaugeGeoJson:
     1026      properties:
     1027        type:
     1028          $ref: '#/components/schemas/geoJsonType'
     1029        geometry:
     1030          $ref: '#/components/schemas/geoJsonPoint'
     1031        properties:
     1032          $ref: '#/components/schemas/GaugeGeoJson_properties'
     1033      required:
     1034      - geometry
     1035      - properties
     1036      - type
     1037      title: Gauge
     1038      type: object
     1039    GaugesGeoJson:
     1040      items:
     1041        $ref: '#/components/schemas/GaugeGeoJson'
     1042      title: Gauges in GeoJson format
     1043      type: array
    6411044    HttpError:
    6421045      properties:
    6431046        code:
    644           format: int32
    6451047          type: integer
    6461048        message:
    … …  
    6511053      title: HTTP Error Response Object
    6521054      type: object
     1055    GaugeGeoJson_properties:
     1056      properties:
     1057        name:
     1058          title: Item Name
     1059          type: string
     1060        manager:
     1061          title: Username
     1062          type: string
     1063        comment:
     1064          title: Comment of an item
     1065          type: string
     1066      required:
     1067      - name
    6531068  securitySchemes:
    6541069    basicAuth:
  • src/mapservice/src-gen/openapi_server/test/test_waters_controller.py

    r28198a1 r13cbe66  
    77from six import BytesIO
    88
     9from openapi_server.models.gauge import Gauge  # noqa: E501
     10from openapi_server.models.gauge_creation import GaugeCreation  # noqa: E501
    911from openapi_server.models.http_error import HttpError  # noqa: E501
    1012from openapi_server.models.water import Water  # noqa: E501
    … …  
    1618    """WatersController integration test stubs"""
    1719
    18     def test_water_get_by_id(self):
    19         """Test case for water_get_by_id
    20 
    21         Represents a water
    22         """
    23         headers = {
    24         }
    25         response = self.client.open(
    26             '/mapservice/v1/waters/{id}'.format(id='56'),
    27             method='GET',
    28             headers=headers)
    29         self.assert200(response,
    30                        'Response body is : ' + response.data.decode('utf-8'))
    31 
    3220    def test_waters_create(self):
    3321        """Test case for waters_create
    … …  
    3523        Add a new water
    3624        """
    37         water_creation = WaterCreation()
     25        water_creation = {
     26  "osmId" : 0,
     27  "name" : "name"
     28}
    3829        headers = {
     30            'Accept': 'application/json',
     31            'Content-Type': 'application/json',
    3932            'X-API-KEY': 'test_key',
    40            
     33            'Authorization': 'BasicZm9vOmJhcg==',
    4134        }
    4235        response = self.client.open(
    … …  
    4639            data=json.dumps(water_creation),
    4740            content_type='application/json')
     41        self.assert200(response,
     42                       'Response body is : ' + response.data.decode('utf-8'))
     43
     44    def test_waters_gauge_create(self):
     45        """Test case for waters_gauge_create
     46
     47        Add a new water
     48        """
     49        gauge_creation = {
     50  "name" : "name",
     51  "location" : [ 0.8008281904610115, 0.8008281904610115 ],
     52  "comment" : "comment"
     53}
     54        headers = {
     55            'Accept': 'application/json',
     56            'Content-Type': 'application/json',
     57            'X-API-KEY': 'test_key',
     58            'Authorization': 'BasicZm9vOmJhcg==',
     59        }
     60        response = self.client.open(
     61            '/mapservice/v1/waters/{water_id}/gauges'.format(water_id='56'),
     62            method='POST',
     63            headers=headers,
     64            data=json.dumps(gauge_creation),
     65            content_type='application/json')
     66        self.assert200(response,
     67                       'Response body is : ' + response.data.decode('utf-8'))
     68
     69    def test_waters_gauge_get_by_id(self):
     70        """Test case for waters_gauge_get_by_id
     71
     72        Represents a gauge
     73        """
     74        headers = {
     75            'Accept': 'application/json',
     76        }
     77        response = self.client.open(
     78            '/mapservice/v1/waters/{water_id}/gauges/{gauge_id}'.format(water_id='56', gauge_id='56'),
     79            method='GET',
     80            headers=headers)
     81        self.assert200(response,
     82                       'Response body is : ' + response.data.decode('utf-8'))
     83
     84    def test_waters_gauges_get(self):
     85        """Test case for waters_gauges_get
     86
     87        Find gauges of water waterId by gaugeId
     88        """
     89        query_string = [('name', 'Missi'),
     90                        ('manager', 'jane'),
     91                        ('order_by', 'name'),
     92                        ('offset', '0'),
     93                        ('limit', '10')]
     94        headers = {
     95            'Accept': 'application/json',
     96        }
     97        response = self.client.open(
     98            '/mapservice/v1/waters/{water_id}/gauges'.format(water_id='56'),
     99            method='GET',
     100            headers=headers,
     101            query_string=query_string)
    48102        self.assert200(response,
    49103                       'Response body is : ' + response.data.decode('utf-8'))
    … …  
    60114                        ('limit', '10')]
    61115        headers = {
     116            'Accept': 'application/json',
    62117        }
    63118        response = self.client.open(
    … …  
    69124                       'Response body is : ' + response.data.decode('utf-8'))
    70125
     126    def test_waters_get_by_id(self):
     127        """Test case for waters_get_by_id
     128
     129        Represents a water
     130        """
     131        headers = {
     132            'Accept': 'application/json',
     133        }
     134        response = self.client.open(
     135            '/mapservice/v1/waters/{id}'.format(id='56'),
     136            method='GET',
     137            headers=headers)
     138        self.assert200(response,
     139                       'Response body is : ' + response.data.decode('utf-8'))
     140
    71141
    72142if __name__ == '__main__':
  • src/mapservice/src-gen/requirements.txt

    r28198a1 r13cbe66  
    1 connexion == 2.0.2
     1connexion == 2.2.0
    22swagger-ui-bundle == 0.0.2
    33python_dateutil == 2.6.0
    … …  
    55flask-sqlalchemy
    66flask-cors
     7shapely
  • src/mapservice/src/server_impl/controllers/WatersController.py

    r28198a1 r13cbe66  
    1717import connexion
    1818
    19 from ..database.Model import User, Water, db
     19from ..database.Model import User, Water, Gauge, db
    2020from ..HttpErrors import BadRequest, Unauthorized, NotFound
    2121from .UsersController import loggedin_user
    … …  
    4747        return result
    4848
    49 def water_get_by_id(id):
     49def waters_get_by_id(id):
    5050        water = Water.query.filter_by(id=id).all()
    5151        if len(water) != 1:
    … …  
    6262        db.session.commit()
    6363        return water.to_dict()
     64
     65def waters_gauge_get_by_id(water_id, gauge_id):
     66        water = Water.query.filter_by(id=water_id).all()
     67        if len(water) != 1:
     68                return BadRequest
     69        water = water[0]
     70
     71        gauge = Gauge.query.filter_by(water=water).filter_by(id=gauge_id).all()
     72        print(connexion.request.headers['Accept'])
     73        if len(gauge) != 1:
     74                return NotFound
     75        if connexion.request.headers['Accept'] == "application/geo+json":
     76                return gauge[0].to_geojson(), 200, {'Content-Type': 'application/geo+json; charset=utf-8'}
     77        return gauge[0].to_dict()
     78
     79
     80def waters_gauge_create(water_id, gauge_creation):
     81        user = loggedin_user()
     82        if user is None:
     83                return Unauthorized
     84       
     85        water = Water.query.filter_by(id=water_id).all()
     86        if len(water) != 1:
     87                return BadRequest
     88        water = water[0]
     89       
     90        location = 'SRID=4326;POINT({:.6} {:.6})'.format(gauge_creation.location[0], gauge_creation.location[1])
     91        gauge = Gauge(name=gauge_creation.name, manager=user, water=water, location=location, comment=gauge_creation.comment)
     92        db.session.add(gauge)
     93        db.session.commit()
     94        return gauge.to_dict()
     95
     96def waters_gauges_get(water_id, name, manager, order_by, offset, limit):
     97        water = Water.query.filter_by(id=water_id).all()
     98        if len(water) != 1:
     99                return BadRequest
     100       
     101        query = None
     102       
     103        if manager is not None:
     104                manager = User.query.filter_by(username=manager).all()
     105                if len(manager) != 1:
     106                        return NotFound
     107                manager = manager[0]
     108
     109        query = Gauge.query.filter_by(id=water_id)
     110        if manager is not None:
     111                if manager and name is not None:
     112                        query = query.filter_by(manager = manager).filter(Gauge.name.like('%{}%'.format(name)))
     113                elif manager:
     114                        query = query.filter_by(manager = manager)
     115        elif name is not None:
     116                query = query.filter(Gauge.name.like('%{}%'.format(name)))
     117       
     118        result = []
     119        for gauge in query.offset(offset).limit(limit):
     120                if connexion.request.headers['Accept'] == "application/geo+json":
     121                        result.append(gauge.to_geojson())
     122                else:
     123                        result.append(gauge.to_dict())
     124        return result
  • src/mapservice/src/server_impl/database/Model.py

    r28198a1 r13cbe66  
    1717import flask
    1818from flask_sqlalchemy import SQLAlchemy
    19 from sqlalchemy import inspect, text, Enum
     19from sqlalchemy import inspect, text, Enum, event, select, func
     20from geoalchemy2 import Geometry
     21from geoalchemy2.shape import to_shape
     22from shapely import wkb
    2023import hashlib
    2124import datetime
    … …  
    7881        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    7982        user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
    80         key = db.Column(db.String(255), nullable=False)
     83        key = db.Column(db.String(255), nullable=False, unique=True)
    8184        user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
    8285       
    … …  
    99102                if obj.osm_type:
    100103                        result['osmType'] = obj.osm_type.name
    101                 return result
    102 
    103 #class Gauge(db.Model):
    104         #__tablename__ = "gauges"
    105        
    106         #id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    107         #name = db.Column(db.String(255), nullable=False)
    108         #manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    109         #location = POINT
    110         #water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
    111         #comment = db.Column(db.String(255))
     104                if obj.gauges:
     105                        result['gauges'] = []
     106                        for gauge in obj.gauges:
     107                                result['gauges'].append(gauge.to_dict())
     108                return result
     109       
     110class Gauge(db.Model):
     111        __tablename__ = "gauges"
     112       
     113        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
     114        name = db.Column(db.String(255), nullable=False)
     115        manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
     116        water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
     117        # POINT(Lon Lat)
     118        location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
     119        comment = db.Column(db.String(255))
    112120        #osm_id = db.Column(db.Integer)
    113121        #osm_type = db.Column(db.String(255))
    114122        #osm_class = db.Column(db.String(255))
    115         #manager = db.relationship("User", backref=db.backref("users", order_by=username), lazy=True)
    116         #waters = db.relationship("Water", backref=db.backref("waters", order_by=label), lazy=True)
     123        manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
     124        water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
     125       
     126        def to_dict(obj):
     127                result = { 'gaugeId': obj.id, 'name': obj.name }
     128                if obj.manager:
     129                        result['manager'] = obj.manager.username
     130                location = Gauge.wkb_to_dict(obj.location)
     131                result['location'] = [location['longitude'], location['latitude']]
     132                if obj.comment:
     133                        result['comment'] = obj.comment
     134                return result
     135       
     136        def to_geojson(obj):
     137                location = Gauge.wkb_to_dict(obj.location)
     138                result = {
     139                        'type': 'Feature',
     140                        'geometry': {
     141                                'type': 'Point',
     142                                'coordinates': [location['longitude'], location['latitude']]
     143                        },
     144                        'properties': {
     145                                'name': obj.name
     146                        }
     147                }
     148                if obj.manager:
     149                        result['properties']['manager'] = obj.manager.username
     150                if obj.comment:
     151                        result['properties']['comment'] = obj.comment
     152                return result
     153       
     154        def wkb_to_dict(wkbelement):
     155                point = to_shape(wkbelement)
     156                return {'longitude': point.x, 'latitude': point.y}
    117157
    118158def db_test_setup():
     159        if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
     160                print("Initiate spatial meta data for Spatialite...")
     161                db.engine.execute(select([func.InitSpatialMetaData()]))
     162                print("...Finished")
    119163        db.create_all()
    120164       
    … …  
    122166                print("CREATING DATABASE TEST CONTENT")
    123167                with db.session.no_autoflush:
    124                         test_user_john = User.factory('john', 'testpass2', 'john@example.org')
    125                         test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
    126                        
    127                         test_user_jane = User.factory('jane', 'testpass', 'jane@example.org')
    128                         test_user_jane.activated = True
    129                         test_user_jane.first_name = 'Jane'
     168                        test_user_john = None
     169                        query = User.query.filter_by(username='john').all()
     170                        if len(query) == 1:
     171                                test_user_john = query[0]
     172                        else:
     173                                test_user_john = User.factory('john', 'testpass2', 'john@example.org')
     174                                test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
     175                                db.session.add(test_user_john)
     176                                db.session.commit()
     177                       
     178                        test_user_jane = None
     179                        query = User.query.filter_by(username='jane').all()
     180                        if len(query) == 1:
     181                                test_user_jane = query[0]
     182                        else:
     183                                test_user_jane = User.factory('jane', 'testpass', 'jane@example.org')
     184                                test_user_jane.activated = True
     185                                test_user_jane.first_name = 'Jane'
     186                                db.session.add(test_user_jane)
     187                                db.session.commit()
    130188                       
    131189                        test_key_del = ApiKey(user=test_user_jane, key='DelApiKey4711')
    132                         db.session.add(test_key_del)
    133                        
     190                        if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
     191                                db.session.add(test_key_del)
    134192                        if len(ApiKey.query.filter_by(key='test_key').all()) < 1:
    135193                                test_key = ApiKey(user=test_user_jane, key='test_key')
    … …  
    138196                                test_key = ApiKey(user=test_user_jane, key='ApiKey4712')
    139197                                db.session.add(test_key)
    140                         if len(Water.query.filter_by(name='Mississippi').all()) < 1:
     198                        mississippi = None
     199                        query = Water.query.filter_by(name='Mississippi').all()
     200                        if len(query) == 1:
     201                                mississippi = query[0]
     202                        else:
    141203                                mississippi = Water(name='Mississippi', manager=test_user_jane, osm_id=1756854, osm_type=OsmType.Relation)
    142204                                db.session.add(mississippi)
     205                                db.session.commit()
     206                       
    143207                        if len(Water.query.filter_by(name='Forggensee').all()) < 1:
    144                                 mississippi = Water(name='Forggensee', manager=test_user_john, osm_id=897899, osm_type=OsmType.Relation)
    145                                 db.session.add(mississippi)
     208                                forggensee = Water(name='Forggensee', manager=test_user_john, osm_id=897899, osm_type=OsmType.Relation)
     209                                db.session.add(forggensee)
     210                               
     211                        if len(Gauge.query.filter_by(name='New Orleans').all()) < 1:
     212                                new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)')
     213                                db.session.add(new_orleans)
    146214                        db.session.commit()
    147215
Note: See TracChangeset for help on using the changeset viewer.