Commit ad8dbf72 by Gil Sade

initial revision

parents
Pipeline #5 skipped in 0 seconds
/build/
/bin/
.gradle/
.settings
.idea
.lck
.project
.classpath
gradle/
group 'com.ipgallery'
version '1.0.0'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
maven { url "http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository" }
maven { url "http://172.16.1.132:8081/repository/internal" }
}
dependencies {
compile 'com.ipgallery:jinfra-utils:1.1.1'
compile 'com.ipgallery:jinfra-rabbitmq:1.0.0'
compile 'com.ipgallery:jinfra-grs:1.0.0'
compile 'com.ipgallery:jinfra-microservice:1.2.3'
compile 'com.ipgallery:jinfra-itc:1.0.0'
compile 'io.swagger:swagger-annotations:1.5.7'
compile 'org.slf4j:slf4j-simple:1.7.19'
compile 'com.javadocmd:simplelatlng:1.3.1'
}
jar {
manifest.attributes 'Main-Class': 'web.App'
from configurations.compile.collect { zipTree it }
// to remove "no manifiest section for signature"
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}
swagger: '2.0'
info:
version: 1.0.0
title: Location Service
description: |
* Generic location service for all entities
בלי הבדל דת גזע ומין
host: ipgallery.com
basePath: /location/v1
schemes:
- http
- https
consumes:
- application/json
produces:
- application/json
paths:
'/{tenant}/entity/{id}/{type}':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: id
in: path
type: string
format: byte
description: entity id in base64 encoding
required: true
- name: type
in: path
type: string
format: byte
description: entity type in base64 encoding
required: true
get:
description: Getting the entity location
parameters:
- name: format
in: query
type: string
required: false
description: 'the location format - [latlon,geojson], default is latlon'
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntityLocationRestResponse'
post:
description: 'creating/updating a entity location, body can be in Latlon or GeoJSON ([lat,lon])'
parameters:
- name: body
in: body
description: the location data.
required: true
schema:
$ref: '#/definitions/Latlon'
- name: format
in: query
type: string
required: false
description: 'the location format - [latlon,geojson], default is latlon'
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/RestResponse'
put:
description: updating a entity location
parameters:
- name: body
in: body
description: the location data.
required: true
schema:
$ref: '#/definitions/Latlon'
- name: format
in: query
type: string
required: false
description: 'the location format - [latlon,geojson], default is latlon'
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/RestResponse'
delete:
description: deleting an entity location
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/RestResponse'
'/{tenant}/entities':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: ids
in: query
type: array
items:
type: string
format: byte
collectionFormat: csv
get:
description: getting a list of locations of the given entities
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntitiesLocationRestResponse'
'/{tenant}/entitiesNearLocation':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: lat
type: number
format: double
in: query
required: true
description: latitude in double
- name: lon
type: number
format: double
in: query
required: true
description: longtitude in double
- name: since
in: query
type: number
format: integer
description: unix datetime in long
- name: distance
in: query
type: number
format: integer
required: true
description: distance from given location
- name: units
in: query
type: string
required: false
description: 'units of distance, mile/km default is mile'
default: mile
enum:
- mile
- km
get:
description: getting the list of entity-ids near this location
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntityIdsRestResponse'
'/{tenant}/entitiesWithinBox':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: box
in: query
type: array
required: true
description: '2 geo points [[x1,y1],[x2,y2]] enclosing box'
items:
type: array
items:
type: number
format: double
collectionFormat: csv
collectionFormat: csv
- name: since
in: query
type: number
format: integer
description: unix datetime in long
get:
description: getting the list of entity-ids in the box
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntityIdsRestResponse'
'/{tenant}/subscription/entity/{id}/{type}':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: id
in: path
type: string
format: byte
description: entity id in base64 encoding
required: true
- name: type
in: path
type: string
format: byte
description: entity type in base64 encoding
required: true
get:
summary: subscription list
description: getting subscription list for the given entity
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntitySubscriptionsRestResponse'
post:
summary: new subscription
description: creating a new subscription
parameters:
- name: body
in: body
description: subscription data
required: true
schema:
$ref: '#/definitions/EntitySubscription'
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntitySubscriptionRestResponse'
'/{tenant}/subscription/entity/{id}/{type}/{subId}':
parameters:
- name: tenant
in: path
type: string
description: tenant id
required: true
- name: id
in: path
type: string
format: byte
description: entity id in base64 encoding
required: true
- name: type
in: path
type: string
format: byte
description: entity type in base64 encoding
required: true
- name: subId
in: path
type: string
required: true
description: the subscription id
get:
summary: get subscription
description: getting the subscription details for a specific subscription id
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/EntitySubscriptionRestResponse'
put:
summary: updates subscription
description: updating an existing subscription
parameters:
- name: body
in: body
description: subscription data
required: true
schema:
$ref: '#/definitions/EntitySubscription'
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/RestResponse'
delete:
description: delete a subscription
responses:
'200':
description: Rest Response
schema:
$ref: '#/definitions/RestResponse'
definitions:
RestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
type: string
description: object/s in json format
Latlon:
type: object
properties:
lat:
type: number
format: double
description: latitude in double
lon:
type: number
format: double
description: longtitude in double
EntityLocation:
type: object
properties:
entity:
type: string
location:
type: array
description: GeoJSON point format
items:
type: number
format: double
example:
- 54.55
- 55.66
EntityLocationRestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
$ref: '#/definitions/EntityLocation'
EntityIdsRestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
type: array
items:
type: string
description: "array of entity id's"
EntitiesLocationRestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
type: array
items:
$ref: '#/definitions/EntityLocation'
EntitySubscriptionRestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
type: array
items:
$ref: '#/definitions/EntitySubscriptionResponse'
description: "array of entity id's"
EntitySubscriptionsRestResponse:
type: object
properties:
success:
type: boolean
error:
type: string
objectNode:
type: array
items:
$ref: '#/definitions/EntitySubscription'
description: "array of entity id's"
EntitySubscription:
description: "either 'near' object valid or 'box' , not both"
type: object
properties:
callback_url:
type: string
description: the url to post the notification
near:
type: object
description: 'near location subscription, radius from point'
properties:
location:
type: array
description: GeoJSON point format
items:
type: number
format: double
example:
- 54.55
- 55.66
distance:
type: number
format: integer
description: distance from given location
units:
type: string
description: units of distance
default: mile
enum:
- mile
- km
box:
description: '2 geo points [[x1,y1],[x2,y2]] enclosing box'
type: array
items:
type: array
description: GeoJSON point format
items:
type: number
format: double
expires:
type: number
format: integer
description: expiration time in seconds
direction:
description: in/out entering or existing
type: string
enum:
- in
- out
EntitySubscriptionResponse:
allOf:
- $ref: '#/definitions/EntitySubscription'
- type: object
properties:
subId:
description: 'the subscription-id, generated by the service'
type: string
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'LocationService'
package domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitiesLocationRestResponse {
private Boolean success = null;
private String error = null;
private List<EntityLocation> objectNode = new ArrayList<EntityLocation>();
/**
**/
public EntitiesLocationRestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public EntitiesLocationRestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
**/
public EntitiesLocationRestResponse objectNode(List<EntityLocation> objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("objectNode")
public List<EntityLocation> getObjectNode() {
return objectNode;
}
public void setObjectNode(List<EntityLocation> objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitiesLocationRestResponse entitiesLocationRestResponse = (EntitiesLocationRestResponse) o;
return Objects.equals(success, entitiesLocationRestResponse.success) &&
Objects.equals(error, entitiesLocationRestResponse.error) &&
Objects.equals(objectNode, entitiesLocationRestResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitiesLocationRestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.ArrayList;
import java.util.List;
/**
* Created by gil on 4/6/16.
*/
public class EntityGeoLocation extends EntityLocation {
private List<Double> location = new ArrayList<Double>();
/**
* GeoJSON point format
**/
public EntityLocation location(List<Double> location) {
this.location = location;
return this;
}
public List<Double> getLocation() {
return location;
}
public void setLocation(List<Double> location) {
this.location = location;
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntityIdsRestResponse {
private Boolean success = null;
private String error = null;
private List<String> objectNode = new ArrayList<String>();
/**
**/
public EntityIdsRestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public EntityIdsRestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
* array of entity id's
**/
public EntityIdsRestResponse objectNode(List<String> objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "array of entity id's")
@JsonProperty("objectNode")
public List<String> getObjectNode() {
return objectNode;
}
public void setObjectNode(List<String> objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntityIdsRestResponse entityIdsRestResponse = (EntityIdsRestResponse) o;
return Objects.equals(success, entityIdsRestResponse.success) &&
Objects.equals(error, entityIdsRestResponse.error) &&
Objects.equals(objectNode, entityIdsRestResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntityIdsRestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
/**
* Created by gil on 4/6/16.
*/
public class EntityLatLonLocation extends EntityLocation {
public String getLatLon() {
return latLon;
}
public void setLatLon(String latLon) {
this.latLon = latLon;
}
private String latLon;
}
package domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntityLocation {
private String entity = null;
public EntityLocation entity(String entity) {
this.entity = entity;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("entity")
public String getEntity() {
return entity;
}
public void setEntity(String entity) {
this.entity = entity;
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntityLocationRestResponse {
private Boolean success = null;
private String error = null;
private EntityLocation objectNode = null;
/**
**/
public EntityLocationRestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public EntityLocationRestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
**/
public EntityLocationRestResponse objectNode(EntityLocation objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("objectNode")
public EntityLocation getObjectNode() {
return objectNode;
}
public void setObjectNode(EntityLocation objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntityLocationRestResponse entityLocationRestResponse = (EntityLocationRestResponse) o;
return Objects.equals(success, entityLocationRestResponse.success) &&
Objects.equals(error, entityLocationRestResponse.error) &&
Objects.equals(objectNode, entityLocationRestResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntityLocationRestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* either &#39;near&#39; object valid or &#39;box&#39; , not both
**/
@ApiModel(description = "either 'near' object valid or 'box' , not both")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitySubscription {
private String callbackUrl = null;
private EntitySubscriptionNear near = null;
private List<List<Double>> box = new ArrayList<List<Double>>();
private BigDecimal expires = null;
public enum DirectionEnum {
IN("in"),
OUT("out");
private String value;
DirectionEnum(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return value;
}
}
private DirectionEnum direction = null;
/**
* the url to post the notification
**/
public EntitySubscription callbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
return this;
}
@ApiModelProperty(value = "the url to post the notification")
@JsonProperty("callback_url")
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
/**
**/
public EntitySubscription near(EntitySubscriptionNear near) {
this.near = near;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("near")
public EntitySubscriptionNear getNear() {
return near;
}
public void setNear(EntitySubscriptionNear near) {
this.near = near;
}
/**
* 2 geo points [[x1,y1],[x2,y2]] enclosing box
**/
public EntitySubscription box(List<List<Double>> box) {
this.box = box;
return this;
}
@ApiModelProperty(value = "2 geo points [[x1,y1],[x2,y2]] enclosing box")
@JsonProperty("box")
public List<List<Double>> getBox() {
return box;
}
public void setBox(List<List<Double>> box) {
this.box = box;
}
/**
* expiration time in seconds
**/
public EntitySubscription expires(BigDecimal expires) {
this.expires = expires;
return this;
}
@ApiModelProperty(value = "expiration time in seconds")
@JsonProperty("expires")
public BigDecimal getExpires() {
return expires;
}
public void setExpires(BigDecimal expires) {
this.expires = expires;
}
/**
* in/out entering or existing
**/
public EntitySubscription direction(DirectionEnum direction) {
this.direction = direction;
return this;
}
@ApiModelProperty(value = "in/out entering or existing")
@JsonProperty("direction")
public DirectionEnum getDirection() {
return direction;
}
public void setDirection(DirectionEnum direction) {
this.direction = direction;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitySubscription entitySubscription = (EntitySubscription) o;
return Objects.equals(callbackUrl, entitySubscription.callbackUrl) &&
Objects.equals(near, entitySubscription.near) &&
Objects.equals(box, entitySubscription.box) &&
Objects.equals(expires, entitySubscription.expires) &&
Objects.equals(direction, entitySubscription.direction);
}
@Override
public int hashCode() {
return Objects.hash(callbackUrl, near, box, expires, direction);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitySubscription {\n");
sb.append(" callbackUrl: ").append(toIndentedString(callbackUrl)).append("\n");
sb.append(" near: ").append(toIndentedString(near)).append("\n");
sb.append(" box: ").append(toIndentedString(box)).append("\n");
sb.append(" expires: ").append(toIndentedString(expires)).append("\n");
sb.append(" direction: ").append(toIndentedString(direction)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* near location subscription, radius from point
**/
@ApiModel(description = "near location subscription, radius from point")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitySubscriptionNear {
private BigDecimal distance = null;
private List<Double> location = new ArrayList<Double>();
public enum UnitsEnum {
MILE("mile"),
KM("km");
private String value;
UnitsEnum(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return value;
}
}
private UnitsEnum units = UnitsEnum.MILE;
/**
* distance from given location
**/
public EntitySubscriptionNear distance(BigDecimal distance) {
this.distance = distance;
return this;
}
@ApiModelProperty(value = "distance from given location")
@JsonProperty("distance")
public BigDecimal getDistance() {
return distance;
}
public void setDistance(BigDecimal distance) {
this.distance = distance;
}
/**
* GeoJSON point format
**/
public EntitySubscriptionNear location(List<Double> location) {
this.location = location;
return this;
}
@ApiModelProperty(value = "GeoJSON point format")
@JsonProperty("location")
public List<Double> getLocation() {
return location;
}
public void setLocation(List<Double> location) {
this.location = location;
}
/**
* units of distance
**/
public EntitySubscriptionNear units(UnitsEnum units) {
this.units = units;
return this;
}
@ApiModelProperty(value = "units of distance")
@JsonProperty("units")
public UnitsEnum getUnits() {
return units;
}
public void setUnits(UnitsEnum units) {
this.units = units;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitySubscriptionNear entitySubscriptionNear = (EntitySubscriptionNear) o;
return Objects.equals(distance, entitySubscriptionNear.distance) &&
Objects.equals(location, entitySubscriptionNear.location) &&
Objects.equals(units, entitySubscriptionNear.units);
}
@Override
public int hashCode() {
return Objects.hash(distance, location, units);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitySubscriptionNear {\n");
sb.append(" distance: ").append(toIndentedString(distance)).append("\n");
sb.append(" location: ").append(toIndentedString(location)).append("\n");
sb.append(" units: ").append(toIndentedString(units)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitySubscriptionResponse extends EntitySubscription {
private String callbackUrl = null;
private EntitySubscriptionNear near = null;
private List<List<Double>> box = new ArrayList<List<Double>>();
private BigDecimal expires = null;
private String subId = null;
/**
* the url to post the notification
**/
public EntitySubscriptionResponse callbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
return this;
}
@ApiModelProperty(value = "the url to post the notification")
@JsonProperty("callback_url")
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
/**
**/
public EntitySubscriptionResponse near(EntitySubscriptionNear near) {
this.near = near;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("near")
public EntitySubscriptionNear getNear() {
return near;
}
public void setNear(EntitySubscriptionNear near) {
this.near = near;
}
/**
* 2 geo points [[x1,y1],[x2,y2]] enclosing box
**/
public EntitySubscriptionResponse box(List<List<Double>> box) {
this.box = box;
return this;
}
@ApiModelProperty(value = "2 geo points [[x1,y1],[x2,y2]] enclosing box")
@JsonProperty("box")
public List<List<Double>> getBox() {
return box;
}
public void setBox(List<List<Double>> box) {
this.box = box;
}
/**
* expiration time in seconds
**/
public EntitySubscriptionResponse expires(BigDecimal expires) {
this.expires = expires;
return this;
}
@ApiModelProperty(value = "expiration time in seconds")
@JsonProperty("expires")
public BigDecimal getExpires() {
return expires;
}
public void setExpires(BigDecimal expires) {
this.expires = expires;
}
/**
* the subscription-id, generated by the service
**/
public EntitySubscriptionResponse subId(String subId) {
this.subId = subId;
return this;
}
@ApiModelProperty(value = "the subscription-id, generated by the service")
@JsonProperty("subId")
public String getSubId() {
return subId;
}
public void setSubId(String subId) {
this.subId = subId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitySubscriptionResponse entitySubscriptionResponse = (EntitySubscriptionResponse) o;
return Objects.equals(callbackUrl, entitySubscriptionResponse.callbackUrl) &&
Objects.equals(near, entitySubscriptionResponse.near) &&
Objects.equals(box, entitySubscriptionResponse.box) &&
Objects.equals(expires, entitySubscriptionResponse.expires) &&
Objects.equals(subId, entitySubscriptionResponse.subId);
}
@Override
public int hashCode() {
return Objects.hash(callbackUrl, near, box, expires, subId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitySubscriptionResponse {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" callbackUrl: ").append(toIndentedString(callbackUrl)).append("\n");
sb.append(" near: ").append(toIndentedString(near)).append("\n");
sb.append(" box: ").append(toIndentedString(box)).append("\n");
sb.append(" expires: ").append(toIndentedString(expires)).append("\n");
sb.append(" subId: ").append(toIndentedString(subId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitySubscriptionRestResponse {
private Boolean success = null;
private String error = null;
private List<EntitySubscriptionResponse> objectNode = new ArrayList<EntitySubscriptionResponse>();
/**
**/
public EntitySubscriptionRestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public EntitySubscriptionRestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
* array of entity id's
**/
public EntitySubscriptionRestResponse objectNode(List<EntitySubscriptionResponse> objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "array of entity id's")
@JsonProperty("objectNode")
public List<EntitySubscriptionResponse> getObjectNode() {
return objectNode;
}
public void setObjectNode(List<EntitySubscriptionResponse> objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitySubscriptionRestResponse entitySubscriptionRestResponse = (EntitySubscriptionRestResponse) o;
return Objects.equals(success, entitySubscriptionRestResponse.success) &&
Objects.equals(error, entitySubscriptionRestResponse.error) &&
Objects.equals(objectNode, entitySubscriptionRestResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitySubscriptionRestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class EntitySubscriptionsRestResponse {
private Boolean success = null;
private String error = null;
private List<EntitySubscription> objectNode = new ArrayList<EntitySubscription>();
/**
**/
public EntitySubscriptionsRestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public EntitySubscriptionsRestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
* array of entity id's
**/
public EntitySubscriptionsRestResponse objectNode(List<EntitySubscription> objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "array of entity id's")
@JsonProperty("objectNode")
public List<EntitySubscription> getObjectNode() {
return objectNode;
}
public void setObjectNode(List<EntitySubscription> objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntitySubscriptionsRestResponse entitySubscriptionsRestResponse = (EntitySubscriptionsRestResponse) o;
return Objects.equals(success, entitySubscriptionsRestResponse.success) &&
Objects.equals(error, entitySubscriptionsRestResponse.error) &&
Objects.equals(objectNode, entitySubscriptionsRestResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntitySubscriptionsRestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class Latlon {
private Double lat = null;
private Double lon = null;
/**
* latitude in double
**/
public Latlon lat(Double lat) {
this.lat = lat;
return this;
}
@ApiModelProperty(value = "latitude in double")
@JsonProperty("lat")
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
/**
* longtitude in double
**/
public Latlon lon(Double lon) {
this.lon = lon;
return this;
}
@ApiModelProperty(value = "longtitude in double")
@JsonProperty("lon")
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Latlon latlon = (Latlon) o;
return Objects.equals(lat, latlon.lat) &&
Objects.equals(lon, latlon.lon);
}
@Override
public int hashCode() {
return Objects.hash(lat, lon);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Latlon {\n");
sb.append(" lat: ").append(toIndentedString(lat)).append("\n");
sb.append(" lon: ").append(toIndentedString(lon)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package domain;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-03-31T07:24:28.094Z")
public class RestResponse {
private Boolean success = null;
private String error = null;
private String objectNode = null;
/**
**/
public RestResponse success(Boolean success) {
this.success = success;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("success")
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
/**
**/
public RestResponse error(String error) {
this.error = error;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
* object/s in json format
**/
public RestResponse objectNode(String objectNode) {
this.objectNode = objectNode;
return this;
}
@ApiModelProperty(value = "object/s in json format")
@JsonProperty("objectNode")
public String getObjectNode() {
return objectNode;
}
public void setObjectNode(String objectNode) {
this.objectNode = objectNode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RestResponse restResponse = (RestResponse) o;
return Objects.equals(success, restResponse.success) &&
Objects.equals(error, restResponse.error) &&
Objects.equals(objectNode, restResponse.objectNode);
}
@Override
public int hashCode() {
return Objects.hash(success, error, objectNode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class RestResponse {\n");
sb.append(" success: ").append(toIndentedString(success)).append("\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append(" objectNode: ").append(toIndentedString(objectNode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
package handlers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import domain.*;
import grs.BaseRestResponse;
import logic.LocationServiceManager;
import microservice.RequestContext;
import microservice.handlers.BaseHandler;
import microservice.io.iface.ILogger;
import util.Enums;
import utils.common.CacheClient;
import utils.common.RedisCacheClient;
import java.util.*;
//import java.util.regex.Pattern;
/**
* Created by gil on 3/31/16.
*/
public class LocationServiceHandler extends BaseHandler {
private LocationServiceManager locationServiceManager = null;
private Double CONST_MILE = 1.60934;
private CacheClient rcc = null;
// public static final Pattern regExCsvParamSeperatorPattern = Pattern.compile(",");
public LocationServiceHandler(ILogger logger) {
this.locationServiceManager = new LocationServiceManager(logger);
this.rcc = new RedisCacheClient();
}
public ILogger getLogger() {
return this.logger;
}
@Override
public void doCreate(RequestContext requestContext) {
Enums.EnumRestCommands operation = null;
operation = Enums.EnumRestCommands.resolveCommand(requestContext.params[1]);
if (operation != null) {
switch (operation) {
case E_LOCATION_ENTITY_API:
entityIdPost(requestContext);
break;
case E_LOCATION_SUBSCRIPTION_API:
subscriptionEntityIdPost(requestContext);
break;
default:
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
break;
}
}
else
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
}
@Override
public void doRead(RequestContext requestContext) {
Enums.EnumRestCommands operation = null;
operation = Enums.EnumRestCommands.resolveCommand(requestContext.params[1]);
if (operation != null) {
switch (operation) {
case E_LOCATION_ENTITY_API:
entityIdGet(requestContext);
break;
case E_LOCATION_ENTITIES_API:
entitiesGet(requestContext);
break;
case E_LOCATION_ENTITIES_NEAR_LOCATION_API:
entitiesNearLocationGet(requestContext);
break;
case E_LOCATION_ENTITIES_WITHIN_BOX_API:
entitiesWithinBoxGet(requestContext);
break;
case E_LOCATION_SUBSCRIPTION_API:
if (requestContext.params.length >= 6)
subscriptionEntityIdSubIdGet(requestContext);
else {
operation = Enums.EnumRestCommands.resolveCommand(requestContext.params[1]);
if (operation != null) {
switch (operation) {
case E_LOCATION_SUBSCRIPTION_API:
subscriptionEntityIdGet(requestContext);
break;
default:
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
break;
}
}
}
break;
default:
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
break;
}
}
}
@Override
public void doUpdate(RequestContext requestContext) {
Enums.EnumRestCommands operation = null;
operation = Enums.EnumRestCommands.resolveCommand(requestContext.params[1]);
if (operation != null) {
switch (operation) {
case E_LOCATION_ENTITY_API:
entityIdPut(requestContext);
break;
case E_LOCATION_SUBSCRIPTION_API:
subscriptionEntityIdSubIdPut(requestContext);
break;
default:
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
break;
}
}
}
@Override
public void doDelete(RequestContext requestContext) {
Enums.EnumRestCommands operation = null;
operation = Enums.EnumRestCommands.resolveCommand(requestContext.params[1]);
if (operation != null) {
switch (operation) {
case E_LOCATION_ENTITY_API:
entityIdDelete(requestContext);
break;
case E_LOCATION_SUBSCRIPTION_API:
subscriptionEntityIdSubIdDelete(requestContext);
break;
default:
writeObjectToResponse(requestContext, errorResponse("Unknown action"));
break;
}
}
}
/**
*
* getting a list of locations of the given entities
* @param tenant tenant id
* @param ids
* @return EntitiesLocationRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/entities")
public void entitiesGet(RequestContext reqCtx) {
logger.debug("recieved REST request: entitiesGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
EntitiesLocationRestResponse elrr = new EntitiesLocationRestResponse();
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if(queryParams != null && !queryParams.isEmpty()) {
String ids = "ids=" + queryParams.get("ids").pop();
brr = this.locationServiceManager.getEntitiesLocation(ids);
if (brr.success) {
elrr = buildEntitiesLocationRestResponse(brr);
}
}
writeObjectToResponse(reqCtx,elrr);
}
private EntitiesLocationRestResponse buildEntitiesLocationRestResponse(BaseRestResponse brr) {
EntitiesLocationRestResponse elrr = new EntitiesLocationRestResponse();
List<EntityLocation> listEL = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
JsonNode content = (JsonNode) mapper.convertValue(brr.objectNode, JsonNode.class);
if(content != null && content.isArray()) {
for(JsonNode entry : content) {
EntityLocation el = buildEntityLocation(false,entry);
listEL.add(el);
}
elrr.setSuccess(true);
elrr.setObjectNode(listEL);
}
else {
elrr.setSuccess(false);
elrr.setError("failed to getEntities locations");
}
return elrr;
}
/**
*
* getting the list of entity-ids near this location
* @param tenant tenant id
* @param lat latitude in double
* @param lon longtitude in double
* @param distance distance from given location
* @param since unix datetime in long
* @param units units of distance, mile/km default is mile
* @return EntityIdsRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/entitiesNearLocation")
public void entitiesNearLocationGet(RequestContext reqCtx) {
logger.debug("recieved REST request: entitiesNearLocationGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
EntityIdsRestResponse eirr = new EntityIdsRestResponse();
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if(queryParams != null && !queryParams.isEmpty()) {
String enl = buildEntitiesNearLocation(queryParams);
if(enl != null) {
brr = this.locationServiceManager.getEntitiesLocation(enl);
if (brr.success) {
eirr = buildEntityIdsRestResponse(brr.objectNode);
}
}
else {
eirr.success(false);
eirr.error("not all mandatory params present.");
}
}
writeObjectToResponse(reqCtx,eirr);
}
private EntityIdsRestResponse buildEntityIdsRestResponse(JsonNode objectNode) {
EntityIdsRestResponse eirr = new EntityIdsRestResponse();
ObjectMapper mapper = new ObjectMapper();
List<String> node = new ArrayList<String>();
JsonNode content = (JsonNode) mapper.convertValue(objectNode, JsonNode.class);
if(content != null && content.isArray()) {
for(JsonNode nodeObject : content ) {
node.add(nodeObject.get("id").asText());
}
eirr.success(true);
eirr.setObjectNode(node);
}
return eirr;
}
private String buildEntitiesNearLocation(Map<String, Deque<String>> queryParams) {
StringBuilder strBuilder = new StringBuilder();
int counter = 0;
Double mile = 0.0;
boolean isMile = true;
Deque<String> lat = queryParams.get("lat");
if (lat != null && !lat.isEmpty()) {
if(counter > 0)
strBuilder.append("&");
counter++;
strBuilder.append("geoLat=").append(lat.pop());
}
else
return null;
Deque<String> lon = queryParams.get("lon");
if (lon != null && !lon.isEmpty()) {
if(counter > 0)
strBuilder.append("&");
counter++;
strBuilder.append("geoLng=").append(lon.pop());
}
else
return null;
Deque<String> since = queryParams.get("since");
if (since != null && !since.isEmpty()) {
if(counter > 0)
strBuilder.append("&");
counter++;
strBuilder.append("ts=").append(since.pop());
}
Deque<String> units = queryParams.get("units");
if (units != null && !units.isEmpty()) {
if(units.pop().equals("km"))
isMile= false;
}
Deque<String> distance = queryParams.get("distance");
if (distance != null && !distance.isEmpty()) {
if(counter > 0)
strBuilder.append("&");
counter++;
if(!isMile)
mile = Double.parseDouble(distance.pop()) / CONST_MILE;
else
mile = Double.parseDouble(distance.pop());
strBuilder.append("maxDist=").append(mile);
}
else
return null;
return strBuilder.toString();
}
/**
*
* getting the list of entity-ids in the box
* @param tenant tenant id
* @param box 2 geo points [[x1,y1],[x2,y2]] enclosing box
* @param since unix datetime in long
* @return EntityIdsRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/entitiesWithinBox")
public void entitiesWithinBoxGet(RequestContext reqCtx) {
logger.debug("recieved REST request: entitiesWithinBoxGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
EntityIdsRestResponse eirr = new EntityIdsRestResponse();
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if(queryParams != null && !queryParams.isEmpty()) {
String enl = buildEntitiesWithinBox(queryParams);
if(enl != null) {
brr = this.locationServiceManager.getEntitiesLocation(enl);
if (brr.success) {
eirr = buildEntityIdsRestResponse(brr.objectNode);
}
}
else {
eirr.success(false);
eirr.error("not all mandatory params present.");
}
}
writeObjectToResponse(reqCtx,eirr);
}
private String buildEntitiesWithinBox(Map<String, Deque<String>> queryParams) {
StringBuilder strBuilder = new StringBuilder();
Deque<String> box = queryParams.get("box");
if (box != null && !box.isEmpty()) {
strBuilder.append("polygon=").append(box.pop());
}
else
return null;
return strBuilder.toString();
}
/**
*
* Getting the entity location
* @param tenant tenant id
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param format the location format - [latlon,geojson], default is latlon
* @return EntityLocationRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/entity/{id}/{type}")
public void entityIdGet(RequestContext reqCtx) {
logger.debug("recieved REST request: entityIdGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
EntityLocationRestResponse elrr = new EntityLocationRestResponse();
String entityId = reqCtx.params[2];
String entityType = reqCtx.params[3];
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if(queryParams != null && !queryParams.isEmpty()) {
Deque<String> format = queryParams.get("format");
brr = this.locationServiceManager.getEntityLocation(entityId,entityType);
if (brr.success) {
elrr = buildEntityLocationRestResponse(brr,format.pop());
}
}
else {
brr = this.locationServiceManager.getEntityLocation(entityId, entityType);
if (brr.success) {
elrr = buildEntityLocationRestResponse(brr, "latlon");
}
}
writeObjectToResponse(reqCtx,elrr);
}
private EntityLocationRestResponse buildEntityLocationRestResponse(BaseRestResponse brr, String format) {
EntityLocationRestResponse elrr = new EntityLocationRestResponse();
EntityLocation el = new EntityLocation();
if(format.equals("geojson")) {
el = buildEntityLocation(true,brr.objectNode);
elrr.setSuccess(true);
elrr.setObjectNode(el);
}
else { //default lat/lon
el = buildEntityLocation(false,brr.objectNode);
elrr.setSuccess(true);
elrr.setObjectNode(el);
}
return elrr;
}
private EntityLocation buildEntityLocation(boolean isGeoJson, JsonNode jsonNode) {
EntityLocation el = new EntityLocation();
EntityGeoLocation egl = new EntityGeoLocation();
EntityLatLonLocation elll = new EntityLatLonLocation();
ObjectMapper mapper = new ObjectMapper();
JsonNode content = (JsonNode) mapper.convertValue(jsonNode, JsonNode.class);
List<Double> list = new ArrayList<Double>();
JsonNode lat,lon;
lat = content.get("lat");
lon = content.get("lon");
if(isGeoJson) {
list.add(lat.asDouble());
list.add(lon.asDouble());
egl.setEntity(content.get("id").asText());
egl.setLocation(list);
el = egl;
}
else {
elll.setEntity(content.get("id").asText());
elll.setLatLon(coordinatesToJson(lat.asText(),lon.asText()));
el = elll;
}
return el;
}
/**
*
* updating a entity location
* @param tenant tenant id
* @param body the location data.
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param format the location format - [latlon,geojson], default is latlon
* @return RestResponse
*/
// @MSPath(method = "PUT", path = "/{tenant}/entity/{id}/{type}")
public void entityIdPut(RequestContext reqCtx) {
logger.debug("recieved REST request: entityIdPut");
BaseRestResponse brr = new BaseRestResponse(true,null);
String geoLocation = null;
String entityId = reqCtx.params[2];
String entityType = reqCtx.params[3];
JsonNode content = (JsonNode) readObjectFromRequest(reqCtx, JsonNode.class);
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if (content != null) {
geoLocation = convertGeoJson(content,queryParams);
brr = this.locationServiceManager.updateEntityLocation(entityId,entityType,geoLocation);
}
writeObjectToResponse(reqCtx,brr);
}
/**
*
* creating/updating a entity location, body can be in Latlon or GeoJSON ([lat,lon])
* @param tenant tenant id
* @param body the location data.
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param format the location format - [latlon,geojson], default is latlon
* @return RestResponse
*/
// @MSPath(method = "POST", path = "/{tenant}/entity/{id}/{type}")
public void entityIdPost(RequestContext reqCtx) {
logger.debug("recieved REST request: entityIdPost");
BaseRestResponse brr = new BaseRestResponse(true,null);
String geoLocation = null;
String entityId = reqCtx.params[2];
String entityType = reqCtx.params[3];
JsonNode content = (JsonNode) readObjectFromRequest(reqCtx, JsonNode.class);
Map<String, Deque<String>> queryParams = reqCtx.queryParameters;
if (content != null) {
geoLocation = convertGeoJson(content,queryParams);
brr = this.locationServiceManager.updateEntityLocation(entityId,entityType,geoLocation);
}
writeObjectToResponse(reqCtx,brr);
}
public String convertGeoJson(JsonNode content,Map<String, Deque<String>> queryParams) {
String geoLocation = null;
String locationFormat = null;
JsonNode lat = content.get("lat");
JsonNode lon = content.get("lon");
if(queryParams != null && !queryParams.isEmpty()) {
Deque<String> format = queryParams.get("format");
if (format != null && !format.isEmpty())
locationFormat = format.pop();
if(locationFormat != null) {
if(locationFormat.equals("geojson")) {
//{ "coordinates": [100.0, 0.0] }
JsonNode arrNode = content.get("coordinates");
if (arrNode.isArray()) {
lat = arrNode.get(0);
lon = arrNode.get(1);
}
geoLocation = coordinatesToJson(lat.asText(),lon.asText());
}
else if(locationFormat.equals("latlon"))
geoLocation = coordinatesToJson(lat.asText(),lon.asText());
}
}
else {
if(lat != null && !lat.isNull() &&
lon != null && !lon.isNull() )
geoLocation = coordinatesToJson(lat.asText(),lon.asText());
}
return geoLocation;
}
public String coordinatesToJson(String lat, String lon) {
Double doubleLat = null;
Double doubleLon = null;
if(lat != null && !lat.equals("null"))
doubleLat = Double.parseDouble(lat);
if(lon != null && !lon.equals("null"))
doubleLon = Double.parseDouble(lon);
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("lat",doubleLat);
objectNode.put("lon",doubleLon);
return objectNode.toString();
}
/**
*
* deleting an entity location
* @param tenant tenant id
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param format the location format - [latlon,geojson], default is latlon
* @return RestResponse
*/
// @MSPath(method = "DELETE", path = "/{tenant}/entity/{id}/{type}")
public void entityIdDelete(RequestContext reqCtx) {
logger.debug("recieved REST request: entityIdDelete");
BaseRestResponse brr = new BaseRestResponse(true,null);
String entityId = reqCtx.params[2];
String entityType = reqCtx.params[3];
String geoLocation = coordinatesToJson(null,null);
brr = this.locationServiceManager.updateEntityLocation(entityId,entityType,geoLocation);
writeObjectToResponse(reqCtx,brr);
}
/**
* subscription list
* getting subscription list for the given entity
* @param tenant tenant id
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @return EntitySubscriptionsRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/subscription/entity/{id}/{type}")
public void subscriptionEntityIdGet(RequestContext reqCtx) {
logger.debug("recieved REST request: subscriptionEntityIdGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
String entityId = new String(Base64.getDecoder().decode(reqCtx.params[3]));
String entityType = new String(Base64.getDecoder().decode(reqCtx.params[4]));
String patternKey = entityId + ":" + entityType + "*";
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
String[] result = rcc.getByPattern(patternKey);
for(String key : result) {
String record = rcc.get(key);
String[] parts = key.split(":");
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("EntitySubscription",record);
objectNode.put("subId",parts[2]);
arrayNode.add(objectNode);
}
brr.objectNode = arrayNode;
writeObjectToResponse(reqCtx,brr);
}
/**
* new subscription
* creating a new subscription
* @param tenant tenant id
* @param body subscription data
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @return EntitySubscriptionRestResponse
*/
// @MSPath(method = "POST", path = "/{tenant}/subscription/entity/{id}/{type}")
public void subscriptionEntityIdPost(RequestContext reqCtx) {
logger.debug("recieved REST request: subscriptionEntityIdPost");
BaseRestResponse brr = new BaseRestResponse(true,null);
String entityId = new String(Base64.getDecoder().decode(reqCtx.params[3]));
String entityType = new String(Base64.getDecoder().decode(reqCtx.params[4]));
String subId = UUID.randomUUID().toString();
String key = entityId + ":" + entityType + ":" + subId;
JsonNode content = (JsonNode) readObjectFromRequest(reqCtx, JsonNode.class);
if (content != null) {
Integer expires = Integer.parseInt(content.get("expires").asText());
rcc.set(key,content.toString(),expires);
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("EntitySubscription",content);
objectNode.put("subId",subId);
brr.objectNode = objectNode;
}
else {
brr.success = false;
brr.setError("no record provided");
}
writeObjectToResponse(reqCtx,brr);
}
/**
* get subscription
* @param tenant tenant id
* getting the subscription details for a specific subscription id
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param subId the subscription id
* @return EntitySubscriptionRestResponse
*/
// @MSPath(method = "GET", path = "/{tenant}/subscription/entity/{id}/{type}/{subId}")
public void subscriptionEntityIdSubIdGet(RequestContext reqCtx) {
logger.debug("recieved REST request: subscriptionEntityIdSubIdGet");
BaseRestResponse brr = new BaseRestResponse(true,null);
ObjectMapper mapper = new ObjectMapper();
String entityId = new String(Base64.getDecoder().decode(reqCtx.params[3]));
String entityType = new String(Base64.getDecoder().decode(reqCtx.params[4]));
String subId = reqCtx.params[5];
String key = entityId + ":" + entityType + ":" + subId;
String record = rcc.get(key);
if(record != null) {
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("EntitySubscription",record);
objectNode.put("subId",subId);
brr.objectNode = objectNode;
}
else {
brr.success = false;
brr.setError("no such record");
}
writeObjectToResponse(reqCtx,brr);
}
/**
* updates subscription
* updating an existing subscription
* @param tenant tenant id
* @param body subscription data
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param subId the subscription id
* @return RestResponse
*/
// @MSPath(method = "PUT", path = "/{tenant}/subscription/entity/{id}/{type}/{subId}")
public void subscriptionEntityIdSubIdPut(RequestContext reqCtx) {
logger.debug("recieved REST request: subscriptionEntityIdSubIdPut");
BaseRestResponse brr = new BaseRestResponse(true,null);
String entityId = new String(Base64.getDecoder().decode(reqCtx.params[3]));
String entityType = new String(Base64.getDecoder().decode(reqCtx.params[4]));
String subId = reqCtx.params[5];
String key = entityId + ":" + entityType + ":" + subId;
JsonNode content = (JsonNode) readObjectFromRequest(reqCtx, JsonNode.class);
if (content != null) {
Integer expires = Integer.parseInt(content.get("expires").asText());
rcc.set(key,content.toString(),expires);
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("EntitySubscription",content);
objectNode.put("subId",subId);
brr.objectNode = objectNode;
}
else {
brr.success = false;
brr.setError("no record provided");
}
writeObjectToResponse(reqCtx,brr);
}
/**
*
* delete a subscription
* @param tenant tenant id
* @param id entity id in base64 encoding
* @param type entity type in base64 encoding
* @param subId the subscription id
* @return RestResponse
*/
// @MSPath(method = "DELETE", path = "/{tenant}/subscription/entity/{id}/{type}/{subId}")
public void subscriptionEntityIdSubIdDelete(RequestContext reqCtx) {
logger.debug("recieved REST request: subscriptionEntityIdSubIdDelete");
BaseRestResponse brr = new BaseRestResponse(true,null);
String entityId = new String(Base64.getDecoder().decode(reqCtx.params[3]));
String entityType = new String(Base64.getDecoder().decode(reqCtx.params[4]));
String subId = reqCtx.params[5];
String key = entityId + ":" + entityType + ":" + subId;
rcc.delete(key);
writeObjectToResponse(reqCtx,brr);
}
public RestResponse errorResponse(String error) {
RestResponse resp = new RestResponse();
resp.setError(error);
return resp;
}
}
package logic;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javadocmd.simplelatlng.LatLng;
import com.javadocmd.simplelatlng.window.CircularWindow;
import com.javadocmd.simplelatlng.window.RectangularWindow;
import domain.EntitySubscription;
import domain.EntitySubscriptionNear;
import utils.common.CacheClient;
import utils.common.RedisCacheClient;
import java.io.IOException;
import java.util.List;
import static com.javadocmd.simplelatlng.util.LengthUnit.KILOMETER;
import static com.javadocmd.simplelatlng.util.LengthUnit.MILE;
/**
* Created by gil on 4/13/16.
*/
public class LatLonPubSub implements Runnable{
private String idType;
private String geoLocation;
private String oldGeoLocation;
private CacheClient rcc = null;
private LocationServiceManager locationServiceManager = null;
public LatLonPubSub(String idType, String geoLocation, String oldGeoLocation, LocationServiceManager locationServiceManager) {
this.idType = idType;
this.geoLocation = geoLocation;
this.oldGeoLocation = oldGeoLocation;
this.rcc = new RedisCacheClient();
this.locationServiceManager = locationServiceManager;
}
@Override
public void run()
{
readFromCacheClient();
}
private void readFromCacheClient() {
ObjectMapper mapper = new ObjectMapper();
String pattern = idType + "*";
String[] keys = rcc.getByPattern(pattern);
for(String key : keys) {
String value = rcc.get(key);
try {
EntitySubscription es = mapper.readValue(value, EntitySubscription.class);
String url = checkLatLonInRange(es);
if(url != null)
this.locationServiceManager.sendUrl(url,value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String checkLatLonInRange(EntitySubscription es) {
String url = null;
Double lat = null;
Double lng = null;
Double oldLat = null;
Double oldLng = null;
EntitySubscription.DirectionEnum direction;
ObjectMapper mapper = new ObjectMapper();
JsonNode content = null;
try {
content = mapper.readTree(geoLocation);
lat = content.get("lat").asDouble();
lng = content.get("lon").asDouble();
content = mapper.readTree(oldGeoLocation);
oldLat = content.get("lat").asDouble();
oldLng = content.get("lon").asDouble();
} catch (IOException e) {
e.printStackTrace();
}
direction = es.getDirection();
if(es.getBox() != null) {
List<List<Double>> coordinates = es.getBox();
List<Double> coordinate1 = coordinates.get(0);
Double x1 = coordinate1.get(0);
Double y1 = coordinate1.get(1);
List<Double> coordinate2 = coordinates.get(1);
Double x2 = coordinate2.get(0);
Double y2 = coordinate2.get(1);
RectangularWindow recWindow = new RectangularWindow(new LatLng(x1,y1),new LatLng(x2,y2));
if(direction != null && direction.equals(EntitySubscription.DirectionEnum.IN)) {
if (!recWindow.contains(new LatLng(oldLat, oldLng)) &&
recWindow.contains(new LatLng(lat, lng)))
url = es.getCallbackUrl();
}
if(direction != null && direction.equals(EntitySubscription.DirectionEnum.OUT)) {
if (recWindow.contains(new LatLng(oldLat, oldLng)) &&
!recWindow.contains(new LatLng(lat, lng)))
url = es.getCallbackUrl();
}
}
else if(es.getNear() != null) {
EntitySubscriptionNear esn = es.getNear();
List<Double> location = esn.getLocation();
Double x = location.get(0);
Double y = location.get(1);
Double distance = esn.getDistance().doubleValue();
EntitySubscriptionNear.UnitsEnum units = esn.getUnits();
CircularWindow circWindow;
if(units.equals(EntitySubscriptionNear.UnitsEnum.KM))
circWindow = new CircularWindow(new LatLng(x,y),distance,KILOMETER);
else
circWindow = new CircularWindow(new LatLng(x,y),distance,MILE);
if(direction != null && direction.equals(EntitySubscription.DirectionEnum.IN)) {
if( !circWindow.contains(new LatLng(oldLat,oldLng)) &&
circWindow.contains(new LatLng(lat,lng)))
url = es.getCallbackUrl();
}
if(direction != null && direction.equals(EntitySubscription.DirectionEnum.OUT)) {
if( circWindow.contains(new LatLng(oldLat,oldLng)) &&
!circWindow.contains(new LatLng(lat,lng)))
url = es.getCallbackUrl();
}
}
return url;
}
}
package logic;
import grs.BaseRestResponse;
import microservice.MicroserviceClient;
import microservice.io.iface.ILogger;
import microservice.params.CommandParams;
import microservice.params.RestClientParams;
import util.CallBackHttpRequest;
import utils.http.simpleHttpClient.SimpleHttpClient;
import utils.http.simpleHttpClient.SimpleHttpResponse;
import utils.mtqm.MultiThreadQueueManager;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
/**
* Created by gil on 3/31/16.
*/
public class LocationServiceManager {
private static final String DS_IP_ADDRESS = System.getProperty("ds.IpAddress", "localhost:8080");
private static final String CONST_TENANT = "MCX";
private static final String CONST_ENTITIES = "entities";
private static final String CONST_ENTITY = "entity";
private MicroserviceClient restClient = null;
private SimpleHttpClient httpClient = null;
private RestClientParams params = null;
private ILogger logger = null;
private int currentNumber = 0;
private final static String THREAD_MANAGER_THREADS;
private final static String THREAD_MANAGER_QUEUE_SIZE;
static
{
THREAD_MANAGER_THREADS = (System.getProperty("config.thread.manager.threads") != null)? System.getProperty("config.offline.task.threads") : "7";
THREAD_MANAGER_QUEUE_SIZE = (System.getProperty("config.thread.manager.queue.size") != null)? System.getProperty("config.offline.task.queue.size") : "100";
}
private static MultiThreadQueueManager threadManager = null;
public LocationServiceManager(ILogger logger) {
synchronized(this)
{
if (threadManager == null)
{
threadManager = new MultiThreadQueueManager();
threadManager.startManager(Integer.parseInt(THREAD_MANAGER_THREADS), Integer.parseInt(THREAD_MANAGER_QUEUE_SIZE));
}
}
try{
this.logger = logger;
params = new RestClientParams("ds",true,0, DS_IP_ADDRESS, 100);
restClient = new MicroserviceClient(MicroserviceClient.EnumRestClientType.E_HTTP, params);
httpClient = new SimpleHttpClient();
httpClient.Initialize(100);
}
catch(Exception e){
restClient= null;
}
}
public BaseRestResponse updateEntityLocation(String entityId, String entityType , String geoLocation) {
logger.debug("calling updateEntityLocation");
String oldGeoLocation = null;
String id = new String(Base64.getDecoder().decode(entityId));
String type = new String(Base64.getDecoder().decode(entityType));
String idType = id + ":" + type;
String[] params = new String[4];
params[0] = CONST_TENANT;
params[1] = CONST_ENTITY;
params[2] = entityId;
params[3] = entityType;
String requestParams = "returnType=before";
BaseRestResponse resp = null;
CommandParams cmdParams = new CommandParams("entities", params, requestParams,geoLocation, null);
resp = restClient.update(cmdParams);
oldGeoLocation = resp.objectNode.toString();
currentNumber = threadManager.getNextQueueNumber(currentNumber);
threadManager.sendJob(1,
new LatLonPubSub(idType,geoLocation,oldGeoLocation,this),
null,
currentNumber,
LocationServiceManager.class.getName());
return resp;
}
public BaseRestResponse getEntityLocation(String entityId, String entityType) {
logger.debug("calling getEntityLocation");
String[] params = new String[4];
params[0] = CONST_TENANT;
params[1] = CONST_ENTITY;
params[2] = entityId;
params[3] = entityType;
BaseRestResponse resp = null;
CommandParams cmdParams = new CommandParams("entities", params, null,null, null);
resp = restClient.read(cmdParams);
return resp;
}
public BaseRestResponse getEntitiesLocation(String str) {
logger.debug("calling getEntitiesLocation");
String[] params = new String[2];
params[0] = CONST_TENANT;
params[1] = CONST_ENTITIES;
BaseRestResponse resp = null;
CommandParams cmdParams = new CommandParams("entities", params, str,null, null);
resp = restClient.read(cmdParams);
return resp;
}
public BaseRestResponse sendUrl(String url,String content) {
BaseRestResponse brr = new BaseRestResponse(true,null);
CallBackHttpRequest request = new CallBackHttpRequest(url, content );
try {
SimpleHttpResponse resp = httpClient.processRequest(request);
if (resp.getStatusCode() != 200) {
brr.success = false;
brr.setError("failed to send callback");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return brr;
}
}
package util;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import utils.http.simpleHttpClient.SimpleHttpRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by gil on 4/17/16.
*/
public class CallBackHttpRequest extends SimpleHttpRequest {
String callbackUrl = null;
String content = null;
public CallBackHttpRequest(String callbackUrl, String content) {
this.callbackUrl = callbackUrl;
this.content = content;
setMethod(Method.POST);
addHeader("Content-Type", "application/json");
}
protected HttpUriRequest buildPostRequest() {
HttpPost postRequest = new HttpPost(callbackUrl);
// add headers
for(Map.Entry<String, String> hdr : headers.entrySet()) {
postRequest.addHeader(hdr.getKey(), hdr.getValue());
}
// add content
if (content != null) {
try {
StringEntity contentEntity = new StringEntity(content,"UTF-8");
contentEntity.setContentType(contentType);
postRequest.setEntity(contentEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return postRequest;
}
}
package util;
/**
* Created by gil on 3/31/16.
*/
public class Enums {
public enum EnumRestCommands {
E_LOCATION_ENTITY_API("entity"),
E_LOCATION_ENTITIES_API("entities"),
E_LOCATION_SUBSCRIPTION_API("subscription"),
E_LOCATION_ENTITIES_NEAR_LOCATION_API("entitiesNearLocation"),
E_LOCATION_ENTITIES_WITHIN_BOX_API("entitiesWithinBox");
private String str;
private EnumRestCommands(String strCommand) {
this.str = strCommand;
}
public String getStrCommand() {
return str;
}
public static EnumRestCommands resolveCommand(String strCommand) {
for (EnumRestCommands command : EnumRestCommands.values()) {
if ( command != null &&
command.getStrCommand() != null &&
command.getStrCommand().equals(strCommand) ) {
return command;
}
}
return null;
}
}
}
package web;
/**
* Created by gil on 3/31/16.
*/
import utils.common.ConfigProperties;
import handlers.LocationServiceHandler;
import microservice.MicroserviceApp;
import microservice.io.iface.ILogger;
import microservice.params.RestServerParams;
public class App {
public App() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
ConfigProperties.getInstance().loadProperties();
// load rest server parameters
Long port = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.port","9090", ConfigProperties.EnumPropertyType.E_LONG);
String host = (String) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.host","localhost", ConfigProperties.EnumPropertyType.E_STRING);
Long workerThreadsNum = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.worker.threads","8", ConfigProperties.EnumPropertyType.E_LONG);
RestServerParams rsParams = new RestServerParams(port.intValue(), host, workerThreadsNum.intValue());
rsParams.setPubSubServerPort(0);
MicroserviceApp msApp = new MicroserviceApp(rsParams, null, "LocationService");
ILogger logger = msApp.getLogger();
LocationServiceHandler locationServiceHandler = new LocationServiceHandler(logger);
msApp.addHandler("/LocationService/api/v1", locationServiceHandler);
if (!msApp.startApp())
System.out.println("failed starting... check logs");
}
}
import com.javadocmd.simplelatlng.LatLng;
import com.javadocmd.simplelatlng.window.CircularWindow;
import com.javadocmd.simplelatlng.window.RectangularWindow;
import org.junit.Test;
import static com.javadocmd.simplelatlng.util.LengthUnit.KILOMETER;
import static junit.framework.TestCase.assertEquals;
/**
* Created by gil on 4/13/16.
*/
public class TestLatLonPackge {
@Test
public void testBox(){
System.out.print("testBox\n");
RectangularWindow w = new RectangularWindow(new LatLng(45, -67.5),new LatLng(20,-80));
CircularWindow c = new CircularWindow(new LatLng(10, 0), 40,KILOMETER);
assertEquals(w.contains(new LatLng(40,-70)),true);
// assertEquals(w.contains(new LatLng(40,70)),true);
assertEquals(c.contains(new LatLng(10.1,0.1)),true);
System.out.print(w);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment