├── README.md ├── aws-api-gateway-cart-REST.png ├── aws-api-gateway-mapping-template ├── aws-lambda-cart-microservice.png ├── build.gradle ├── gradle ├── integrationtest.gradle ├── jacoco.gradle ├── jaxb.gradle ├── jdepend.gradle ├── pmd.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── com │ │ └── org │ │ └── cart │ │ ├── action │ │ ├── AbstractAction.java │ │ ├── Action.java │ │ ├── CreateCartAction.java │ │ ├── DeleteCartAction.java │ │ ├── ReadCartAction.java │ │ ├── UpdateCartAction.java │ │ └── model │ │ │ └── ListCartAbandon.java │ │ ├── application │ │ └── DynamoDBConfiguration.java │ │ ├── dao │ │ └── DynamoDBManager.java │ │ ├── exception │ │ ├── AuthorizationException.java │ │ ├── BadRequestException.java │ │ ├── DAOException.java │ │ ├── DefaultException.java │ │ └── InternalErrorException.java │ │ ├── model │ │ ├── CartAccess.java │ │ ├── DateObj.java │ │ ├── LambdaRequest.java │ │ ├── Response.java │ │ └── cart │ │ │ ├── Cart.java │ │ │ ├── CartDAO.java │ │ │ ├── CartDAOImpl.java │ │ │ └── ReadCartResponse.java │ │ ├── router │ │ └── RequestRouter.java │ │ └── utils │ │ ├── DateUtils.java │ │ ├── JsonUtils.java │ │ └── Utils.java └── resources │ └── spring │ ├── app-bean-context.xml │ └── properties-context.xml └── test └── java └── com └── org └── cart ├── action └── ReadCartActionTest.java ├── router └── RequestRouterTest.java └── utils ├── DateUtilsTest.java ├── JsonUtilsTest.java └── UtilsTest.java /README.md: -------------------------------------------------------------------------------- 1 | # cart-lambda 2 | AWS Lambda Cart Micro Service - Serverless REST API's 3 | 4 | ## TODO LIST 5 | 6 | `adding aws cognito security aspect` 7 | 8 | `add more unit testing mocking dynamoDB locally` 9 | 10 | ##Architecture 11 | 12 | ![Architecture](https://github.com/dhanugupta/cart-aws-lambda/blob/master/aws-lambda-cart-microservice.png?raw=true) 13 | 14 | ## Presentation 15 | 16 | http://www.slideshare.net/dhanugupta/aws-lambda-cart-microservice-server-less 17 | 18 | ## Various components used in this example: 19 | 20 | AWS API Gateway 21 | > API Gateway helps developers deliver robust, secure, and scalable mobile and web application back ends. 22 | 23 | AWS Lambda Functions 24 | > Run code without thinking about servers. Pay for only the compute time you consume. 25 | 26 | AWS DynamoDB 27 | > Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models. 28 | 29 | Deployment 30 | > JAVA, Gradle, Jenkins Deployment 31 | 32 | ### AWS DynamoDB 33 | 34 | 1. Create Table on DynamoDB 35 | 36 | Name : ‘cart’ 37 | 38 | Partition Key : ‘loginId’ (String) 39 | 40 | Sort key : ‘sku’ (String) 41 | 42 | Read Capacity Units : 100 43 | 44 | Write Capacity Units : 50 45 | 46 | Note: If you want to read more on provisioned read/write capacities 47 | 48 | http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html 49 | 50 | ### AWS Lambda 51 | 1. Create a new Lambda function. As 52 | 53 | Name : `CartRequestRouter` 54 | 55 | Handler : `com.org.cart.router.RequestRouter::lambdaHandler` 56 | 57 | Runtime Env : `Java` 58 | 59 | Memory : `1024` 60 | 61 | Timeout : `30secs` to start with 62 | 63 | Note : 64 | 1. Ensure your Lambda function is using the correct IAM role. The role must have the ability to write/read to DynamoDB. 65 | 2. All Lambda interactions are logged in Cloudwatch logs. View the logs for debugging. 66 | 67 | 2. The Lambda function handler tells Lambda what java method under `com.org.cart.router.RequestRouter` - 68 | ` lambdaHandler(InputStream request, OutputStream response, Context context) ` 69 | 3. Review & create function. 70 | 71 | ###API Gateway 72 | 1. Create a new API. Give it a name and description. This will be our RESTful endpoint. 73 | 2. Create a resource. The path should be `/cart` , for example. 74 | 3. We need to add one more resource as `/read` under cart as `/cart/read`. Create a GET method with Lambda integration. 75 | 4. Now let's setup the Integration Request. Cart Micro Service GET request will be of type `application/json`. This Integration step will map this type to a JSON object, which Lambda requires. In the Integration Requests page create a mapping template. Content-type is `application/json` and template: 76 | ``` 77 | { 78 | "body" : $input.json('$'), 79 | "headers": { 80 | #foreach($header in $input.params().header.keySet()) 81 | "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end 82 | 83 | #end 84 | }, 85 | "params": { 86 | #foreach($param in $input.params().path.keySet()) 87 | "$param": "$util.escapeJavaScript($util.urlDecode($input.params().path.get($param)))" #if($foreach.hasNext),#end 88 | 89 | #endhjkyt 90 | }, 91 | "query": { 92 | #foreach($queryParam in $input.params().querystring.keySet()) 93 | "$queryParam": "$util.escapeJavaScript($util.urlDecode($input.params().querystring.get($queryParam)))" #if($foreach.hasNext),#end 94 | #end 95 | }, 96 | "stage" : "$context.stage", 97 | "requestId" : "$context.requestId", 98 | "apiId" : "$context.apiId", 99 | "resource-path" : "$context.resourcePath", 100 | "resourceId" : "$context.resourceId", 101 | "httpMethod" : "$context.httpMethod", 102 | "sourceIp" : "$context.identity.sourceIp", 103 | "userAgent" : "$context.identity.userAgent", 104 | "accountId" : "$context.identity.accountId", 105 | "apiKey" : "$context.identity.apiKey", 106 | "caller" : "$context.identity.caller", 107 | "user" : "$context.identity.user", 108 | "userArn" : "$context.identity.userArn" 109 | } 110 | 111 | ``` 112 | 113 | More on [Intergration Requests](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html). 114 | `$input.params()` parse the request object for the corresponding variable and allows the mapping template to build a JSON object. 115 | 116 | ![Screencast](https://github.com/dhanugupta/cart-aws-lambda/blob/master/aws-api-gateway-cart-REST.png?raw=true) 117 | 118 | 5. Let's ensure the response is correct. Cart Micro Service will respond as valid JSON. 119 | 6. Lambda cannot return valid JSON Response. 120 | 121 | 7. Now let's deploy this API, so we can test it! Click the Deploy API button. 122 | 123 | ###Connecting the dots & Testing 124 | 125 | 1. We should now have a publically accessible GET endpoint. Ex: `https://xxxx.execute-api.us-west-2.amazonaws.com/prod/cart` 126 | 2. Make sure you add API Key to API Gateway for security purpose. Each client has to provie `x-api-key:xxxxxxxx` to access each REST API's. 127 | 3. You can access read API as `https://xxxx.execute-api.us-west-2.amazonaws.com/prod/cart/read?loginId=xxxx` and response will be JSON Object like 128 | ``` 129 | { cart:[], 130 | code:200, 131 | loginId:xxx} 132 | ``` 133 | 134 | ##Troubleshooting 135 | 136 | 1. Cloudwatch logs are your friends. 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /aws-api-gateway-cart-REST.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dhanugupta/cart-aws-lambda/1b3933ff333d320a131a8187fff1cdaf2873b21e/aws-api-gateway-cart-REST.png -------------------------------------------------------------------------------- /aws-api-gateway-mapping-template: -------------------------------------------------------------------------------- 1 | { 2 | "body" : $input.json('$'), 3 | "headers": { 4 | #foreach($header in $input.params().header.keySet()) 5 | "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end 6 | 7 | #end 8 | }, 9 | "params": { 10 | #foreach($param in $input.params().path.keySet()) 11 | "$param": "$util.escapeJavaScript($util.urlDecode($input.params().path.get($param)))" #if($foreach.hasNext),#end 12 | 13 | #endhjkyt 14 | }, 15 | "query": { 16 | #foreach($queryParam in $input.params().querystring.keySet()) 17 | "$queryParam": "$util.escapeJavaScript($util.urlDecode($input.params().querystring.get($queryParam)))" #if($foreach.hasNext),#end 18 | #end 19 | }, 20 | "stage" : "$context.stage", 21 | "requestId" : "$context.requestId", 22 | "apiId" : "$context.apiId", 23 | "resource-path" : "$context.resourcePath", 24 | "resourceId" : "$context.resourceId", 25 | "httpMethod" : "$context.httpMethod", 26 | "sourceIp" : "$context.identity.sourceIp", 27 | "userAgent" : "$context.identity.userAgent", 28 | "accountId" : "$context.identity.accountId", 29 | "apiKey" : "$context.identity.apiKey", 30 | "caller" : "$context.identity.caller", 31 | "user" : "$context.identity.user", 32 | "userArn" : "$context.identity.userArn" 33 | } 34 | -------------------------------------------------------------------------------- /aws-lambda-cart-microservice.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dhanugupta/cart-aws-lambda/1b3933ff333d320a131a8187fff1cdaf2873b21e/aws-lambda-cart-microservice.png -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | maven { url 'http://dl.bintray.com/robfletcher/gradle-plugins' } 5 | } 6 | dependencies { 7 | 8 | } 9 | } 10 | 11 | apply plugin: 'java' 12 | apply plugin: 'eclipse' 13 | 14 | project.ext.buildnumber = System.env.BUILD_NUMBER 15 | import org.apache.tools.ant.filters.* 16 | 17 | processResources { 18 | filter ReplaceTokens, tokens: [ 19 | "project.buildnumber": project.getProperty("buildnumber").toString() 20 | ] 21 | } 22 | 23 | eclipse { 24 | jdt { 25 | //if you want to alter the java versions (by default they are configured with gradle java plugin settings): 26 | sourceCompatibility = 1.8 27 | targetCompatibility = 1.8 28 | } 29 | } 30 | 31 | version = 1.0 32 | 33 | apply plugin: 'war' 34 | war { 35 | baseName = 'cart' 36 | } 37 | 38 | 39 | repositories { 40 | mavenCentral() 41 | maven { url "http://repo.opensourceagility.com/release/"} 42 | } 43 | def springRelease="4.2.3.RELEASE" 44 | 45 | dependencies { 46 | compile group: 'commons-collections', name: 'commons-collections', version: '3.2' 47 | testCompile group: 'junit', name: 'junit', version: '4.+' 48 | 49 | // Spring integration 50 | compile('org.springframework:spring-core:4.2.3.RELEASE') 51 | 52 | compile('org.springframework:spring-framework-bom:4.2.3.RELEASE') 53 | compile('org.springframework:spring-context:4.2.3.RELEASE') 54 | compile('org.springframework:spring-aop:4.2.3.RELEASE') 55 | compile('org.springframework:spring-webmvc:4.2.3.RELEASE'); 56 | 57 | compile('org.resthub:springmvc-router:1.2.1') 58 | 59 | compile ('org.slf4j:slf4j-simple:1.7.6') 60 | 61 | compile('com.google.code.gson:gson:2.3.1') 62 | compile('javax.servlet:javax.servlet-api:3.0.1') 63 | //Spring Reflections for test 64 | testCompile("org.springframework:spring-test:4.2.3.RELEASE") 65 | //Mock 66 | testCompile "org.mockito:mockito-all:1.9.5" 67 | // Mappers 68 | compile("com.fasterxml.jackson.core:jackson-databind:2.3.1") 69 | 70 | compile 'com.amazonaws:aws-lambda-java-core:1.0.0' 71 | 72 | compile('com.amazonaws:aws-java-sdk:1.10.40') 73 | } 74 | 75 | 76 | task buildZip(type: Zip) { 77 | from compileJava 78 | from processResources 79 | into('lib') { 80 | from configurations.runtime 81 | } 82 | baseName = 'cart' 83 | } 84 | 85 | build.dependsOn buildZip 86 | 87 | 88 | task wrapper(type: Wrapper) { 89 | gradleVersion = '2.2' 90 | } -------------------------------------------------------------------------------- /gradle/integrationtest.gradle: -------------------------------------------------------------------------------- 1 | // Integration Tests 2 | sourceSets { 3 | integrationTest { 4 | java.srcDir file('src/integrationtest/java') 5 | resources.srcDir file('src/integrationtest/resources') 6 | compileClasspath = sourceSets.main.output + configurations.testRuntime 7 | runtimeClasspath = output + compileClasspath 8 | } 9 | } 10 | 11 | task integrationTest(type: Test) { 12 | description = 'Runs the integration tests' 13 | group = 'verification' 14 | testClassesDir = sourceSets.integrationTest.output.classesDir 15 | classpath = sourceSets.integrationTest.runtimeClasspath 16 | reports.junitXml.destination = file("$reports.junitXml.destination/integration") 17 | } 18 | -------------------------------------------------------------------------------- /gradle/jacoco.gradle: -------------------------------------------------------------------------------- 1 | // Code Coverage 2 | 3 | apply plugin: "jacoco" 4 | 5 | test { 6 | jacoco { 7 | excludes = ["**/*Test.java com/aol/ecommerce/schema/*.java **/*JAXBDebug.java com/aol/cmi/application/*.java"] 8 | } 9 | } 10 | 11 | task jacocoIntegrationTestReport(type: JacocoReport) { 12 | sourceSets sourceSets.main 13 | executionData integrationTest 14 | } 15 | 16 | integrationTest { 17 | jacoco { 18 | excludes = ["**/*Test.java com/aol/ecommerce/schema/*.java **/*JAXBDebug.java com/aol/cmi/application/*.java"] 19 | } 20 | } 21 | 22 | jacocoTestReport.doFirst{ 23 | classDirectories = files('build/classes/main/com/aol/avocado') 24 | } 25 | 26 | jacocoIntegrationTestReport.doFirst{ 27 | classDirectories = files('build/classes/main/com/aol/avocado') 28 | } 29 | 30 | -------------------------------------------------------------------------------- /gradle/jaxb.gradle: -------------------------------------------------------------------------------- 1 | configurations { 2 | jaxb 3 | } 4 | 5 | dependencies { 6 | // JAXB 7 | jaxb 'com.sun.xml.bind:jaxb-xjc:2.2.4-1' 8 | } 9 | 10 | task jaxb () { 11 | // output directory 12 | def jaxbTargetDir = file( "${buildDir}/generated-src" ) 13 | 14 | // perform actions 15 | doLast { 16 | jaxbTargetDir.mkdirs() 17 | 18 | ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath) 19 | ant.jaxbTargetDir = jaxbTargetDir 20 | 21 | // ecommerce web service 22 | ant.xjc(destdir: '${jaxbTargetDir}', package: 'com.aol.ecommerce', schema: 'src/main/resources/com/aol/ecommerce/ecommerce.xsd') 23 | 24 | } 25 | 26 | } 27 | 28 | compileJava.dependsOn jaxb 29 | 30 | sourceSets { 31 | main { 32 | java.srcDir file("$buildDir/generated-src") 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /gradle/jdepend.gradle: -------------------------------------------------------------------------------- 1 | // Code Quality - JDepend 2 | 3 | apply plugin: "jdepend" 4 | 5 | jdepend { 6 | ignoreFailures = true 7 | } 8 | -------------------------------------------------------------------------------- /gradle/pmd.gradle: -------------------------------------------------------------------------------- 1 | // Code Quality - PMD 2 | 3 | apply plugin: "pmd" 4 | 5 | pmd { 6 | ignoreFailures = true 7 | } 8 | 9 | tasks.withType(Pmd) { 10 | reports { 11 | xml.enabled = true 12 | html.enabled = true 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dhanugupta/cart-aws-lambda/1b3933ff333d320a131a8187fff1cdaf2873b21e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 30 09:49:34 CDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http://pse-ci-a01.twhite.aol.com//gradle-2.2-20140814162226+0000-bin-Sonar44Fix.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | GRADLE_OPTS="-Xmx1536m -Xms1024m -XX:MaxPermSize=512m -XX:+CMSClassUnloadingEnabled -XX:+HeapDumpOnOutOfMemoryError" 12 | 13 | APP_NAME="Gradle" 14 | APP_BASE_NAME=`basename "$0"` 15 | 16 | # Use the maximum available, or set MAX_FD != -1 to use that value. 17 | MAX_FD="maximum" 18 | 19 | warn ( ) { 20 | echo "$*" 21 | } 22 | 23 | die ( ) { 24 | echo 25 | echo "$*" 26 | echo 27 | exit 1 28 | } 29 | 30 | # OS specific support (must be 'true' or 'false'). 31 | cygwin=false 32 | msys=false 33 | darwin=false 34 | case "`uname`" in 35 | CYGWIN* ) 36 | cygwin=true 37 | ;; 38 | Darwin* ) 39 | darwin=true 40 | ;; 41 | MINGW* ) 42 | msys=true 43 | ;; 44 | esac 45 | 46 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 47 | if $cygwin ; then 48 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 49 | fi 50 | 51 | # Attempt to set APP_HOME 52 | # Resolve links: $0 may be a link 53 | PRG="$0" 54 | # Need this for relative symlinks. 55 | while [ -h "$PRG" ] ; do 56 | ls=`ls -ld "$PRG"` 57 | link=`expr "$ls" : '.*-> \(.*\)$'` 58 | if expr "$link" : '/.*' > /dev/null; then 59 | PRG="$link" 60 | else 61 | PRG=`dirname "$PRG"`"/$link" 62 | fi 63 | done 64 | SAVED="`pwd`" 65 | cd "`dirname \"$PRG\"`/" >&- 66 | APP_HOME="`pwd -P`" 67 | cd "$SAVED" >&- 68 | 69 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 70 | 71 | # Determine the Java command to use to start the JVM. 72 | if [ -n "$JAVA_HOME" ] ; then 73 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 74 | # IBM's JDK on AIX uses strange locations for the executables 75 | JAVACMD="$JAVA_HOME/jre/sh/java" 76 | else 77 | JAVACMD="$JAVA_HOME/bin/java" 78 | fi 79 | if [ ! -x "$JAVACMD" ] ; then 80 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 81 | 82 | Please set the JAVA_HOME variable in your environment to match the 83 | location of your Java installation." 84 | fi 85 | else 86 | JAVACMD="java" 87 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 88 | 89 | Please set the JAVA_HOME variable in your environment to match the 90 | location of your Java installation." 91 | fi 92 | 93 | # Increase the maximum file descriptors if we can. 94 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 95 | MAX_FD_LIMIT=`ulimit -H -n` 96 | if [ $? -eq 0 ] ; then 97 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 98 | MAX_FD="$MAX_FD_LIMIT" 99 | fi 100 | ulimit -n $MAX_FD 101 | if [ $? -ne 0 ] ; then 102 | warn "Could not set maximum file descriptor limit: $MAX_FD" 103 | fi 104 | else 105 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 106 | fi 107 | fi 108 | 109 | # For Darwin, add options to specify how the application appears in the dock 110 | if $darwin; then 111 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 112 | fi 113 | 114 | # For Cygwin, switch paths to Windows format before running java 115 | if $cygwin ; then 116 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 117 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 118 | 119 | # We build the pattern for arguments to be converted via cygpath 120 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 121 | SEP="" 122 | for dir in $ROOTDIRSRAW ; do 123 | ROOTDIRS="$ROOTDIRS$SEP$dir" 124 | SEP="|" 125 | done 126 | OURCYGPATTERN="(^($ROOTDIRS))" 127 | # Add a user-defined pattern to the cygpath arguments 128 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 129 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 130 | fi 131 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 132 | i=0 133 | for arg in "$@" ; do 134 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 135 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 136 | 137 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 138 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 139 | else 140 | eval `echo args$i`="\"$arg\"" 141 | fi 142 | i=$((i+1)) 143 | done 144 | case $i in 145 | (0) set -- ;; 146 | (1) set -- "$args0" ;; 147 | (2) set -- "$args0" "$args1" ;; 148 | (3) set -- "$args0" "$args1" "$args2" ;; 149 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 150 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 151 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 152 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 153 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 154 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 155 | esac 156 | fi 157 | 158 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 159 | function splitJvmOpts() { 160 | JVM_OPTS=("$@") 161 | } 162 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 163 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 164 | 165 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 166 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/AbstractAction.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | 6 | public abstract class AbstractAction implements Action{ 7 | 8 | /** 9 | * Returns an initialized Gson object with the default configuration 10 | * @return An initialized Gson object 11 | */ 12 | protected Gson getGson() { 13 | return new GsonBuilder() 14 | //.enableComplexMapKeySerialization() 15 | //.serializeNulls() 16 | //.setDateFormat(DateFormat.LONG) 17 | //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) 18 | .setPrettyPrinting() 19 | .create(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/Action.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import com.amazonaws.services.lambda.runtime.Context; 4 | import com.org.cart.exception.AuthorizationException; 5 | import com.org.cart.exception.BadRequestException; 6 | import com.org.cart.exception.DAOException; 7 | import com.org.cart.model.LambdaRequest; 8 | 9 | public interface Action { 10 | 11 | String handle(LambdaRequest lambdaRequest, Context context) throws AuthorizationException,BadRequestException,DAOException,Exception; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/CreateCartAction.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.util.StringUtils; 6 | 7 | import com.amazonaws.services.lambda.runtime.Context; 8 | import com.google.gson.Gson; 9 | import com.org.cart.dao.DynamoDBManager; 10 | import com.org.cart.exception.BadRequestException; 11 | import com.org.cart.exception.DAOException; 12 | import com.org.cart.model.LambdaRequest; 13 | import com.org.cart.model.cart.Cart; 14 | import com.org.cart.model.cart.CartDAO; 15 | import com.org.cart.model.cart.ReadCartResponse; 16 | 17 | public class CreateCartAction extends AbstractAction{ 18 | 19 | static final Logger LOGGER = LoggerFactory.getLogger(CreateCartAction.class); 20 | 21 | private static final String LOGINID = "loginId"; 22 | 23 | private static final String SKU = "sku"; 24 | 25 | private static final String SUCCESS = "200"; 26 | 27 | 28 | @Override 29 | public String handle(LambdaRequest lambdaRequest, Context context) 30 | throws BadRequestException,DAOException, Exception { 31 | 32 | validateRequest(lambdaRequest); 33 | 34 | Cart cartBody = new Gson().fromJson(lambdaRequest.getBody(), Cart.class); 35 | 36 | CartDAO dao = DynamoDBManager.getCartDAO(); 37 | 38 | try { 39 | dao.createCart(cartBody); 40 | } catch (Exception e) { 41 | 42 | LOGGER.info("Error while creating the cart" + e.getMessage()); 43 | throw new BadRequestException("ERROR CREATING THE CART ITEM"); 44 | } 45 | 46 | ReadCartResponse readCartResponse = new ReadCartResponse(); 47 | readCartResponse.setLoginId(cartBody.getLoginId()); 48 | readCartResponse.setCode(SUCCESS); 49 | 50 | return new Gson().toJson(readCartResponse); 51 | } 52 | 53 | private void validateRequest(LambdaRequest lambdaRequest) throws BadRequestException { 54 | if(!lambdaRequest.getBody().has(LOGINID)) { 55 | throw new BadRequestException("NO LOGINID PARAM PRESENT"); 56 | } 57 | if(!lambdaRequest.getBody().has(SKU)) { 58 | throw new BadRequestException("NO SKU PARAM PRESENT"); 59 | } 60 | if(StringUtils.isEmpty(lambdaRequest.getBody().get(LOGINID).getAsString())){ 61 | throw new BadRequestException("EMPTY LOGINID PRESENT"); 62 | } 63 | 64 | if(StringUtils.isEmpty(lambdaRequest.getBody().get(SKU).getAsString())){ 65 | throw new BadRequestException("EMPTY SKU PRESENT"); 66 | } 67 | 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/DeleteCartAction.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.util.StringUtils; 6 | 7 | import com.amazonaws.services.lambda.runtime.Context; 8 | import com.google.gson.Gson; 9 | import com.org.cart.dao.DynamoDBManager; 10 | import com.org.cart.exception.BadRequestException; 11 | import com.org.cart.model.LambdaRequest; 12 | import com.org.cart.model.cart.Cart; 13 | import com.org.cart.model.cart.CartDAO; 14 | import com.org.cart.model.cart.ReadCartResponse; 15 | 16 | public class DeleteCartAction extends AbstractAction{ 17 | 18 | static final Logger LOGGER = LoggerFactory.getLogger(DeleteCartAction.class); 19 | 20 | private static final String LOGINID = "loginId"; 21 | 22 | private static final String SUCCESS = "200"; 23 | 24 | @Override 25 | public String handle(LambdaRequest lambdaRequest, Context context) 26 | throws BadRequestException { 27 | 28 | validateRequest(lambdaRequest); 29 | 30 | CartDAO dao = DynamoDBManager.getCartDAO(); 31 | Cart cart = new Cart(); 32 | cart.setLoginId(lambdaRequest.getQuery().get(LOGINID).getAsString()); 33 | if(!StringUtils.isEmpty(lambdaRequest.getQuery().get("sku"))){ 34 | cart.setSku(lambdaRequest.getQuery().get("sku").getAsString()); 35 | } 36 | try { 37 | dao.deleteItem(cart); 38 | } catch (Exception e) { 39 | LOGGER.info("Error while deleting the cart item response\n" + e.getMessage()); 40 | throw new BadRequestException("ERROR Deleting THE Cart Data"); 41 | } 42 | 43 | ReadCartResponse readCartResponse = new ReadCartResponse(); 44 | 45 | readCartResponse.setCode(SUCCESS); 46 | 47 | return new Gson().toJson(readCartResponse); 48 | } 49 | 50 | private void validateRequest(final LambdaRequest lambdaRequest) throws BadRequestException { 51 | if(!lambdaRequest.getQuery().has(LOGINID)) { 52 | throw new BadRequestException("NO LOGINID PARAM PRESENT"); 53 | } 54 | if(StringUtils.isEmpty(lambdaRequest.getQuery().get(LOGINID).getAsString())){ 55 | throw new BadRequestException("EMPTY LOGINID PRESENT"); 56 | } 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/ReadCartAction.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.util.StringUtils; 9 | 10 | import com.amazonaws.services.lambda.runtime.Context; 11 | import com.google.gson.Gson; 12 | import com.org.cart.dao.DynamoDBManager; 13 | import com.org.cart.exception.BadRequestException; 14 | import com.org.cart.model.LambdaRequest; 15 | import com.org.cart.model.cart.Cart; 16 | import com.org.cart.model.cart.CartDAO; 17 | import com.org.cart.model.cart.ReadCartResponse; 18 | 19 | 20 | public class ReadCartAction extends AbstractAction{ 21 | 22 | static final Logger LOGGER = LoggerFactory.getLogger(ReadCartAction.class); 23 | 24 | private static final String LOGINID = "loginId"; 25 | 26 | private static final String SUCCESS = "200"; 27 | 28 | @Override 29 | public String handle(LambdaRequest lambdaRequest, Context context) 30 | throws BadRequestException { 31 | 32 | validateRequest(lambdaRequest); 33 | 34 | String loginId = lambdaRequest.getQuery().get(LOGINID).getAsString(); 35 | 36 | CartDAO dao = DynamoDBManager.getCartDAO(); 37 | List cartList = new ArrayList(); 38 | try { 39 | cartList = dao.getCartByLoginId(loginId); 40 | } catch (Exception e) { 41 | LOGGER.info("ERROR RETRIEVING THE DATA FROM DYANMODB " + e.getMessage()); 42 | throw new BadRequestException("ERROR RETRIEVING THE DATA FROM DYANMODB"); 43 | } 44 | 45 | ReadCartResponse readCartResponse = new ReadCartResponse(); 46 | readCartResponse.setLoginId(loginId); 47 | readCartResponse.setCart(cartList); 48 | readCartResponse.setCode(SUCCESS); 49 | 50 | return new Gson().toJson(readCartResponse); 51 | 52 | } 53 | 54 | private void validateRequest(LambdaRequest lambdaRequest) throws BadRequestException { 55 | if(lambdaRequest.getQuery() == null){ 56 | throw new BadRequestException("NO REQUEST PARAM PRESENT"); 57 | } 58 | if(!lambdaRequest.getQuery().has(LOGINID)) { 59 | throw new BadRequestException("NO LOGINID PARAM PRESENT"); 60 | } 61 | if(StringUtils.isEmpty(lambdaRequest.getQuery().get(LOGINID).getAsString())){ 62 | LOGGER.info("jkshfjs"); 63 | throw new BadRequestException("EMPTY LOGINID PRESENT"); 64 | } 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/UpdateCartAction.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.util.StringUtils; 6 | 7 | import com.amazonaws.services.lambda.runtime.Context; 8 | import com.google.gson.Gson; 9 | import com.org.cart.dao.DynamoDBManager; 10 | import com.org.cart.exception.BadRequestException; 11 | import com.org.cart.exception.DAOException; 12 | import com.org.cart.model.LambdaRequest; 13 | import com.org.cart.model.cart.Cart; 14 | import com.org.cart.model.cart.CartDAO; 15 | import com.org.cart.model.cart.ReadCartResponse; 16 | 17 | public class UpdateCartAction extends AbstractAction{ 18 | 19 | static final Logger LOGGER = LoggerFactory.getLogger(UpdateCartAction.class); 20 | 21 | private static final String LOGINID = "loginId"; 22 | 23 | private static final String SKU = "sku"; 24 | 25 | private static final String SUCCESS = "200"; 26 | 27 | 28 | @Override 29 | public String handle(LambdaRequest lambdaRequest, Context context) 30 | throws BadRequestException,DAOException, Exception { 31 | 32 | validateRequest(lambdaRequest); 33 | 34 | Cart cartBody = new Gson().fromJson(lambdaRequest.getBody(), Cart.class); 35 | 36 | CartDAO dao = DynamoDBManager.getCartDAO(); 37 | 38 | try { 39 | dao.createCart(cartBody); 40 | } catch (Exception e) { 41 | 42 | LOGGER.info("Error while creating the cart" + e.getMessage()); 43 | throw new BadRequestException("ERROR UPDATING THE CART ITEM"); 44 | } 45 | 46 | ReadCartResponse readCartResponse = new ReadCartResponse(); 47 | readCartResponse.setLoginId(cartBody.getLoginId()); 48 | readCartResponse.setCode(SUCCESS); 49 | 50 | return new Gson().toJson(readCartResponse); 51 | } 52 | 53 | private void validateRequest(LambdaRequest lambdaRequest) throws BadRequestException { 54 | if(!lambdaRequest.getBody().has(LOGINID)) { 55 | throw new BadRequestException("NO LOGINID PARAM PRESENT"); 56 | } 57 | if(!lambdaRequest.getBody().has(SKU)) { 58 | throw new BadRequestException("NO SKU PARAM PRESENT"); 59 | } 60 | if(StringUtils.isEmpty(lambdaRequest.getBody().get(LOGINID).getAsString())){ 61 | throw new BadRequestException("EMPTY LOGINID PRESENT"); 62 | } 63 | 64 | if(StringUtils.isEmpty(lambdaRequest.getBody().get(SKU).getAsString())){ 65 | throw new BadRequestException("EMPTY SKU PRESENT"); 66 | } 67 | 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/action/model/ListCartAbandon.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action.model; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.org.cart.model.cart.Cart; 7 | 8 | public class ListCartAbandon { 9 | List cart = new ArrayList(); 10 | 11 | /** 12 | * @return the cart 13 | */ 14 | public List getCart() { 15 | return cart; 16 | } 17 | 18 | /** 19 | * @param cart the cart to set 20 | */ 21 | public void setCart(List cart) { 22 | this.cart = cart; 23 | } 24 | 25 | 26 | 27 | 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/application/DynamoDBConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.application; 2 | 3 | public class DynamoDBConfiguration { 4 | 5 | public static final String CART_TABLE_NAME = "cart"; 6 | 7 | public static final String CART_ACCESS_TABLE_NAME = "cartaccess"; 8 | 9 | public static final int SCAN_LIMIT = 50; 10 | 11 | 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/dao/DynamoDBManager.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.dao; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; 7 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; 8 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; 9 | import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedList; 10 | import com.amazonaws.services.dynamodbv2.model.ListTablesResult; 11 | import com.org.cart.exception.DAOException; 12 | import com.org.cart.model.cart.CartDAO; 13 | import com.org.cart.model.cart.CartDAOImpl; 14 | 15 | public class DynamoDBManager { 16 | 17 | // credentials for the client come from the environment variables pre-configured by Lambda. These are tied to the 18 | // Lambda function execution role.new BasicAWSCredentials(amazonAWSAccessKey,amazonAWSSecretKey) 19 | private static AmazonDynamoDBClient dynamoDB; 20 | 21 | public static void init() throws Exception,DAOException { 22 | dynamoDB = new AmazonDynamoDBClient(); 23 | } 24 | 25 | public static void save(Object entity) { 26 | DynamoDBMapper mapper = new DynamoDBMapper(dynamoDB); 27 | mapper.save(entity); 28 | } 29 | 30 | public static PaginatedList query(Class klass, DynamoDBQueryExpression query) { 31 | DynamoDBMapper mapper = new DynamoDBMapper(dynamoDB); 32 | PaginatedList list = mapper.query(klass, query); 33 | return list; 34 | } 35 | 36 | public static T get(Class klass, DynamoDBQueryExpression query) { 37 | DynamoDBMapper mapper = new DynamoDBMapper(dynamoDB); 38 | PaginatedList list = mapper.query(klass, query); 39 | if (list.isEmpty()) { 40 | return null; 41 | } 42 | return list.get(0); 43 | } 44 | 45 | public static List tableNames() { 46 | ListTablesResult tables = dynamoDB.listTables(); 47 | List result = new ArrayList(); 48 | for (String tableName : tables.getTableNames()) { 49 | result.add(tableName); 50 | } 51 | return result; 52 | } 53 | 54 | /** 55 | * Contains the implementations of the DAO objects. By default we only have a DynamoDB implementation 56 | */ 57 | public enum DAOType { 58 | DynamoDB 59 | } 60 | 61 | public static CartDAO getCartDAO(DAOType daoType) { 62 | CartDAO dao = null; 63 | switch (daoType) { 64 | case DynamoDB: 65 | dao = CartDAOImpl.getInstance(); 66 | break; 67 | } 68 | 69 | return dao; 70 | } 71 | 72 | public static CartDAO getCartDAO() { 73 | return getCartDAO(DAOType.DynamoDB); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/exception/AuthorizationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.exception; 14 | 15 | /** 16 | * This exception is thrown whenever this service is not authorize to communicate with another AWS service, it should not 17 | * be exposed to Lambda or returned to the client. When this exception is caught we should throw an InternalErrorException 18 | */ 19 | public class AuthorizationException extends Exception { 20 | /** 21 | * 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | private static final String PREFIX = "AUTH_REQ: "; 25 | public AuthorizationException(String s, Exception e) { 26 | super(PREFIX+s, e); 27 | } 28 | 29 | public AuthorizationException(String s) { 30 | super(PREFIX+s); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/exception/BadRequestException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.exception; 14 | 15 | /** 16 | * This exception should be thrown whenever requests fail validation. The exception sets a default pattern in the string 17 | * "BAD_REQ: .*" that can be easily matched from the API Gateway for mapping. 18 | */ 19 | public class BadRequestException extends Exception { 20 | /** 21 | * 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | private static final String PREFIX = "BAD_REQ: "; 25 | public BadRequestException(String s, Exception e) { 26 | super(PREFIX + s, e); 27 | } 28 | 29 | public BadRequestException(String s) { 30 | super(PREFIX + s); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/exception/DAOException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.exception; 14 | 15 | /** 16 | * This exception should bot be exposed to Lambda or the client application. It's used internally to identify a DAO issue 17 | */ 18 | public class DAOException extends Exception { 19 | /** 20 | * 21 | */ 22 | private static final long serialVersionUID = 1L; 23 | 24 | public DAOException(String s, Exception e) { 25 | super(s, e); 26 | } 27 | 28 | public DAOException(String s) { 29 | super(s); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/exception/DefaultException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.exception; 14 | 15 | /** 16 | * This exception is thrown whenever this service is not authorize to communicate with another AWS service, it should not 17 | * be exposed to Lambda or returned to the client. When this exception is caught we should throw an InternalErrorException 18 | */ 19 | public class DefaultException extends Exception { 20 | /** 21 | * 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | 25 | public DefaultException(String s, Exception e) { 26 | super(s, e); 27 | } 28 | 29 | public DefaultException(String s) { 30 | super(s); 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/exception/InternalErrorException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.exception; 14 | 15 | 16 | /** 17 | * This exception is thrown whenever an internal error occurs, for example a DAO error if the data store is not accessible. 18 | * The exception sets a default pattern in the string "INT_ERROR: .*" that can be easily matched from the API Gateway for 19 | * mapping. 20 | */ 21 | public class InternalErrorException extends Exception { 22 | /** 23 | * 24 | */ 25 | private static final long serialVersionUID = 1L; 26 | private static final String PREFIX = "INT_ERROR: "; 27 | 28 | public InternalErrorException(String s, Exception e) { 29 | super(PREFIX + s, e); 30 | } 31 | 32 | public InternalErrorException(String s) { 33 | super(PREFIX + s); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/CartAccess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance 5 | * with the License. A copy of the License is located at 6 | * 7 | * http://aws.amazon.com/apache2.0/ 8 | * 9 | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 10 | * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions 11 | * and limitations under the License. 12 | */ 13 | package com.org.cart.model; 14 | 15 | import java.io.Serializable; 16 | import java.util.Date; 17 | 18 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; 19 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; 20 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; 21 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 22 | import com.org.cart.application.DynamoDBConfiguration; 23 | import com.org.cart.utils.DateUtils; 24 | 25 | /** 26 | * The Pet object. This bean also contains the annotations required for the DynamoDB object mapper to work 27 | */ 28 | @DynamoDBTable(tableName = DynamoDBConfiguration.CART_ACCESS_TABLE_NAME) 29 | @JsonIgnoreProperties(ignoreUnknown=true) 30 | public class CartAccess implements Serializable { 31 | 32 | private static final long serialVersionUID = -5633936564993343482L; 33 | private String createdAt = DateUtils.getStringDate(new Date()); 34 | private String updatedAt = DateUtils.getStringDate(new Date()); 35 | 36 | private String accessKey; 37 | 38 | private String resourcePath; 39 | 40 | private boolean access; 41 | 42 | 43 | 44 | /** 45 | * @return the accessKey 46 | */ 47 | @DynamoDBHashKey 48 | @DynamoDBAttribute(attributeName = "accessKey") 49 | public String getAccessKey() { 50 | return accessKey; 51 | } 52 | 53 | /** 54 | * @param accessKey the accessKey to set 55 | */ 56 | public void setAccessKey(String accessKey) { 57 | this.accessKey = accessKey; 58 | } 59 | 60 | 61 | 62 | /** 63 | * @return the resourcePath 64 | */ 65 | public String getResourcePath() { 66 | return resourcePath; 67 | } 68 | 69 | /** 70 | * @param resourcePath the resourcePath to set 71 | */ 72 | public void setResourcePath(String resourcePath) { 73 | this.resourcePath = resourcePath; 74 | } 75 | 76 | /** 77 | * @return the access 78 | */ 79 | @DynamoDBAttribute(attributeName = "access") 80 | public boolean isAccess() { 81 | return access; 82 | } 83 | 84 | /** 85 | * @param access the access to set 86 | */ 87 | public void setAccess(boolean access) { 88 | this.access = access; 89 | } 90 | 91 | /** 92 | * @return the createdAt 93 | */ 94 | @DynamoDBAttribute(attributeName = "createdAt") 95 | public String getCreatedAt() { 96 | return createdAt; 97 | } 98 | 99 | /** 100 | * @param createdAt the createdAt to set 101 | */ 102 | public void setCreatedAt(String createdAt) { 103 | this.createdAt = createdAt; 104 | } 105 | 106 | /** 107 | * @return the updatedAt 108 | */ 109 | @DynamoDBAttribute(attributeName = "updatedAt") 110 | public String getUpdatedAt() { 111 | return updatedAt; 112 | } 113 | 114 | /** 115 | * @param updatedAt the updatedAt to set 116 | */ 117 | public void setUpdatedAt(String updatedAt) { 118 | this.updatedAt = updatedAt; 119 | } 120 | 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/DateObj.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | 7 | @JsonIgnoreProperties(ignoreUnknown=true) 8 | public class DateObj implements Serializable { 9 | 10 | private static final long serialVersionUID = 1L; 11 | 12 | private long days; 13 | 14 | private long hours; 15 | 16 | private long minutes; 17 | 18 | private long seconds; 19 | 20 | /** 21 | * @return the days 22 | */ 23 | public long getDays() { 24 | return days; 25 | } 26 | 27 | /** 28 | * @param days the days to set 29 | */ 30 | public void setDays(long days) { 31 | this.days = days; 32 | } 33 | 34 | /** 35 | * @return the hours 36 | */ 37 | public long getHours() { 38 | return hours; 39 | } 40 | 41 | /** 42 | * @param hours the hours to set 43 | */ 44 | public void setHours(long hours) { 45 | this.hours = hours; 46 | } 47 | 48 | /** 49 | * @return the minutes 50 | */ 51 | public long getMinutes() { 52 | return minutes; 53 | } 54 | 55 | /** 56 | * @param minutes the minutes to set 57 | */ 58 | public void setMinutes(long minutes) { 59 | this.minutes = minutes; 60 | } 61 | 62 | /** 63 | * @return the seconds 64 | */ 65 | public long getSeconds() { 66 | return seconds; 67 | } 68 | 69 | /** 70 | * @param seconds the seconds to set 71 | */ 72 | public void setSeconds(long seconds) { 73 | this.seconds = seconds; 74 | } 75 | 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/LambdaRequest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import com.google.gson.JsonObject; 7 | 8 | 9 | @JsonIgnoreProperties(ignoreUnknown=true) 10 | public class LambdaRequest implements Serializable { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 1L; 16 | 17 | private JsonObject body; 18 | 19 | private JsonObject params; 20 | 21 | private JsonObject query; 22 | 23 | private JsonObject headers; 24 | 25 | private String method; 26 | 27 | private String httpMethod; 28 | 29 | private String apiId; 30 | 31 | private String requestId; 32 | 33 | private String resourceId; 34 | 35 | private String resourcePath; 36 | 37 | private String sourceId; 38 | 39 | private String userAgent; 40 | 41 | private String apiKey; 42 | 43 | private String stage; 44 | 45 | 46 | /** 47 | * @return the body 48 | */ 49 | public JsonObject getBody() { 50 | return body; 51 | } 52 | 53 | /** 54 | * @param body the body to set 55 | */ 56 | public void setBody(JsonObject body) { 57 | this.body = body; 58 | } 59 | 60 | /** 61 | * @return the query 62 | */ 63 | public JsonObject getQuery() { 64 | return query; 65 | } 66 | 67 | /** 68 | * @param query the query to set 69 | */ 70 | public void setQuery(JsonObject query) { 71 | this.query = query; 72 | } 73 | 74 | 75 | 76 | /** 77 | * @return the resourcePath 78 | */ 79 | public String getResourcePath() { 80 | return resourcePath; 81 | } 82 | 83 | /** 84 | * @param resourcePath the resourcePath to set 85 | */ 86 | public void setResourcePath(String resourcePath) { 87 | this.resourcePath = resourcePath; 88 | } 89 | 90 | /** 91 | * @return the params 92 | */ 93 | public JsonObject getParams() { 94 | return params; 95 | } 96 | 97 | /** 98 | * @param params the params to set 99 | */ 100 | public void setParams(JsonObject params) { 101 | this.params = params; 102 | } 103 | 104 | /** 105 | * @return the headers 106 | */ 107 | public JsonObject getHeaders() { 108 | return headers; 109 | } 110 | 111 | /** 112 | * @param headers the headers to set 113 | */ 114 | public void setHeaders(JsonObject headers) { 115 | this.headers = headers; 116 | } 117 | 118 | /** 119 | * @return the method 120 | */ 121 | public String getMethod() { 122 | return method; 123 | } 124 | 125 | /** 126 | * @param method the method to set 127 | */ 128 | public void setMethod(String method) { 129 | this.method = method; 130 | } 131 | 132 | /** 133 | * @return the httpMethod 134 | */ 135 | public String getHttpMethod() { 136 | return httpMethod; 137 | } 138 | 139 | /** 140 | * @param httpMethod the httpMethod to set 141 | */ 142 | public void setHttpMethod(String httpMethod) { 143 | this.httpMethod = httpMethod; 144 | } 145 | 146 | /** 147 | * @return the apiId 148 | */ 149 | public String getApiId() { 150 | return apiId; 151 | } 152 | 153 | /** 154 | * @param apiId the apiId to set 155 | */ 156 | public void setApiId(String apiId) { 157 | this.apiId = apiId; 158 | } 159 | 160 | /** 161 | * @return the requestId 162 | */ 163 | public String getRequestId() { 164 | return requestId; 165 | } 166 | 167 | /** 168 | * @param requestId the requestId to set 169 | */ 170 | public void setRequestId(String requestId) { 171 | this.requestId = requestId; 172 | } 173 | 174 | /** 175 | * @return the resourceId 176 | */ 177 | public String getResourceId() { 178 | return resourceId; 179 | } 180 | 181 | /** 182 | * @param resourceId the resourceId to set 183 | */ 184 | public void setResourceId(String resourceId) { 185 | this.resourceId = resourceId; 186 | } 187 | 188 | /** 189 | * @return the sourceId 190 | */ 191 | public String getSourceId() { 192 | return sourceId; 193 | } 194 | 195 | /** 196 | * @param sourceId the sourceId to set 197 | */ 198 | public void setSourceId(String sourceId) { 199 | this.sourceId = sourceId; 200 | } 201 | 202 | /** 203 | * @return the userAgent 204 | */ 205 | public String getUserAgent() { 206 | return userAgent; 207 | } 208 | 209 | /** 210 | * @param userAgent the userAgent to set 211 | */ 212 | public void setUserAgent(String userAgent) { 213 | this.userAgent = userAgent; 214 | } 215 | 216 | /** 217 | * @return the apiKey 218 | */ 219 | public String getApiKey() { 220 | return apiKey; 221 | } 222 | 223 | /** 224 | * @param apiKey the apiKey to set 225 | */ 226 | public void setApiKey(String apiKey) { 227 | this.apiKey = apiKey; 228 | } 229 | 230 | /** 231 | * @return the stage 232 | */ 233 | public String getStage() { 234 | return stage; 235 | } 236 | 237 | /** 238 | * @param stage the stage to set 239 | */ 240 | public void setStage(String stage) { 241 | this.stage = stage; 242 | } 243 | 244 | 245 | 246 | } 247 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/Response.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.model; 2 | 3 | 4 | public class Response { 5 | 6 | private Object data = new Object(); 7 | private String code; 8 | private String message; 9 | 10 | 11 | /** 12 | * @return the data 13 | */ 14 | public Object getData() { 15 | return data; 16 | } 17 | /** 18 | * @param data the data to set 19 | */ 20 | public void setData(Object data) { 21 | this.data = data; 22 | } 23 | /** 24 | * @return the code 25 | */ 26 | public String getCode() { 27 | return code; 28 | } 29 | /** 30 | * @param code the code to set 31 | */ 32 | public void setCode(String code) { 33 | this.code = code; 34 | } 35 | /** 36 | * @return the message 37 | */ 38 | public String getMessage() { 39 | return message; 40 | } 41 | /** 42 | * @param message the message to set 43 | */ 44 | public void setMessage(String message) { 45 | this.message = message; 46 | } 47 | 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/cart/Cart.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.model.cart; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; 9 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; 10 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; 11 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 12 | import com.org.cart.application.DynamoDBConfiguration; 13 | import com.org.cart.utils.DateUtils; 14 | 15 | /** 16 | * The Cart object. This bean also contains the annotations required for the DynamoDB object mapper to work 17 | */ 18 | @DynamoDBTable(tableName = DynamoDBConfiguration.CART_TABLE_NAME) 19 | @JsonIgnoreProperties(ignoreUnknown=true) 20 | public class Cart implements Serializable { 21 | /** 22 | * 23 | */ 24 | private static final long serialVersionUID = -5633936564993343482L; 25 | private String itemState ="OPEN"; 26 | private String loginId; 27 | 28 | private String sku; 29 | 30 | private String email; 31 | private String createdAt = DateUtils.getStringDate(new Date()); 32 | private String updatedAt = DateUtils.getStringDate(new Date()); 33 | 34 | private String source; 35 | 36 | private String client; 37 | 38 | private String clientIp; 39 | private String lang = "en"; 40 | private String locale = "US"; 41 | 42 | private String country = "US"; 43 | 44 | 45 | private String checkoutUrl; 46 | 47 | 48 | private Map additionalAttributes = new HashMap(); 49 | 50 | 51 | @DynamoDBAttribute(attributeName = "itemState") 52 | public String getItemState() { 53 | return itemState; 54 | } 55 | 56 | public void setItemState(String itemState) { 57 | this.itemState = itemState; 58 | } 59 | 60 | @DynamoDBHashKey 61 | @DynamoDBAttribute(attributeName = "loginId") 62 | public String getLoginId() { 63 | return loginId; 64 | } 65 | 66 | public void setLoginId(String loginId) { 67 | this.loginId = loginId; 68 | } 69 | 70 | /** 71 | * @return the sku 72 | */ 73 | @DynamoDBHashKey 74 | @DynamoDBAttribute(attributeName = "sku") 75 | public String getSku() { 76 | return sku; 77 | } 78 | 79 | /** 80 | * @param sku the sku to set 81 | */ 82 | public void setSku(String sku) { 83 | this.sku = sku; 84 | } 85 | 86 | public String getId() { 87 | // TODO Auto-generated method stub 88 | return null; 89 | } 90 | 91 | /** 92 | * @return the email 93 | */ 94 | @DynamoDBAttribute(attributeName = "email") 95 | public String getEmail() { 96 | return email; 97 | } 98 | 99 | /** 100 | * @param email the email to set 101 | */ 102 | public void setEmail(String email) { 103 | this.email = email; 104 | } 105 | 106 | /** 107 | * @return the createdAt 108 | */ 109 | @DynamoDBAttribute(attributeName = "createdAt") 110 | public String getCreatedAt() { 111 | return createdAt; 112 | } 113 | 114 | /** 115 | * @param createdAt the createdAt to set 116 | */ 117 | public void setCreatedAt(String createdAt) { 118 | this.createdAt = createdAt; 119 | } 120 | 121 | /** 122 | * @return the updatedAt 123 | */ 124 | @DynamoDBAttribute(attributeName = "updatedAt") 125 | public String getUpdatedAt() { 126 | return updatedAt; 127 | } 128 | 129 | /** 130 | * @param updatedAt the updatedAt to set 131 | */ 132 | public void setUpdatedAt(String updatedAt) { 133 | this.updatedAt = updatedAt; 134 | } 135 | 136 | 137 | /** 138 | * @return the source 139 | */ 140 | @DynamoDBAttribute(attributeName = "source") 141 | public String getSource() { 142 | return source; 143 | } 144 | 145 | /** 146 | * @param source the source to set 147 | */ 148 | public void setSource(String source) { 149 | this.source = source; 150 | } 151 | 152 | /** 153 | * @return the clientIp 154 | */ 155 | @DynamoDBAttribute(attributeName = "clientIp") 156 | public String getClientIp() { 157 | return clientIp; 158 | } 159 | 160 | /** 161 | * @param clientIp the clientIp to set 162 | */ 163 | public void setClientIp(String clientIp) { 164 | this.clientIp = clientIp; 165 | } 166 | 167 | /** 168 | * @return the lang 169 | */ 170 | @DynamoDBAttribute(attributeName = "lang") 171 | public String getLang() { 172 | return lang; 173 | } 174 | 175 | /** 176 | * @param lang the lang to set 177 | */ 178 | public void setLang(String lang) { 179 | this.lang = lang; 180 | } 181 | 182 | /** 183 | * @return the locale 184 | */ 185 | @DynamoDBAttribute(attributeName = "locale") 186 | public String getLocale() { 187 | return locale; 188 | } 189 | 190 | /** 191 | * @param locale the locale to set 192 | */ 193 | public void setLocale(String locale) { 194 | this.locale = locale; 195 | } 196 | 197 | /** 198 | * @return the country 199 | */ 200 | @DynamoDBAttribute(attributeName = "country") 201 | public String getCountry() { 202 | return country; 203 | } 204 | 205 | /** 206 | * @param country the country to set 207 | */ 208 | public void setCountry(String country) { 209 | this.country = country; 210 | } 211 | 212 | /** 213 | * @return the client 214 | */ 215 | @DynamoDBAttribute(attributeName = "client") 216 | public String getClient() { 217 | return client; 218 | } 219 | 220 | /** 221 | * @param client the client to set 222 | */ 223 | public void setClient(String client) { 224 | this.client = client; 225 | } 226 | 227 | 228 | 229 | /** 230 | * @return the checkoutUrl 231 | */ 232 | @DynamoDBAttribute(attributeName = "checkoutUrl") 233 | public String getCheckoutUrl() { 234 | return checkoutUrl; 235 | } 236 | 237 | /** 238 | * @param checkoutUrl the checkoutUrl to set 239 | */ 240 | public void setCheckoutUrl(String checkoutUrl) { 241 | this.checkoutUrl = checkoutUrl; 242 | } 243 | 244 | 245 | 246 | /** 247 | * @return the additionalAttributes 248 | */ 249 | @DynamoDBAttribute(attributeName = "additionalAttributes") 250 | public Map getAdditionalAttributes() { 251 | return additionalAttributes; 252 | } 253 | 254 | /** 255 | * @param additionalAttributes the additionalAttributes to set 256 | */ 257 | public void setAdditionalAttributes(Map additionalAttributes) { 258 | this.additionalAttributes = additionalAttributes; 259 | } 260 | 261 | 262 | 263 | } 264 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/cart/CartDAO.java: -------------------------------------------------------------------------------- 1 | 2 | package com.org.cart.model.cart; 3 | 4 | import java.util.List; 5 | 6 | import com.org.cart.exception.DAOException; 7 | 8 | /** 9 | * This interface defines the methods required for an implementation of the PetDAO object 10 | */ 11 | public interface CartDAO { 12 | 13 | Cart getCartByState(String cartState) throws DAOException; 14 | 15 | List getCartByLoginId(String loginId) throws DAOException; 16 | 17 | String createCart(Cart cart) throws DAOException; 18 | 19 | void deleteItem(Cart cart) throws DAOException; 20 | 21 | void deleteAll(Cart cart) throws DAOException; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/cart/CartDAOImpl.java: -------------------------------------------------------------------------------- 1 | 2 | package com.org.cart.model.cart; 3 | 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.util.StringUtils; 11 | 12 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; 13 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; 14 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; 15 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; 16 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; 17 | import com.amazonaws.services.dynamodbv2.model.AttributeValue; 18 | import com.org.cart.exception.DAOException; 19 | 20 | /** 21 | * The DynamoDB implementation of the PetDAO object. This class expects the Pet bean to be annotated with the required 22 | * DynamoDB Object Mapper annotations. Configuration values for the class such as table name and pagination rows is read 23 | * from the DynamoDBConfiguration class in the com.amazonaws.apigateway.configuration package. Credentials for the 24 | * DynamoDB client are read from the environment variables in the Lambda instance. 25 | *

26 | * This class is a singleton and should only be accessed through the static getInstance method. The constructor is defined 27 | * as protected. 28 | */ 29 | public class CartDAOImpl implements CartDAO { 30 | 31 | static final Logger LOGGER = LoggerFactory.getLogger(CartDAOImpl.class); 32 | 33 | private static CartDAOImpl instance = null; 34 | 35 | // credentials for the client come from the environment variables pre-configured by Lambda. These are tied to the 36 | // Lambda function execution role.new BasicAWSCredentials(amazonAWSAccessKey,amazonAWSSecretKey) 37 | private static AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(); 38 | 39 | /** 40 | * Returns the initialized default instance of the PetDAO 41 | * 42 | * @return An initialized PetDAO instance 43 | */ 44 | public static CartDAOImpl getInstance() { 45 | if (instance == null) { 46 | instance = new CartDAOImpl(); 47 | } 48 | 49 | return instance; 50 | } 51 | 52 | protected CartDAOImpl() { 53 | // constructor is protected so that it can't be called from the outside 54 | } 55 | 56 | /** 57 | * Returns a DynamoDBMapper object initialized with the default DynamoDB client 58 | * 59 | * @return An initialized DynamoDBMapper 60 | */ 61 | protected DynamoDBMapper getMapper() { 62 | return new DynamoDBMapper(ddbClient); 63 | } 64 | 65 | @Override 66 | public Cart getCartByState(String cartState) throws DAOException { 67 | return getMapper().load(Cart.class, cartState); 68 | } 69 | 70 | @Override 71 | public List getCartByLoginId(String loginId) throws DAOException { 72 | //QUERY EXPRESSION TO PULL ONLY OPEN ITEM STATE 73 | Cart cartKey = new Cart(); 74 | cartKey.setLoginId(loginId); 75 | 76 | Map expressionAttributeValues = new HashMap(); 77 | expressionAttributeValues.put(":val", new AttributeValue().withS("OPEN")); 78 | 79 | DynamoDBQueryExpression queryExpression = new DynamoDBQueryExpression() 80 | .withHashKeyValues(cartKey) 81 | .withFilterExpression("itemState = :val") 82 | .withExpressionAttributeValues(expressionAttributeValues); 83 | 84 | List cartCollection = getMapper().query(Cart.class, queryExpression); 85 | return cartCollection; 86 | } 87 | 88 | @Override 89 | public String createCart(Cart cart) throws DAOException { 90 | getMapper().save(cart, new DynamoDBMapperConfig(SaveBehavior.UPDATE)); 91 | return cart.getLoginId(); 92 | } 93 | 94 | @Override 95 | public void deleteItem(Cart cart) throws DAOException { 96 | if(StringUtils.isEmpty(cart.getSku())){ 97 | deleteAll(cart); 98 | } 99 | if(!StringUtils.isEmpty(cart.getSku())){ 100 | getMapper().delete(cart); 101 | } 102 | } 103 | 104 | @Override 105 | public void deleteAll(Cart cart) throws DAOException { 106 | //IF SKU IS NOT PRESENT LIST ALL ITEM AND THEN DELETE THEM 107 | List cartCollection = getCartByLoginId(cart.getLoginId()); 108 | for(Cart cct : cartCollection){ 109 | Cart ct = new Cart(); 110 | ct.setLoginId(cct.getLoginId()); 111 | ct.setSku(cct.getSku()); 112 | getMapper().delete(ct); 113 | } 114 | 115 | 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/model/cart/ReadCartResponse.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.model.cart; 2 | 3 | 4 | public class ReadCartResponse { 5 | 6 | private Object cart = new Object(); 7 | private String code; 8 | private String message; 9 | private String loginId; 10 | 11 | 12 | 13 | /** 14 | * @return the cart 15 | */ 16 | public Object getCart() { 17 | return cart; 18 | } 19 | /** 20 | * @param cart the cart to set 21 | */ 22 | public void setCart(Object cart) { 23 | this.cart = cart; 24 | } 25 | /** 26 | * @return the loginId 27 | */ 28 | public String getLoginId() { 29 | return loginId; 30 | } 31 | /** 32 | * @param loginId the loginId to set 33 | */ 34 | public void setLoginId(String loginId) { 35 | this.loginId = loginId; 36 | } 37 | /** 38 | * @return the code 39 | */ 40 | public String getCode() { 41 | return code; 42 | } 43 | /** 44 | * @param code the code to set 45 | */ 46 | public void setCode(String code) { 47 | this.code = code; 48 | } 49 | /** 50 | * @return the message 51 | */ 52 | public String getMessage() { 53 | return message; 54 | } 55 | /** 56 | * @param message the message to set 57 | */ 58 | public void setMessage(String message) { 59 | this.message = message; 60 | } 61 | 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/router/RequestRouter.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.router; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | import java.util.Map; 7 | 8 | import org.apache.commons.io.IOUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.context.ConfigurableApplicationContext; 12 | import org.springframework.context.support.ClassPathXmlApplicationContext; 13 | import org.springframework.util.ObjectUtils; 14 | import org.springframework.util.StringUtils; 15 | 16 | import com.amazonaws.services.lambda.runtime.Context; 17 | import com.amazonaws.services.lambda.runtime.LambdaLogger; 18 | import com.google.gson.Gson; 19 | import com.google.gson.JsonObject; 20 | import com.google.gson.JsonParser; 21 | import com.org.cart.action.Action; 22 | import com.org.cart.exception.BadRequestException; 23 | import com.org.cart.exception.DAOException; 24 | import com.org.cart.exception.InternalErrorException; 25 | import com.org.cart.model.LambdaRequest; 26 | 27 | public class RequestRouter { 28 | 29 | static final Logger LOGGER = LoggerFactory.getLogger(RequestRouter.class); 30 | 31 | private static final String ACTIONCLASS = "resourcePath"; 32 | 33 | 34 | /** 35 | * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the 36 | * "action" property to decide where to route the request. The "body" property of the incoming request is passed 37 | * to the DemoAction implementation as a request body. 38 | * 39 | * @param request The InputStream for the incoming event. This should contain an "action" and "body" properties. The 40 | * action property should contain the namespaced name of the class that should handle the invocation. 41 | * The class should implement the DemoAction interface. The body property should contain the full 42 | * request body for the action class. 43 | * @param response An OutputStream where the response returned by the action class is written 44 | * @param context The Lambda Context object 45 | * @throws BadRequestException This Exception is thrown whenever parameters are missing from the request or the action 46 | * class can't be found 47 | * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database 48 | * is not accessible 49 | */ 50 | public static void lambdaHandler(InputStream request, OutputStream response, Context context) throws BadRequestException, InternalErrorException,DAOException,Exception { 51 | //Initialize the context logger 52 | LambdaLogger logger = context.getLogger(); 53 | 54 | JsonParser parser = new JsonParser(); 55 | JsonObject inputObj; 56 | try { 57 | inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject(); 58 | } catch (Exception e) { 59 | logger.log("Error while reading request\n" + e.getMessage()); 60 | throw new InternalErrorException("Error while reading request\n"+e.getMessage()); 61 | } 62 | 63 | LOGGER.info("input obj {}",inputObj); 64 | 65 | 66 | //Validate InputStream Request 67 | validateServiceObject(inputObj); 68 | 69 | //LOAD THE CONTEXT PROPERTIES 70 | ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/*.xml"); 71 | 72 | String actionClass = getActionClass(applicationContext,inputObj); 73 | 74 | applicationContext.close(); 75 | 76 | Action action = null; 77 | 78 | try { 79 | action = Action.class.cast(Class.forName(actionClass).newInstance()); 80 | } catch (final InstantiationException e) { 81 | logger.log("Error while instantiating action class\n" + e.getMessage()); 82 | throw new InternalErrorException("Error while instantiating action class\n"+e.getMessage()); 83 | } catch (final IllegalAccessException e) { 84 | logger.log("Illegal access while instantiating action class\n" + e.getMessage()); 85 | throw new InternalErrorException("Illegal access while instantiating action class\n"+e.getMessage()); 86 | } catch (final ClassNotFoundException e) { 87 | logger.log("Action class could not be found\n" + e.getMessage()); 88 | throw new InternalErrorException("Action class could not be found\n"+e.getMessage()); 89 | } 90 | 91 | if (action == null) { 92 | logger.log("Action class is null"); 93 | throw new BadRequestException("Invalid action class"); 94 | } 95 | 96 | String json_string = new Gson().toJson(inputObj); 97 | LambdaRequest lambdaRequest = new Gson().fromJson(json_string, LambdaRequest.class); 98 | String output = action.handle(lambdaRequest, context);//action.handle(inputObj, context); 99 | 100 | try { 101 | IOUtils.write(output, response); 102 | } catch (final IOException e) { 103 | logger.log("Error while writing response\n" + e.getMessage()); 104 | throw new InternalErrorException(e.getMessage()); 105 | } 106 | } 107 | 108 | @SuppressWarnings("unchecked") 109 | private static String getActionClass(ConfigurableApplicationContext applicationContext, 110 | JsonObject inputObj) { 111 | 112 | Map beanMapping = (Map) applicationContext.getBean("apiMap"); 113 | String actionName = inputObj.get(ACTIONCLASS).getAsString(); 114 | String actionBean =""; 115 | for (Map.Entry beanMap : beanMapping.entrySet()) { 116 | if(actionName.contains(beanMap.getKey())) { 117 | actionBean = beanMap.getValue().toString(); 118 | break; 119 | } 120 | } 121 | 122 | return actionBean; 123 | 124 | } 125 | private static void validateServiceObject(JsonObject inputObj) throws BadRequestException { 126 | if(ObjectUtils.isEmpty(inputObj) || StringUtils.isEmpty(inputObj.get(ACTIONCLASS))){ 127 | throw new BadRequestException("Could not find "+ACTIONCLASS+" key in request"); 128 | } 129 | 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/utils/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.GregorianCalendar; 8 | 9 | import javax.xml.bind.DatatypeConverter; 10 | import javax.xml.datatype.DatatypeFactory; 11 | import javax.xml.datatype.XMLGregorianCalendar; 12 | 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import com.org.cart.model.DateObj; 17 | 18 | public class DateUtils { 19 | private static final Logger LOGGER = LoggerFactory.getLogger(DateUtils.class); 20 | 21 | private static final String DATEFORMAT="MM-dd-yyyy hh:mm:ss"; 22 | private static final String DATEFORMATNEW="MMddyyyy"; 23 | 24 | DateUtils () { 25 | //NOOP private constructor 26 | } 27 | 28 | public static Date createDate(Date date) { 29 | 30 | if(date==null) { 31 | return null; 32 | } 33 | 34 | return new Date(date.getTime()); 35 | } 36 | 37 | public static Date parseDate(String s) { 38 | return DatatypeConverter.parseDate(s).getTime(); 39 | } 40 | 41 | public static String printDate(Date dt) { 42 | Calendar cal = new GregorianCalendar(); 43 | cal.setTime(dt); 44 | return DatatypeConverter.printDate(cal); 45 | } 46 | 47 | public static Date toDate(XMLGregorianCalendar xmlDate) { 48 | if(xmlDate==null) { 49 | return null; 50 | } 51 | 52 | return xmlDate.toGregorianCalendar().getTime(); 53 | } 54 | 55 | public static XMLGregorianCalendar toXmlDate(Date date) { 56 | try { 57 | GregorianCalendar c = new GregorianCalendar(); 58 | c.setTime(date); 59 | return DatatypeFactory.newInstance().newXMLGregorianCalendar(c); 60 | } catch (Exception e) { 61 | LOGGER.warn("Error converting date to xml : {}", e.getMessage(), e); 62 | return null; 63 | } 64 | } 65 | 66 | public static long daysBetween(Calendar startDate, Calendar endDate) { 67 | Calendar date = (Calendar) startDate.clone(); 68 | long daysBetween = 0; 69 | while (date.before(endDate)) { 70 | date.add(Calendar.DAY_OF_MONTH, 1); 71 | daysBetween++; 72 | } 73 | return daysBetween; 74 | } 75 | 76 | public static Calendar dateToCalendar(Date date){ 77 | Calendar cal = Calendar.getInstance(); 78 | cal.setTime(date); 79 | return cal; 80 | } 81 | 82 | public static Date stringToDate(String str){ 83 | SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT); 84 | try { 85 | Date date = sdf.parse(str); 86 | return date; 87 | } catch (ParseException e) { 88 | LOGGER.warn("Error in parsing Date : {} ",e.getMessage(),e); 89 | return null; 90 | } 91 | } 92 | 93 | public static boolean isSameDate(String start, String end){ 94 | SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMATNEW); 95 | return dateFormat.format(stringToDate(start)).equals(dateFormat.format(stringToDate(end))); 96 | 97 | } 98 | 99 | public static boolean isSameDate(String start, Date end){ 100 | SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMATNEW); 101 | return dateFormat.format(stringToDate(start)).equals(dateFormat.format(end)); 102 | 103 | } 104 | 105 | public static Calendar addNumberDays(Calendar startDate,int number){ 106 | Calendar date = (Calendar) startDate.clone(); 107 | date.add(Calendar.DATE, number); 108 | return date; 109 | } 110 | 111 | public static String getStringDate(Date dt){ 112 | String returnDate = ""; 113 | SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); 114 | returnDate = sdf.format(dt); 115 | 116 | return returnDate; 117 | } 118 | 119 | public static DateObj dateDifference(String dateStart, String dateStop){ 120 | 121 | //HH converts hour in 24 hours format (0-23), day calculation 122 | SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); 123 | 124 | Date d1 = null; 125 | Date d2 = null; 126 | 127 | DateObj dtObj = new DateObj(); 128 | 129 | try { 130 | 131 | d1 = format.parse(dateStart); 132 | d2 = format.parse(dateStop); 133 | 134 | //in milliseconds 135 | long diff = d2.getTime() - d1.getTime(); 136 | 137 | long diffSeconds = diff / 1000 % 60; 138 | long diffMinutes = diff / (60 * 1000) % 60; 139 | long diffHours = diff / (60 * 60 * 1000) % 24; 140 | long diffDays = diff / (24 * 60 * 60 * 1000); 141 | 142 | dtObj.setDays(diffDays); 143 | dtObj.setHours(diffHours); 144 | dtObj.setMinutes(diffMinutes); 145 | dtObj.setSeconds(diffSeconds); 146 | 147 | } catch (Exception e) { 148 | LOGGER.warn("error warning",e); 149 | } 150 | 151 | return dtObj; 152 | } 153 | 154 | 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/utils/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import java.util.Map; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | 11 | public class JsonUtils { 12 | 13 | private static final ObjectMapper OBJECTMAPPER = new ObjectMapper(); 14 | private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class); 15 | 16 | private static ObjectMapper objectMapper = new ObjectMapper(); 17 | 18 | private JsonUtils(){ 19 | 20 | } 21 | public static String toJsonString(Object object) { 22 | try { 23 | if(object==null) { 24 | return null; 25 | } 26 | 27 | return OBJECTMAPPER.writeValueAsString(object); 28 | 29 | } catch (Exception e) { 30 | LOGGER .warn(e.getMessage(), e); 31 | return null; 32 | 33 | } 34 | } 35 | 36 | 37 | public static String toJsonStringNonNull(Object object) { 38 | try { 39 | if(object==null) { 40 | return null; 41 | } 42 | 43 | OBJECTMAPPER.setSerializationInclusion(Include.NON_NULL); 44 | return OBJECTMAPPER.writeValueAsString(object); 45 | 46 | } catch (Exception e) { 47 | LOGGER .warn(e.getMessage(), e); 48 | return null; 49 | } 50 | } 51 | 52 | 53 | @SuppressWarnings({ "unchecked" }) 54 | public static Map getMapObject(Object object) { 55 | try { 56 | return objectMapper.readValue(JsonUtils.toJsonString(object), Map.class); 57 | }catch(Exception e){ 58 | LOGGER.warn("getMapObject Exception{}",e); 59 | LOGGER.warn(String.format("Exception with Map Object", object)); 60 | return null; 61 | } 62 | 63 | 64 | } 65 | 66 | 67 | @SuppressWarnings({ "unchecked" }) 68 | public static Map getMapObjectFromString(String str) { 69 | try { 70 | return objectMapper.readValue(str, Map.class); 71 | }catch(Exception e){ 72 | LOGGER.warn("{}",e); 73 | return null; 74 | } 75 | 76 | 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/org/cart/utils/Utils.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import com.google.gson.JsonObject; 7 | 8 | public class Utils { 9 | 10 | private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class); 11 | 12 | 13 | Utils(){ 14 | 15 | } 16 | 17 | public static JsonObject getJsonObject(JsonObject inputObj,String key){ 18 | JsonObject response = null; 19 | if (inputObj.get(key) != null) { 20 | response = inputObj.get(key).getAsJsonObject(); 21 | } 22 | return response; 23 | } 24 | 25 | public static String getStringObject(JsonObject inputObj,String key){ 26 | String response = null; 27 | if (inputObj.get(key) != null) { 28 | response = inputObj.get(key).getAsString(); 29 | } 30 | return response; 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/resources/spring/app-bean-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/resources/spring/properties-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/test/java/com/org/cart/action/ReadCartActionTest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.action; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | import static org.mockito.Matchers.anyString; 5 | import static org.mockito.Mockito.mock; 6 | import static org.mockito.Mockito.when; 7 | 8 | import java.util.ArrayList; 9 | 10 | import org.junit.After; 11 | import org.junit.Before; 12 | import org.junit.Ignore; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.test.context.ContextConfiguration; 18 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 19 | 20 | import com.amazonaws.services.lambda.runtime.Context; 21 | import com.google.gson.JsonObject; 22 | import com.org.cart.action.ReadCartAction; 23 | import com.org.cart.exception.BadRequestException; 24 | import com.org.cart.exception.DAOException; 25 | import com.org.cart.model.LambdaRequest; 26 | import com.org.cart.model.cart.Cart; 27 | import com.org.cart.model.cart.CartDAO; 28 | @RunWith(SpringJUnit4ClassRunner.class) 29 | @ContextConfiguration(locations={"classpath*:spring/responses-context.xml"}) 30 | public class ReadCartActionTest { 31 | 32 | static final Logger LOGGER = LoggerFactory.getLogger(ReadCartActionTest.class); 33 | 34 | private ReadCartAction readCartAction; 35 | 36 | private LambdaRequest lambdaRequest; 37 | 38 | private Context context; 39 | 40 | private CartDAO cartDao; 41 | 42 | @Before 43 | public void setUp() throws Exception { 44 | 45 | readCartAction = new ReadCartAction(); 46 | cartDao = mock(CartDAO.class); 47 | context = mock(Context.class); 48 | lambdaRequest = new LambdaRequest(); 49 | 50 | //cartDao = DAOFactory.getCartDAO(); 51 | 52 | //ReflectionTestUtils.setField(readCartAction, "cartDao", cartDao ); 53 | 54 | } 55 | 56 | @After 57 | public void tearDown() throws Exception { 58 | } 59 | 60 | @Test(expected = BadRequestException.class) 61 | public void testNoQuery() throws BadRequestException { 62 | readCartAction.handle(lambdaRequest, context); 63 | } 64 | 65 | @Test(expected = BadRequestException.class) 66 | public void testNoLoginId() throws BadRequestException { 67 | JsonObject queryObject = new JsonObject(); 68 | queryObject.addProperty("name", " test"); 69 | lambdaRequest.setQuery(queryObject); 70 | LOGGER.info("query {}",lambdaRequest.getQuery()); 71 | readCartAction.handle(lambdaRequest, context); 72 | } 73 | 74 | @Test(expected = BadRequestException.class) 75 | public void testEmptyLoginId() throws BadRequestException { 76 | JsonObject queryObject = new JsonObject(); 77 | queryObject.addProperty("loginId", ""); 78 | 79 | lambdaRequest.setQuery(queryObject); 80 | readCartAction.handle(lambdaRequest, context); 81 | } 82 | 83 | @Test 84 | @Ignore 85 | public void testWithLoginId() throws BadRequestException, DAOException { 86 | JsonObject queryObject = new JsonObject(); 87 | queryObject.addProperty("loginId", " test"); 88 | 89 | lambdaRequest.setQuery(queryObject); 90 | when(cartDao.getCartByLoginId(anyString())).thenReturn(new ArrayList()); 91 | String response = readCartAction.handle(lambdaRequest, context); 92 | assertNotNull(response); 93 | } 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/test/java/com/org/cart/router/RequestRouterTest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.router; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import com.org.cart.router.RequestRouter; 8 | 9 | public class RequestRouterTest { 10 | 11 | private RequestRouter requestRouter; 12 | 13 | @Before 14 | public void setUp() throws Exception { 15 | 16 | requestRouter = new RequestRouter(); 17 | 18 | } 19 | 20 | @After 21 | public void tearDown() throws Exception { 22 | } 23 | 24 | @Test 25 | public void test() { 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/org/cart/utils/DateUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertFalse; 5 | import static org.junit.Assert.assertNotNull; 6 | import static org.junit.Assert.assertNull; 7 | import static org.junit.Assert.assertTrue; 8 | 9 | import java.util.Date; 10 | 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import com.org.cart.model.DateObj; 17 | import com.org.cart.utils.DateUtils; 18 | 19 | 20 | 21 | 22 | 23 | public class DateUtilsTest { 24 | 25 | private static final Logger LOGGER = LoggerFactory.getLogger(DateUtilsTest.class); 26 | 27 | private static final String strDate = "02-01-2015 00:00:00"; 28 | private static final String strDate1 = "02-01-2015 06:66:12"; 29 | private static final String endDate = "02-10-2015 00:00:00"; 30 | private static final String strDateException = "02-01/2015 00:00:00"; 31 | 32 | private DateUtils dateUtils; 33 | @Before 34 | public void setUp() throws Exception { 35 | 36 | dateUtils = new DateUtils(); 37 | } 38 | 39 | @Test 40 | public void testCreateDate() { 41 | 42 | assertNull(DateUtils.createDate(null)); 43 | assertNotNull(DateUtils.createDate(new Date())); 44 | assertNotNull(DateUtils.createDate(new Date(1879829718))); 45 | } 46 | 47 | @Test 48 | public void testParseDate(){ 49 | String s = "1426705867000"; 50 | LOGGER.info("{}",DateUtils.parseDate(s)); 51 | assertNotNull(DateUtils.parseDate(s)); 52 | assertNotNull(DateUtils.printDate(DateUtils.createDate(new Date(1879829718)))); 53 | } 54 | @Test 55 | public void testToXmlDate(){ 56 | assertNotNull(DateUtils.toXmlDate(DateUtils.createDate(new Date(1879829718)))); 57 | assertNull(DateUtils.toXmlDate(null)); 58 | } 59 | @Test 60 | public void testToDate(){ 61 | assertNotNull(DateUtils.toDate(DateUtils.toXmlDate(DateUtils.createDate(new Date(1879829718))))); 62 | assertNull(DateUtils.toDate(null)); 63 | } 64 | 65 | @Test 66 | public void testDateToCalendar(){ 67 | assertNotNull(DateUtils.dateToCalendar(DateUtils.stringToDate(strDate))); 68 | } 69 | 70 | @Test 71 | public void testStringtoDate(){ 72 | assertNotNull(DateUtils.stringToDate(strDate)); 73 | } 74 | 75 | @Test 76 | public void testStringtoDateException(){ 77 | assertNull(DateUtils.stringToDate(strDateException)); 78 | } 79 | 80 | @Test 81 | public void testDaysBetween(){ 82 | assertEquals(9,DateUtils.daysBetween(DateUtils.dateToCalendar(DateUtils.stringToDate(strDate)), DateUtils.dateToCalendar(DateUtils.stringToDate(endDate)))); 83 | assertEquals(0,DateUtils.daysBetween(DateUtils.dateToCalendar(DateUtils.stringToDate(endDate)), DateUtils.dateToCalendar(DateUtils.stringToDate(strDate)))); 84 | } 85 | 86 | @Test 87 | public void testSameDate(){ 88 | assertTrue(DateUtils.isSameDate(strDate, strDate1)); 89 | assertFalse(DateUtils.isSameDate(strDate, endDate)); 90 | assertTrue(DateUtils.isSameDate(strDate, DateUtils.stringToDate(strDate))); 91 | assertFalse(DateUtils.isSameDate(strDate, DateUtils.stringToDate(endDate))); 92 | } 93 | 94 | @Test 95 | public void testNumberofDays(){ 96 | LOGGER.info(" {}",DateUtils.addNumberDays(DateUtils.dateToCalendar(DateUtils.stringToDate(strDate)), 0)); 97 | } 98 | 99 | @Test 100 | public void testgetStringDate(){ 101 | 102 | LOGGER.info(" {}",DateUtils.getStringDate(DateUtils.stringToDate(strDate))); 103 | } 104 | 105 | @Test 106 | public void testdateDifference(){ 107 | DateObj dtObj = DateUtils.dateDifference(DateUtils.getStringDate(DateUtils.stringToDate(strDate)), DateUtils.getStringDate(DateUtils.stringToDate(strDate1))); 108 | assertEquals("7",Long.toString(dtObj.getHours())); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/test/java/com/org/cart/utils/JsonUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | import static org.junit.Assert.assertNull; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import com.org.cart.utils.JsonUtils; 14 | 15 | public class JsonUtilsTest { 16 | 17 | 18 | private final Object obj = "{\"test\":\"tt\"}"; 19 | 20 | @Before 21 | public void setUp() throws Exception { 22 | 23 | } 24 | 25 | @After 26 | public void tearDown() throws Exception { 27 | } 28 | 29 | @Test 30 | public void test() { 31 | assertNotNull(JsonUtils.toJsonString(obj)); 32 | } 33 | 34 | @Test 35 | public void testNotNull() { 36 | assertNotNull(JsonUtils.toJsonStringNonNull(obj)); 37 | } 38 | 39 | @Test 40 | public void testNull() { 41 | assertNull(JsonUtils.toJsonString(null)); 42 | } 43 | 44 | @Test 45 | public void testNullMapObj() { 46 | assertNull(JsonUtils.getMapObject(null)); 47 | } 48 | 49 | @Test 50 | public void testMapObj() { 51 | Map mapObj = new HashMap(); 52 | mapObj.put("ff", "ff"); 53 | assertNotNull(JsonUtils.getMapObject(mapObj )); 54 | } 55 | 56 | @Test 57 | public void testMapObjFromString() { 58 | String test = "{\"complete\":\"test\"}"; 59 | assertNotNull(JsonUtils.getMapObjectFromString(test )); 60 | } 61 | @Test 62 | public void testMapObjFromStringNull() { 63 | String test = "test"; 64 | assertNull(JsonUtils.getMapObjectFromString(test )); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/org/cart/utils/UtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.org.cart.utils; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import com.org.cart.utils.Utils; 8 | public class UtilsTest { 9 | 10 | private Utils utils; 11 | 12 | private static final String url ="https://startcheckout.aol.com/"; 13 | private static final String urlWith ="https://startcheckout.aol.com/?ncid=1234"; 14 | private static final String urlWithMboxPc ="https://startcheckout.aol.com/?ncid=1234&mboxPC=3445"; 15 | private static final String urlWithMboxSession ="https://startcheckout.aol.com/?ncid=1234&mboxSession=3445"; 16 | 17 | @Before 18 | public void setUp() throws Exception { 19 | utils = new Utils(); 20 | 21 | } 22 | 23 | @After 24 | public void tearDown() throws Exception { 25 | } 26 | 27 | @Test 28 | public void test() { 29 | utils = new Utils(); 30 | } 31 | 32 | 33 | } 34 | --------------------------------------------------------------------------------