From 5d267abf30403c317a143d673d9a7f80f4e583b4 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Mon, 10 Jul 2023 18:18:11 +0530 Subject: [PATCH 01/24] Add initial structure for ballerina rest-social-media service --- rest-social-media/ballerina/Ballerina.toml | 8 + rest-social-media/ballerina/Cloud.toml | 8 + rest-social-media/ballerina/Config.toml | 10 ++ .../ballerina/resources/db/init.sql | 27 +++ .../ballerina/response_error_interceptor.bal | 50 ++++++ rest-social-media/ballerina/sentiment.bal | 26 +++ .../ballerina/social_media_service.bal | 162 ++++++++++++++++++ .../ballerina/social_media_service_desc.bal | 76 ++++++++ 8 files changed, 367 insertions(+) create mode 100644 rest-social-media/ballerina/Ballerina.toml create mode 100644 rest-social-media/ballerina/Cloud.toml create mode 100644 rest-social-media/ballerina/Config.toml create mode 100644 rest-social-media/ballerina/resources/db/init.sql create mode 100644 rest-social-media/ballerina/response_error_interceptor.bal create mode 100644 rest-social-media/ballerina/sentiment.bal create mode 100644 rest-social-media/ballerina/social_media_service.bal create mode 100644 rest-social-media/ballerina/social_media_service_desc.bal diff --git a/rest-social-media/ballerina/Ballerina.toml b/rest-social-media/ballerina/Ballerina.toml new file mode 100644 index 0000000..735d0ef --- /dev/null +++ b/rest-social-media/ballerina/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "integration_samples" +name = "ballerina_social_media" +version = "0.0.1" +distribution = "2201.7.0" + +[build-options] +observabilityIncluded = true diff --git a/rest-social-media/ballerina/Cloud.toml b/rest-social-media/ballerina/Cloud.toml new file mode 100644 index 0000000..42ab7a2 --- /dev/null +++ b/rest-social-media/ballerina/Cloud.toml @@ -0,0 +1,8 @@ +[container.image] +repository="integrationsamples" +name="ballerina-social-media" +tag="0.0.1" + +[[container.copy.files]] +sourceFile="./Config.toml" +target="./Config.toml" diff --git a/rest-social-media/ballerina/Config.toml b/rest-social-media/ballerina/Config.toml new file mode 100644 index 0000000..51e07ce --- /dev/null +++ b/rest-social-media/ballerina/Config.toml @@ -0,0 +1,10 @@ +moderate = true + +[databaseConfig] +database_user = "social_media_user" +database_password = "dummypassword" +host = "localhost" +port = 3306 + +[ballerina.observe] +tracingEnabled=true diff --git a/rest-social-media/ballerina/resources/db/init.sql b/rest-social-media/ballerina/resources/db/init.sql new file mode 100644 index 0000000..0019f8e --- /dev/null +++ b/rest-social-media/ballerina/resources/db/init.sql @@ -0,0 +1,27 @@ +CREATE TABLE USER_DETAILS(ID IDENTITY PRIMARY KEY, BIRTH_DATE DATE, NAME VARCHAR(255)); +CREATE TABLE POST(ID IDENTITY PRIMARY KEY, DESCRIPTION VARCHAR(255), USER_ID BIGINT); + +ALTER TABLE POST +ADD FOREIGN KEY (USER_ID) +REFERENCES USER_DETAILS(ID) ON DELETE CASCADE; + +insert into user_details(birth_date, name) +values(current_date(), 'Ranga'); + +insert into user_details(birth_date, name) +values(current_date(), 'Ravi'); + +insert into user_details(birth_date, name) +values(current_date(), 'Sathish'); + +insert into post(description, user_id) +values('I want to learn AWS', 1); + +insert into post(description, user_id) +values('I want to learn DevOps', 1); + +insert into post(description, user_id) +values('I want to learn GCP', 2); + +insert into post(description, user_id) +values('I want to learn multi cloud', 3); diff --git a/rest-social-media/ballerina/response_error_interceptor.bal b/rest-social-media/ballerina/response_error_interceptor.bal new file mode 100644 index 0000000..10a7a13 --- /dev/null +++ b/rest-social-media/ballerina/response_error_interceptor.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/http; +import ballerina/constraint; + +// Handle listener errors +service class ResponseErrorInterceptor { + *http:ResponseErrorInterceptor; + + remote function interceptResponseError(http:RequestContext ctx, error err) + returns SocialMediaBadReqeust|SocialMediaServerError { + ErrorDetails errorDetails = buildErrorPayload(err.message(), ""); + + if err is constraint:Error { + SocialMediaBadReqeust socialMediaBadRequest = { + body: errorDetails + }; + return socialMediaBadRequest; + } else { + SocialMediaServerError socialMediaServerError = { + body: errorDetails + }; + return socialMediaServerError; + } + } +} + +type SocialMediaBadReqeust record {| + *http:BadRequest; + ErrorDetails body; +|}; + +type SocialMediaServerError record {| + *http:InternalServerError; + ErrorDetails body; +|}; diff --git a/rest-social-media/ballerina/sentiment.bal b/rest-social-media/ballerina/sentiment.bal new file mode 100644 index 0000000..6931a79 --- /dev/null +++ b/rest-social-media/ballerina/sentiment.bal @@ -0,0 +1,26 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +type Probability record { + decimal neg; + decimal neutral; + decimal pos; +}; + +type Sentiment record { + Probability probability; + string label; +}; diff --git a/rest-social-media/ballerina/social_media_service.bal b/rest-social-media/ballerina/social_media_service.bal new file mode 100644 index 0000000..5246139 --- /dev/null +++ b/rest-social-media/ballerina/social_media_service.bal @@ -0,0 +1,162 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/http; +import ballerina/sql; +import ballerina/mime; +import ballerinax/mysql.driver as _; +import ballerinax/mysql; +import ballerina/log; +import ballerina/time; + +configurable boolean moderate = ?; + +type DataBaseConfig record {| + string host; + int port; + string user; + string password; + string database; +|}; +configurable DataBaseConfig databaseConfig = ?; + +listener http:Listener socialMediaListener = new (9090, + interceptors = [new ResponseErrorInterceptor()] +); + +service SocialMedia /social\-media on socialMediaListener { + + final mysql:Client socialMediaDb; + final http:Client sentimentEndpoint; + + public function init() returns error? { + self.socialMediaDb = check new (...databaseConfig); + self.sentimentEndpoint = check new("localhost:9099", + retryConfig = { + interval: 3 + } + ); + log:printInfo("Social media service started"); + } + + # Get all the users + # + # + return - The list of users or error message + resource function get users() returns User[]|error { + stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.user_details`); + return from User user in userStream + select user; + } + + # Get a specific user + # + # + id - The user ID of the user to be retrived + # + return - A specific user or error message + resource function get users/[int id]() returns User|UserNotFound|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE ID = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } else { + return result; + } + } + + # Create a new user + # + # + newUser - The user details of the new user + # + return - The created message or error message + resource function post users(@http:Payload NewUser newUser) returns http:Created|error { + _ = check self.socialMediaDb->execute(` + INSERT INTO social_media_database.user_details(birth_date, name) + VALUES (${newUser.birthDate}, ${newUser.name});`); + return http:CREATED; + } + + # Delete a user + # + # + id - The user ID of the user to be deleted + # + return - The success message or error message + resource function delete users/[int id]() returns http:NoContent|error { + _ = check self.socialMediaDb->execute(` + DELETE FROM social_media_database.user_details WHERE id = ${id};`); + return http:NO_CONTENT; + } + + # Get posts for a give user + # + # + id - The user ID for which posts are retrieved + # + return - A list of posts or error message + resource function get users/[int id]/posts() returns Post[]|UserNotFound|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE id = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } + + stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.post WHERE user_id = ${id}`); + Post[]|error posts = from Post post in postStream + select post; + return posts; + } + + # Create a post for a given user + # + # + id - The user ID for which the post is created + # + return - The created message or error message + resource function post users/[int id]/posts(@http:Payload NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE id = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } + + Sentiment sentiment = check self.sentimentEndpoint->/text\-processing/api/sentiment.post( + { text: newPost }, + mediatype = mime:APPLICATION_FORM_URLENCODED + ); + if sentiment.label == "neg" { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + PostForbidden postForbidden = { + body: errorDetails + }; + return postForbidden; + } + + _ = check self.socialMediaDb->execute(` + INSERT INTO social_media_database.post(description, user_id) + VALUES (${newPost.description}, ${id});`); + return http:CREATED; + } +} + +function buildErrorPayload(string msg, string path) returns ErrorDetails { + ErrorDetails errorDetails = { + message: msg, + timeStamp: time:utcNow(), + details: string `uri=${path}` + }; + return errorDetails; +} diff --git a/rest-social-media/ballerina/social_media_service_desc.bal b/rest-social-media/ballerina/social_media_service_desc.bal new file mode 100644 index 0000000..fd0acc5 --- /dev/null +++ b/rest-social-media/ballerina/social_media_service_desc.bal @@ -0,0 +1,76 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import ballerina/constraint; +import ballerina/http; +import ballerina/sql; +import ballerina/time; + +type SocialMedia service object { + *http:Service; + + // users resource + resource function get users() returns User[]|error; + resource function get users/[int id]() returns User|UserNotFound|error; + resource function post users(NewUser newUser) returns http:Created|error; + resource function delete users/[int id]() returns http:NoContent|error; + + // posts resource + resource function get users/[int id]/posts() returns Post[]|UserNotFound|error; + resource function post users/[int id]/posts(NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error; +}; + +// user representations +type User record {| + int id; + string name; + @sql:Column {name: "birth_date"} + time:Date birthDate; +|}; + +public type NewUser record {| + @constraint:String { + minLength: 2 + } + string name; + time:Date birthDate; +|}; + +type UserNotFound record {| + *http:NotFound; + ErrorDetails body; +|}; + +// post representations +type Post record {| + int id; + string description; +|}; + +public type NewPost record {| + string description; +|}; + +type PostForbidden record {| + *http:Forbidden; + ErrorDetails body; +|}; + +type ErrorDetails record {| + time:Utc timeStamp; + string message; + string details; +|}; From 8a2b6744cb5ebd79067832c41ce4edf7fa013dd6 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Mon, 10 Jul 2023 19:53:41 +0530 Subject: [PATCH 02/24] Add spring-boot social-media service --- rest-social-media/springboot/mvnw | 308 ++++++++++++++++++ rest-social-media/springboot/mvnw.cmd | 205 ++++++++++++ rest-social-media/springboot/pom.xml | 95 ++++++ .../socialmedia/SocialMediaApplication.java | 13 + .../controller/SocialMediaController.java | 167 ++++++++++ .../exception/AppExceptionalHandler.java | 36 ++ .../socialmedia/exception/ErrorDetails.java | 28 ++ .../exception/NegativeSentimentException.java | 8 + .../exception/UserNotFoundException.java | 8 + .../springboot/socialmedia/model/Post.java | 47 +++ .../springboot/socialmedia/model/User.java | 71 ++++ .../repository/PostRepository.java | 7 + .../repository/UserRepository.java | 7 + .../socialmedia/sentiment/Probability.java | 31 ++ .../socialmedia/sentiment/Sentiment.java | 22 ++ .../socialmedia/sentiment/SentimentProxy.java | 16 + .../sentiment/SentimentRequest.java | 17 + .../src/main/resources/application.properties | 17 + .../springboot/src/main/resources/data.sql | 20 ++ .../SocialMediaApplicationTests.java | 13 + 20 files changed, 1136 insertions(+) create mode 100755 rest-social-media/springboot/mvnw create mode 100644 rest-social-media/springboot/mvnw.cmd create mode 100644 rest-social-media/springboot/pom.xml create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java create mode 100644 rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java create mode 100644 rest-social-media/springboot/src/main/resources/application.properties create mode 100644 rest-social-media/springboot/src/main/resources/data.sql create mode 100644 rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java diff --git a/rest-social-media/springboot/mvnw b/rest-social-media/springboot/mvnw new file mode 100755 index 0000000..66df285 --- /dev/null +++ b/rest-social-media/springboot/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/rest-social-media/springboot/mvnw.cmd b/rest-social-media/springboot/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/rest-social-media/springboot/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/rest-social-media/springboot/pom.xml b/rest-social-media/springboot/pom.xml new file mode 100644 index 0000000..3896968 --- /dev/null +++ b/rest-social-media/springboot/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.1 + + + + integration.samples.springboot + social-media + 0.0.1-SNAPSHOT + social-media + + Demo social media service using Spring Boot + + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + io.github.resilience4j + resilience4j-spring-boot2 + 2.1.0 + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.1.0 + + + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.0.3 + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + mysql + mysql-connector-java + 8.0.33 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + integrationsamples/springboot-${project.artifactId}:0.0.1 + + IF_NOT_PRESENT + + + + + diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java new file mode 100644 index 0000000..47cbf96 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.socialmedia; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SocialMediaApplication { + + public static void main(String[] args) { + SpringApplication.run(SocialMediaApplication.class, args); + } + +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java new file mode 100644 index 0000000..268af79 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java @@ -0,0 +1,167 @@ +package integration.samples.springboot.socialmedia.controller; + +import integration.samples.springboot.socialmedia.exception.ErrorDetails; +import integration.samples.springboot.socialmedia.exception.NegativeSentimentException; +import integration.samples.springboot.socialmedia.exception.UserNotFoundException; +import integration.samples.springboot.socialmedia.model.Post; +import integration.samples.springboot.socialmedia.model.User; +import integration.samples.springboot.socialmedia.repository.PostRepository; +import integration.samples.springboot.socialmedia.repository.UserRepository; +import integration.samples.springboot.socialmedia.sentiment.Sentiment; +import integration.samples.springboot.socialmedia.sentiment.SentimentProxy; +import integration.samples.springboot.socialmedia.sentiment.SentimentRequest; +import io.github.resilience4j.retry.annotation.Retry; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Optional; + +@RestController +public class SocialMediaController { + + private final UserRepository userRepository; + private final PostRepository postRepository; + private final SentimentProxy sentimentProxy; + + @Value("${sentiment.moderate}") + private boolean moderate; + + @Autowired + public SocialMediaController(UserRepository userRepository, + PostRepository postRepository, + SentimentProxy sentimentProxy) { + this.userRepository = userRepository; + this.postRepository = postRepository; + this.sentimentProxy = sentimentProxy; + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get users", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = User.class) + ) + ) + }) + }) + @GetMapping("/social-media/users") + public List retrieveAllUsers() { + return userRepository.findAll(); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = User.class) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/social-media/users/{id}") + public User retrieveUser(@PathVariable int id) { + Optional user = userRepository.findById(id); + + if (user.isEmpty()) + throw new UserNotFoundException("id: " + id); + + return user.get(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Create user", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = User.class))}), + @ApiResponse(responseCode = "400", description = "Bad request", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}) + }) + @PostMapping("/social-media/users") + public ResponseEntity createUser(@Valid @RequestBody User user) { + userRepository.save(user); + return ResponseEntity.created(null).build(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Delete user") + }) + @DeleteMapping("/social-media/users/{id}") + public void deleteUser(@PathVariable int id) { + userRepository.deleteById(id); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Create post", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = Post.class))}), + @ApiResponse(responseCode = "404", description = "User not found", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))})}) + @GetMapping("/social-media/users/{id}/posts") + public List retrieveUserPosts(@PathVariable int id) { + Optional user = userRepository.findById(id); + + if (user.isEmpty()) + throw new UserNotFoundException("id: " + id); + + return user.get().getPosts(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Create post", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = User.class))}), + @ApiResponse(responseCode = "403", description = "Negative sentiment detected", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}), + @ApiResponse(responseCode = "404", description = "User not found", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}) + }) + @PostMapping("/social-media/users/{id}/post") + @Retry(name = "sentiment-api") + public ResponseEntity createUserPost(@PathVariable int id, @Valid @RequestBody Post post) { + Optional user = userRepository.findById(id); + if (user.isEmpty()) { + throw new UserNotFoundException("id: " + id); + } + if (moderate) { + Sentiment sentiment = sentimentProxy.retrieveSentiment(new SentimentRequest(post.getDescription())); + if (sentiment.getLabel().equalsIgnoreCase("neg")) { + throw new NegativeSentimentException("Negative sentiment detected"); + } + } + post.setUser(user.get()); + postRepository.save(post); + return ResponseEntity.created(null).build(); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java new file mode 100644 index 0000000..fcdbe6d --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java @@ -0,0 +1,36 @@ +package integration.samples.springboot.socialmedia.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +@RestControllerAdvice +public class AppExceptionalHandler { + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + ErrorDetails handleAllException(Exception exception, WebRequest request) { + return new ErrorDetails(exception.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(UserNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + ErrorDetails handleUserNotFoundException(Exception userNotFound, WebRequest request) { + return new ErrorDetails(userNotFound.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(NegativeSentimentException.class) + @ResponseStatus(HttpStatus.FORBIDDEN) + ErrorDetails handleNegativeSentimentException(Exception negativeSentiment, WebRequest request) { + return new ErrorDetails(negativeSentiment.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ErrorDetails handleMethodArgumentNotValid(MethodArgumentNotValidException methodArgNotvalid, WebRequest request) { + return new ErrorDetails(methodArgNotvalid.getMessage(), request.getDescription(false)); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java new file mode 100644 index 0000000..cea6061 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java @@ -0,0 +1,28 @@ +package integration.samples.springboot.socialmedia.exception; + +import java.time.LocalDateTime; + +public class ErrorDetails { + + private LocalDateTime timeStamp; + private String message; + private String details; + + public ErrorDetails(String message, String details) { + this.timeStamp = LocalDateTime.now(); + this.message = message; + this.details = details; + } + + public LocalDateTime getTimeStamp() { + return timeStamp; + } + + public String getMessage() { + return message; + } + + public String getDetails() { + return details; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java new file mode 100644 index 0000000..9dcc0ef --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.socialmedia.exception; + +public class NegativeSentimentException extends RuntimeException { + + public NegativeSentimentException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java new file mode 100644 index 0000000..fce7f4a --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.socialmedia.exception; + +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java new file mode 100644 index 0000000..6f78bd1 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java @@ -0,0 +1,47 @@ +package integration.samples.springboot.socialmedia.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; + +@Entity +public class Post { + + @Id + @GeneratedValue + private int id; + + private String description; + + @ManyToOne(fetch = FetchType.LAZY) + @JsonIgnore + private User user; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + @Override + public String toString() { + return "Post{" + "id=" + id + ", description='" + description + '\'' + '}'; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java new file mode 100644 index 0000000..21c8d07 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java @@ -0,0 +1,71 @@ +package integration.samples.springboot.socialmedia.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.Size; + +import java.time.LocalDate; +import java.util.List; + +@Entity(name = "user_details") +public class User { + + @Id + @GeneratedValue + private int id; + @Size(min = 2, message = "Name should have at least two characters") + private String name; + + @Past(message = "Birthdate should be in the past") + private LocalDate birthDate; + + @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) + @JsonIgnore + private List posts; + + public User() {} + + public User(int id, String name, LocalDate birthDate) { + this.id = id; + this.name = name; + this.birthDate = birthDate; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + public List getPosts() { + return posts; + } + + public void setPosts(List posts) { + this.posts = posts; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name='" + name + '\'' + ", birthDate=" + birthDate + '}'; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java new file mode 100644 index 0000000..6fefcdd --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.socialmedia.repository; + +import integration.samples.springboot.socialmedia.model.Post; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java new file mode 100644 index 0000000..449a84e --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.socialmedia.repository; + +import integration.samples.springboot.socialmedia.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java new file mode 100644 index 0000000..feb0475 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java @@ -0,0 +1,31 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class Probability { + private double neg; + private double neutral; + private double pos; + + public double getNeg() { + return neg; + } + + public void setNeg(double neg) { + this.neg = neg; + } + + public double getNeutral() { + return neutral; + } + + public void setNeutral(double neutral) { + this.neutral = neutral; + } + + public double getPos() { + return pos; + } + + public void setPos(double pos) { + this.pos = pos; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java new file mode 100644 index 0000000..71bb114 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java @@ -0,0 +1,22 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class Sentiment { + private Probability probability; + private String label; + + public Probability getProbability() { + return probability; + } + + public void setProbability(Probability probability) { + this.probability = probability; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java new file mode 100644 index 0000000..6d56c4d --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java @@ -0,0 +1,16 @@ +package integration.samples.springboot.socialmedia.sentiment; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@FeignClient(name="sentiment-api", url="localhost:8088") +public interface SentimentProxy { + @RequestMapping( + method = RequestMethod.POST, + value = "/text-processing/api/sentiment", + consumes = "application/x-www-form-urlencoded" + ) + Sentiment retrieveSentiment(@RequestBody SentimentRequest sentimentRequest); +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java new file mode 100644 index 0000000..79b80fb --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java @@ -0,0 +1,17 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class SentimentRequest { + private String text; + + public SentimentRequest(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/rest-social-media/springboot/src/main/resources/application.properties b/rest-social-media/springboot/src/main/resources/application.properties new file mode 100644 index 0000000..95d9cb9 --- /dev/null +++ b/rest-social-media/springboot/src/main/resources/application.properties @@ -0,0 +1,17 @@ +server.port=8087 + +spring.datasource.url=jdbc:mysql://localhost:3306/social_media_database +spring.datasource.username=social_media_user +spring.datasource.password=dummypassword +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + +logging.pattern.level=trace_id=%mdc{traceId} span_id=%mdc{spanId} trace_flags=%mdc{traceFlags} %p + +spring.jpa.defer-datasource-initialization=true +spring.jpa.show-sql=true + +sentiment.moderate=true + +resilience4j.retry.instances.sentiment-api.maxRetryAttempts=3 +resilience4j.retry.instances.sentiment-api.waitDuration=5s diff --git a/rest-social-media/springboot/src/main/resources/data.sql b/rest-social-media/springboot/src/main/resources/data.sql new file mode 100644 index 0000000..eac075c --- /dev/null +++ b/rest-social-media/springboot/src/main/resources/data.sql @@ -0,0 +1,20 @@ +insert into user_details(id, birth_date, name) +values(1001, current_date(), 'Ranga'); + +insert into user_details(id, birth_date, name) +values(1002, current_date(), 'Ravi'); + +insert into user_details(id, birth_date, name) +values(1003, current_date(), 'Sathish'); + +insert into post(id, description, user_id) +values(2001, 'I want to learn AWS', 1001); + +insert into post(id, description, user_id) +values(2002, 'I want to learn DevOps', 1001); + +insert into post(id, description, user_id) +values(2003, 'I want to learn GCP', 1002); + +insert into post(id, description, user_id) +values(2004, 'I want to learn multi cloud', 1002); diff --git a/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java new file mode 100644 index 0000000..6598f8f --- /dev/null +++ b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.socialmedia; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SocialMediaApplicationTests { + + @Test + void contextLoads() { + } + +} From b1e5629738b20f53df9133a347e8659c0686e37b Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 11:36:21 +0530 Subject: [PATCH 03/24] Disable tests for time-being --- .../springboot/socialmedia/SocialMediaApplicationTests.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java index 6598f8f..8961567 100644 --- a/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java +++ b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java @@ -6,8 +6,8 @@ @SpringBootTest class SocialMediaApplicationTests { - @Test - void contextLoads() { - } + // @Test + // void contextLoads() { + // } } From eda8dd05fb996c63eb649bee215c8e8a938c310b Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 11:36:50 +0530 Subject: [PATCH 04/24] Add spring-boot-reactive social-media service --- rest-social-media/springboot-reactive/mvnw | 308 ++++++++++++++++++ .../springboot-reactive/mvnw.cmd | 205 ++++++++++++ rest-social-media/springboot-reactive/pom.xml | 77 +++++ .../socialmedia/SocialMediaApplication.java | 13 + .../controller/SocialMediaController.java | 213 ++++++++++++ .../exception/AppExceptionalHandler.java | 39 +++ .../socialmedia/exception/ErrorDetails.java | 28 ++ .../exception/NegativeSentimentException.java | 7 + .../exception/UserNotFoundException.java | 7 + .../reactive/socialmedia/model/Post.java | 35 ++ .../reactive/socialmedia/model/User.java | 51 +++ .../repository/PostRepository.java | 10 + .../repository/UserRepository.java | 15 + .../repository/impl/PostRepositoryImpl.java | 52 +++ .../repository/impl/UserRepositoryImpl.java | 69 ++++ .../socialmedia/sentiment/Probability.java | 31 ++ .../socialmedia/sentiment/Sentiment.java | 22 ++ .../sentiment/SentimentAnalysisClient.java | 8 + .../SentimentAnalysisClientImpl.java | 28 ++ .../src/main/resources/application.properties | 8 + .../SocialMediaApplicationTests.java | 13 + 21 files changed, 1239 insertions(+) create mode 100755 rest-social-media/springboot-reactive/mvnw create mode 100644 rest-social-media/springboot-reactive/mvnw.cmd create mode 100644 rest-social-media/springboot-reactive/pom.xml create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java create mode 100644 rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java create mode 100644 rest-social-media/springboot-reactive/src/main/resources/application.properties create mode 100644 rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java diff --git a/rest-social-media/springboot-reactive/mvnw b/rest-social-media/springboot-reactive/mvnw new file mode 100755 index 0000000..66df285 --- /dev/null +++ b/rest-social-media/springboot-reactive/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/rest-social-media/springboot-reactive/mvnw.cmd b/rest-social-media/springboot-reactive/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/rest-social-media/springboot-reactive/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/rest-social-media/springboot-reactive/pom.xml b/rest-social-media/springboot-reactive/pom.xml new file mode 100644 index 0000000..ed2a0f9 --- /dev/null +++ b/rest-social-media/springboot-reactive/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.1 + + + + integration.samples.springboot.reactive + social-media + 0.0.1-SNAPSHOT + social-media + Demo social media service using Spring Boot + + + 17 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springdoc + springdoc-openapi-webflux-ui + 1.7.0 + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-data-r2dbc + + + io.asyncer + r2dbc-mysql + 1.0.2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + integrationsamples/springboot-reactive-${project.artifactId}:0.0.1 + + IF_NOT_PRESENT + + + + + diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java new file mode 100644 index 0000000..8c1d3af --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.reactive.socialmedia; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SocialMediaApplication { + + public static void main(String[] args) { + SpringApplication.run(SocialMediaApplication.class, args); + } + +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java new file mode 100644 index 0000000..1261968 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java @@ -0,0 +1,213 @@ +package integration.samples.springboot.reactive.socialmedia.controller; + +import integration.samples.springboot.reactive.socialmedia.exception.ErrorDetails; +import integration.samples.springboot.reactive.socialmedia.exception.NegativeSentimentException; +import integration.samples.springboot.reactive.socialmedia.exception.UserNotFoundException; +import integration.samples.springboot.reactive.socialmedia.model.Post; +import integration.samples.springboot.reactive.socialmedia.model.User; +import integration.samples.springboot.reactive.socialmedia.repository.PostRepository; +import integration.samples.springboot.reactive.socialmedia.repository.UserRepository; +import integration.samples.springboot.reactive.socialmedia.sentiment.SentimentAnalysisClient; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +@RestController +@RequestMapping("/social-media/users") +public class SocialMediaController { + private final UserRepository userRepository; + private final PostRepository postRepository; + private final SentimentAnalysisClient sentimentAnalysisClient; + + @Value("${sentiment.moderate}") + private boolean moderate; + + @Autowired + public SocialMediaController(UserRepository userRepository, PostRepository postRepository, + SentimentAnalysisClient sentimentAnalysisClient) { + this.userRepository = userRepository; + this.postRepository = postRepository; + this.sentimentAnalysisClient = sentimentAnalysisClient; + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get users", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = User.class) + ) + ) + }) + }) + @GetMapping + public Flux retrieveAllUsers() { + return userRepository.findAll(); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = User.class) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/{id}") + public Mono retrieveUser(@PathVariable long id) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", + description = "Create user", + content = { + @Content( + mediaType = "application/json" + ) + }), + @ApiResponse( + responseCode = "400", + description = "Bad request", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @PostMapping + public Mono> createUser(@Valid @RequestBody User user) { + return userRepository + .save(user) + .map(savedUser -> ResponseEntity.created(null).build()); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Delete user") + }) + @DeleteMapping("/{id}") + public Mono> deleteUser(@PathVariable long id) { + return userRepository + .deleteById(id) + .map(v -> ResponseEntity.noContent().build()); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user posts", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = Post.class) + ) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/{id}/posts") + public Flux retrieveUserPosts(@PathVariable long id) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ).flatMapMany(user -> postRepository.findPostForUser(id)); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", + description = "Create user post", + content = { + @Content( + mediaType = "application/json" + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }), + @ApiResponse( + responseCode = "400", + description = "Bad request", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @PostMapping("/{id}/posts") + public Mono> createUserPost(@PathVariable int id, @Valid @RequestBody Post post) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ).flatMap(user -> moderateContent(post)) + .flatMap(moderatedPost -> postRepository.save(id, post)) + .map(savedPost -> ResponseEntity.created(null).build()); + } + + private Mono moderateContent(Post post) { + if (!moderate) { + return Mono.just(post); + } + return sentimentAnalysisClient + .retrieveSentiment(post.getDescription()) + .map(sentiment -> !sentiment.getLabel().equalsIgnoreCase("neg")) + .switchIfEmpty(Mono.error(new NegativeSentimentException("Negative sentiment detected"))) + .map(sentiment -> post); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java new file mode 100644 index 0000000..2819bf2 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java @@ -0,0 +1,39 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.bind.support.WebExchangeBindException; + +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class AppExceptionalHandler { + + @ExceptionHandler(UserNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + ErrorDetails onUserNotFound(UserNotFoundException userNotFound, ServerHttpRequest request) { + return new ErrorDetails(userNotFound.getMessage(), Map.of("uri", request.getURI().getPath())); + } + + @ExceptionHandler(NegativeSentimentException.class) + @ResponseStatus(HttpStatus.FORBIDDEN) + ErrorDetails onNegativeSentiment(NegativeSentimentException negativeSentiment, ServerHttpRequest request) { + return new ErrorDetails(negativeSentiment.getMessage(), Map.of("uri", request.getURI().getPath())); + } + + @ExceptionHandler(WebExchangeBindException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ErrorDetails onMethodArgumentNotValid(WebExchangeBindException webExchangeBindException, + ServerHttpRequest request) { + return new ErrorDetails("Request validation failed", Map.of( + "uri", request.getURI().getPath(), + "failedValidations", webExchangeBindException.getFieldErrors().stream() + .map(fe -> Map.of(fe.getField(), fe.getDefaultMessage())) + .collect(Collectors.toList()) + )); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java new file mode 100644 index 0000000..c671219 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java @@ -0,0 +1,28 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +import java.time.LocalDateTime; +import java.util.Map; + +public class ErrorDetails { + private final LocalDateTime timeStamp; + private final String message; + private final Map details; + + public ErrorDetails(String message, Map details) { + this.timeStamp = LocalDateTime.now(); + this.message = message; + this.details = details; + } + + public LocalDateTime getTimeStamp() { + return timeStamp; + } + + public String getMessage() { + return message; + } + + public Map getDetails() { + return details; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java new file mode 100644 index 0000000..8ebcd30 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +public class NegativeSentimentException extends RuntimeException { + public NegativeSentimentException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java new file mode 100644 index 0000000..4eba5cf --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java new file mode 100644 index 0000000..26c40bc --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java @@ -0,0 +1,35 @@ +package integration.samples.springboot.reactive.socialmedia.model; + +import org.springframework.data.annotation.Id; + +public class Post { + @Id + private long id; + + private String description; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Post{"); + sb.append("id=").append(id); + sb.append(", description='").append(description).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java new file mode 100644 index 0000000..5560076 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java @@ -0,0 +1,51 @@ +package integration.samples.springboot.reactive.socialmedia.model; + +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.Size; +import org.springframework.data.annotation.Id; + +import java.time.LocalDate; + +public class User { + @Id + private long id; + @Size(min = 2, message = "Name should have at least two characters") + private String name; + + @Past(message = "Birthdate should be in the past") + private LocalDate birthDate; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("User{"); + sb.append("id=").append(id); + sb.append(", name='").append(name).append('\''); + sb.append(", birthDate=").append(birthDate); + sb.append('}'); + return sb.toString(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java new file mode 100644 index 0000000..ca0bca4 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java @@ -0,0 +1,10 @@ +package integration.samples.springboot.reactive.socialmedia.repository; + +import integration.samples.springboot.reactive.socialmedia.model.Post; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface PostRepository { + Flux findPostForUser(long userId); + Mono save(long userId, Post post); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java new file mode 100644 index 0000000..5fb2da0 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java @@ -0,0 +1,15 @@ +package integration.samples.springboot.reactive.socialmedia.repository; + +import integration.samples.springboot.reactive.socialmedia.model.User; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface UserRepository { + Flux findAll(); + + Mono save(User user); + + Mono findById(long id); + + Mono deleteById(long id); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java new file mode 100644 index 0000000..7f832c5 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java @@ -0,0 +1,52 @@ +package integration.samples.springboot.reactive.socialmedia.repository.impl; + +import integration.samples.springboot.reactive.socialmedia.model.Post; +import integration.samples.springboot.reactive.socialmedia.repository.PostRepository; +import io.r2dbc.spi.Row; +import io.r2dbc.spi.RowMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.r2dbc.core.DatabaseClient; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.function.BiFunction; + +@Repository +public class PostRepositoryImpl implements PostRepository { + private static final BiFunction MAPPING_FUNCTION = (row, rowMetadata) -> { + Post post = new Post(); + post.setId(row.get("id", Long.class)); + post.setDescription(row.get("description", String.class)); + return post; + }; + + private final DatabaseClient dbClient; + + @Autowired + public PostRepositoryImpl(DatabaseClient dbClient) { + this.dbClient = dbClient; + } + + @Override + public Flux findPostForUser(long userId) { + return dbClient.sql("SELECT * FROM post WHERE user_id=:userId") + .bind("userId", userId) + .map(MAPPING_FUNCTION) + .all(); + } + + @Override + public Mono save(long userId, Post post) { + return dbClient.sql("INSERT INTO post (description, user_id) VALUES (:description, :userId)") + .filter((statement, next) -> statement.returnGeneratedValues("id").execute()) + .bind("userId", userId) + .bind("description", post.getDescription()) + .fetch() + .first() + .map(row -> { + post.setId((long) row.get("id")); + return post; + }); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java new file mode 100644 index 0000000..5669069 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java @@ -0,0 +1,69 @@ +package integration.samples.springboot.reactive.socialmedia.repository.impl; + +import integration.samples.springboot.reactive.socialmedia.model.User; +import integration.samples.springboot.reactive.socialmedia.repository.UserRepository; +import io.r2dbc.spi.Row; +import io.r2dbc.spi.RowMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.r2dbc.core.DatabaseClient; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.LocalDate; +import java.util.function.BiFunction; + +@Repository +public class UserRepositoryImpl implements UserRepository { + private static final BiFunction MAPPING_FUNCTION = (row, rowMetadata) -> { + User user = new User(); + user.setId(row.get("id", Long.class)); + user.setName(row.get("name", String.class)); + user.setBirthDate(row.get("birth_date", LocalDate.class)); + return user; + }; + + private final DatabaseClient dbClient; + + @Autowired + public UserRepositoryImpl(DatabaseClient dbClient) { + this.dbClient = dbClient; + } + + @Override + public Flux findAll() { + return dbClient.sql("SELECT * FROM user") + .map(MAPPING_FUNCTION) + .all(); + } + + @Override + public Mono save(User user) { + return dbClient.sql("INSERT INTO user (name, birth_date) VALUES (:name, :birthDate)") + .filter((statement, next) -> statement.returnGeneratedValues("id").execute()) + .bind("name", user.getName()) + .bind("birthDate", user.getBirthDate()) + .fetch() + .first() + .map(row -> { + user.setId((long) row.get("id")); + return user; + }); + } + + @Override + public Mono findById(long id) { + return dbClient.sql("SELECT * FROM user WHERE id=:userId") + .bind("userId", id) + .map(MAPPING_FUNCTION) + .first(); + } + + @Override + public Mono deleteById(long id) { + return dbClient.sql("DELETE FROM user WHERE id=:userId") + .bind("userId", id) + .fetch() + .rowsUpdated(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java new file mode 100644 index 0000000..7b6041f --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java @@ -0,0 +1,31 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +public class Probability { + private double neg; + private double neutral; + private double pos; + + public double getNeg() { + return neg; + } + + public void setNeg(double neg) { + this.neg = neg; + } + + public double getNeutral() { + return neutral; + } + + public void setNeutral(double neutral) { + this.neutral = neutral; + } + + public double getPos() { + return pos; + } + + public void setPos(double pos) { + this.pos = pos; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java new file mode 100644 index 0000000..af11c53 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java @@ -0,0 +1,22 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +public class Sentiment { + private Probability probability; + private String label; + + public Probability getProbability() { + return probability; + } + + public void setProbability(Probability probability) { + this.probability = probability; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java new file mode 100644 index 0000000..337d442 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +import reactor.core.publisher.Mono; + +public interface SentimentAnalysisClient { + + Mono retrieveSentiment(String content); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java new file mode 100644 index 0000000..0cf57ff --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java @@ -0,0 +1,28 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +@Service +public class SentimentAnalysisClientImpl implements SentimentAnalysisClient { + private final WebClient sentimentClient; + + @Autowired + public SentimentAnalysisClientImpl() { + this.sentimentClient = WebClient.builder().baseUrl("http://localhost:8088").build(); + } + + @Override + public Mono retrieveSentiment(String content) { + return sentimentClient.post() + .uri("/text-processing/api/sentiment") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromValue(content)) + .retrieve() + .bodyToMono(Sentiment.class); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/resources/application.properties b/rest-social-media/springboot-reactive/src/main/resources/application.properties new file mode 100644 index 0000000..6ab8ef0 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8087 + +spring.r2dbc.url=r2dbc:mysql://localhost:3306/social_media_database +spring.r2dbc.username=social_media_user +spring.r2dbc.password=dummypassword + +sentiment.moderate=true + diff --git a/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java b/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java new file mode 100644 index 0000000..f7c3ee8 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.reactive.socialmedia; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SocialMediaApplicationTests { + + // @Test + // void contextLoads() { + // } + +} From 6f4cbafa3344c1f7fab24dcfb33ac950d2e0cab8 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:11:16 +0530 Subject: [PATCH 05/24] Update the social-media service configurations --- rest-social-media/ballerina/Config.toml | 8 +++--- .../ballerina/resources/db/init.sql | 27 ------------------- 2 files changed, 3 insertions(+), 32 deletions(-) delete mode 100644 rest-social-media/ballerina/resources/db/init.sql diff --git a/rest-social-media/ballerina/Config.toml b/rest-social-media/ballerina/Config.toml index 51e07ce..2902112 100644 --- a/rest-social-media/ballerina/Config.toml +++ b/rest-social-media/ballerina/Config.toml @@ -1,10 +1,8 @@ moderate = true [databaseConfig] -database_user = "social_media_user" -database_password = "dummypassword" host = "localhost" port = 3306 - -[ballerina.observe] -tracingEnabled=true +user = "social_media_user" +password = "dummypassword" +database = "social_media_database" diff --git a/rest-social-media/ballerina/resources/db/init.sql b/rest-social-media/ballerina/resources/db/init.sql deleted file mode 100644 index 0019f8e..0000000 --- a/rest-social-media/ballerina/resources/db/init.sql +++ /dev/null @@ -1,27 +0,0 @@ -CREATE TABLE USER_DETAILS(ID IDENTITY PRIMARY KEY, BIRTH_DATE DATE, NAME VARCHAR(255)); -CREATE TABLE POST(ID IDENTITY PRIMARY KEY, DESCRIPTION VARCHAR(255), USER_ID BIGINT); - -ALTER TABLE POST -ADD FOREIGN KEY (USER_ID) -REFERENCES USER_DETAILS(ID) ON DELETE CASCADE; - -insert into user_details(birth_date, name) -values(current_date(), 'Ranga'); - -insert into user_details(birth_date, name) -values(current_date(), 'Ravi'); - -insert into user_details(birth_date, name) -values(current_date(), 'Sathish'); - -insert into post(description, user_id) -values('I want to learn AWS', 1); - -insert into post(description, user_id) -values('I want to learn DevOps', 1); - -insert into post(description, user_id) -values('I want to learn GCP', 2); - -insert into post(description, user_id) -values('I want to learn multi cloud', 3); From e2fc0831a39693b27ff4a18257a578892716262a Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:11:41 +0530 Subject: [PATCH 06/24] Add db-init scripts --- rest-social-media/resources/db/init.sql | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 rest-social-media/resources/db/init.sql diff --git a/rest-social-media/resources/db/init.sql b/rest-social-media/resources/db/init.sql new file mode 100644 index 0000000..d408991 --- /dev/null +++ b/rest-social-media/resources/db/init.sql @@ -0,0 +1,31 @@ +CREATE TABLE users ( + id INT NOT NULL auto_increment PRIMARY KEY, + birth_date DATE, + name VARCHAR(255) +); +CREATE TABLE posts ( + id INT NOT NULL auto_increment PRIMARY KEY, + description VARCHAR(255), + user_id INT +); + +insert into users(birth_date, name) +values(current_date(), 'Ranga'); + +insert into users(birth_date, name) +values(current_date(), 'Ravi'); + +insert into users(birth_date, name) +values(current_date(), 'Sathish'); + +insert into posts(description, user_id) +values('I want to learn AWS', 1); + +insert into posts(description, user_id) +values('I want to learn DevOps', 1); + +insert into posts(description, user_id) +values('I want to learn GCP', 2); + +insert into posts(description, user_id) +values('I want to learn multi cloud', 3); From 462c9b66380e770efca4ef4bbb66e0e92e819d44 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:11:54 +0530 Subject: [PATCH 07/24] Add the readme file --- rest-social-media/README.md | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 rest-social-media/README.md diff --git a/rest-social-media/README.md b/rest-social-media/README.md new file mode 100644 index 0000000..3623dc3 --- /dev/null +++ b/rest-social-media/README.md @@ -0,0 +1,45 @@ +# Springboot and Ballerina + +A sample code base which touches key features of each technology. The sample is based on a simple API written for a social-media site which has users and associated posts. Following is the high level component diagram. + +drawing + +Following are the features used for the implementation + +1. Configuring verbs and URLs +2. Error handlers for sending customized error messages +3. Adding constraints/validations +4. OpenAPI specification for Generating API docs +5. Accessing database +6. Configurability +7. HTTP client +8. Resiliency - Retry +9. Docker image generation + +# Setting up each environment + +## Spring boot +Run the `springboot-docker-compose.yml` docker compose setup. +```sh +docker compose -f springboot-docker-compose.yml up +``` + +## Spring boot (Reactive) +Run the `springboot-reactive-docker-compose.yml` docker compose setup. +```sh +docker compose -f springboot-reactive-docker-compose.yml up +``` + +## Ballerina +Run the `ballerina-docker-compose.yml` docker compose setup. +```sh +docker compose -f ballerina-docker-compose.yml up +``` + +# Try out +## Spring boot (Default and Reactive) +- To send request open `springboot-social-media.http` file using VS Code with `REST Client` extension + +## Ballerina +- To send request open `ballerina-social-media.http` file using VS Code with `REST Client` extension + From 4861e60cff00092b57977c0e0f3206c055f8e38d Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:12:57 +0530 Subject: [PATCH 08/24] Add relevant docker compose files --- .../ballerina-docker-compose.yml | 36 +++++++++++++++++++ .../springboot-docker-compose.yml | 36 +++++++++++++++++++ .../springboot-reactive-docker-compose.yml | 36 +++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 rest-social-media/ballerina-docker-compose.yml create mode 100644 rest-social-media/springboot-docker-compose.yml create mode 100644 rest-social-media/springboot-reactive-docker-compose.yml diff --git a/rest-social-media/ballerina-docker-compose.yml b/rest-social-media/ballerina-docker-compose.yml new file mode 100644 index 0000000..e6b1e2b --- /dev/null +++ b/rest-social-media/ballerina-docker-compose.yml @@ -0,0 +1,36 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/ballerina-social-media:0.0.1' + ports: + - '9090:9090' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/ballerina-sentiment-api:0.0.1' + ports: + - '9099:9099' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" diff --git a/rest-social-media/springboot-docker-compose.yml b/rest-social-media/springboot-docker-compose.yml new file mode 100644 index 0000000..08d0eba --- /dev/null +++ b/rest-social-media/springboot-docker-compose.yml @@ -0,0 +1,36 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/springboot-social-media:0.0.1' + ports: + - '8087:8087' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/springboot-sentiment-api:0.0.1' + ports: + - '8088:8088' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" diff --git a/rest-social-media/springboot-reactive-docker-compose.yml b/rest-social-media/springboot-reactive-docker-compose.yml new file mode 100644 index 0000000..745f70c --- /dev/null +++ b/rest-social-media/springboot-reactive-docker-compose.yml @@ -0,0 +1,36 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/springboot-reactive-social-media:0.0.1' + ports: + - '8087:8087' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/springboot-sentiment-api:0.0.1' + ports: + - '8088:8088' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" From 14788d24c5a6ac23096f564f03aec7ee776ec5b5 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:13:29 +0530 Subject: [PATCH 09/24] Add relevant .http files for VSCode REST client --- rest-social-media/ballerina-social-media.http | 32 +++++++++++++++++++ .../springboot-social-media.http | 29 +++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 rest-social-media/ballerina-social-media.http create mode 100644 rest-social-media/springboot-social-media.http diff --git a/rest-social-media/ballerina-social-media.http b/rest-social-media/ballerina-social-media.http new file mode 100644 index 0000000..6f60274 --- /dev/null +++ b/rest-social-media/ballerina-social-media.http @@ -0,0 +1,32 @@ +### Creat a user +POST http://localhost:9090/social-media/users +content-type: application/json + +{ + "birthDate": { + "year": 1987, + "month": 02, + "day": 06 + }, + "name": "Rimas" +} + +### Get users +GET http://localhost:9090/social-media/users + +### Get a specific user +GET http://localhost:9090/social-media/users/1 + +### Get posts +GET http://localhost:9090/social-media/users/3/posts + +### Create a post +POST http://localhost:9090/social-media/users/3/posts +content-type: application/json + +{ + "description": "I wang to learn GCP" +} + +### Delete a user +DELETE http://localhost:9090/social-media/users/1 \ No newline at end of file diff --git a/rest-social-media/springboot-social-media.http b/rest-social-media/springboot-social-media.http new file mode 100644 index 0000000..cc19b69 --- /dev/null +++ b/rest-social-media/springboot-social-media.http @@ -0,0 +1,29 @@ +### Creat a user +POST http://localhost:8087/social-media/users +content-type: application/json + +{ + "name": "Ravi", + "birthDate": "1997-08-11" +} + +### Get users +GET http://localhost:8087/social-media/users + +### Get a specific user +GET http://localhost:8087/social-media/users/1 + +### Create a post +POST http://localhost:8087/social-media/users/1/post +content-type: application/json + +{ + "description": "I wang to learn GCP" +} + +### Get posts +GET http://localhost:8087/social-media/users/1/posts + + +### Delete a user +DELETE http://localhost:8087/social-media/users/1 \ No newline at end of file From d52aff6110458c0b18571cf36b95061edd2d47e9 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:15:50 +0530 Subject: [PATCH 10/24] Refactor the MySQL init script --- rest-social-media/resources/db/init.sql | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/rest-social-media/resources/db/init.sql b/rest-social-media/resources/db/init.sql index d408991..30d7df5 100644 --- a/rest-social-media/resources/db/init.sql +++ b/rest-social-media/resources/db/init.sql @@ -1,31 +1,31 @@ -CREATE TABLE users ( +CREATE TABLE user ( id INT NOT NULL auto_increment PRIMARY KEY, birth_date DATE, name VARCHAR(255) ); -CREATE TABLE posts ( +CREATE TABLE post ( id INT NOT NULL auto_increment PRIMARY KEY, description VARCHAR(255), user_id INT ); -insert into users(birth_date, name) +insert into user(birth_date, name) values(current_date(), 'Ranga'); -insert into users(birth_date, name) +insert into user(birth_date, name) values(current_date(), 'Ravi'); -insert into users(birth_date, name) +insert into user(birth_date, name) values(current_date(), 'Sathish'); -insert into posts(description, user_id) +insert into post(description, user_id) values('I want to learn AWS', 1); -insert into posts(description, user_id) +insert into post(description, user_id) values('I want to learn DevOps', 1); -insert into posts(description, user_id) +insert into post(description, user_id) values('I want to learn GCP', 2); -insert into posts(description, user_id) +insert into post(description, user_id) values('I want to learn multi cloud', 3); From 05dbbdd4f777f4cfc0e90421cbb3ec34eafaa705 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:16:13 +0530 Subject: [PATCH 11/24] Refactor the DB entity --- .../integration/samples/springboot/socialmedia/model/User.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java index 21c8d07..f7e4bf8 100644 --- a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java @@ -8,7 +8,7 @@ import java.time.LocalDate; import java.util.List; -@Entity(name = "user_details") +@Entity public class User { @Id From 4e2d9c8783022bc698a09cdfdb439cb803b76ad5 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 12:17:27 +0530 Subject: [PATCH 12/24] Add missing image --- rest-social-media/springboot-and-ballerina.png | Bin 0 -> 13908 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 rest-social-media/springboot-and-ballerina.png diff --git a/rest-social-media/springboot-and-ballerina.png b/rest-social-media/springboot-and-ballerina.png new file mode 100644 index 0000000000000000000000000000000000000000..048047f374ba0c3f833ca56953133105ba7c043f GIT binary patch literal 13908 zcmdUWXH=6-@UIPc5e0=PMFfRth)73TD54k$B`By!M=%rxBtd#piU@>~(7Q@ikRlj5 zNC^ZG5Tu7@2t`^*klt>1U-8`kxBKCqbI(1859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6K1twl1Ip*6R@{>i21osocZDc7A;DD>lYP@DhRCE7Y-%$0lBCa`LP z9JJe78mD!~SGixlRv09&B207M)h|P1R$a%|^#%4Xnx7o~v0JD8iCbYU2nd^db=kE| zn{(5)s;HhIx}6QTr;La|%9@Qb+Dq2!>MB zuoknqmU4v3V?Nt&V|1#p5fCjIJLQOZ&e=Mula@eA#88AgnY$lja*Ct!r6{Q!%wsBL zaB}DMRY2T3E=&4e_#yuFAUIm1->o|#(2jdGRqJL$t27h)#5SGUR%TudHG}(W`5Unl zkSeT=FW!JMH}uHAM1eoQ>00}~2$LrP)4%mi$9dVjh}?W{<;97Gxr+g-(M=^jz(p_m z9gac?kswI4_*3&~Iye8JFBKEbj5TF<#yS+71n5Ror&dSO?r5)Zx~bRu2t0@AtCe58 zw7twBq4}M~_sE;w`aSF4Y4=ds%TYy~+Oe0rLBFPbsAdKFu`59j;*jr~WT;d9l2;J6 zum8R2aRoB9YPI!G$WxzZwc!Hq$Wro^B2hAggBeJ_#8b$o58R-psW`I8yb)vbmBEAQ zJk5+hH-TvO8??z50l)4uZ0KrAfnPmOa Date: Tue, 11 Jul 2023 12:37:50 +0530 Subject: [PATCH 13/24] Add missing config annotation --- .../samples/springboot/socialmedia/SocialMediaApplication.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java index 47cbf96..d28b3d5 100644 --- a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java @@ -2,8 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication +@EnableFeignClients public class SocialMediaApplication { public static void main(String[] args) { From 090c45cd0cf7212adf2e495b9c6ab651c4018e09 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 13:20:52 +0530 Subject: [PATCH 14/24] Update docker compose configurations --- rest-social-media/springboot-docker-compose.yml | 9 +++++++++ rest-social-media/springboot-reactive-docker-compose.yml | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/rest-social-media/springboot-docker-compose.yml b/rest-social-media/springboot-docker-compose.yml index 08d0eba..27b696a 100644 --- a/rest-social-media/springboot-docker-compose.yml +++ b/rest-social-media/springboot-docker-compose.yml @@ -16,6 +16,15 @@ services: image: 'shafreen/springboot-sentiment-api:0.0.1' ports: - '8088:8088' + depends_on: + zipkin: + condition: service_started + network_mode: "host" + + zipkin: + image: 'openzipkin/zipkin' + ports: + - '9411:9411' network_mode: "host" mysql: diff --git a/rest-social-media/springboot-reactive-docker-compose.yml b/rest-social-media/springboot-reactive-docker-compose.yml index 745f70c..290f805 100644 --- a/rest-social-media/springboot-reactive-docker-compose.yml +++ b/rest-social-media/springboot-reactive-docker-compose.yml @@ -16,6 +16,15 @@ services: image: 'shafreen/springboot-sentiment-api:0.0.1' ports: - '8088:8088' + depends_on: + zipkin: + condition: service_started + network_mode: "host" + + zipkin: + image: 'openzipkin/zipkin' + ports: + - '9411:9411' network_mode: "host" mysql: From b3352a418ff799fcf0876c36005908aef9229831 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 13:57:10 +0530 Subject: [PATCH 15/24] Add retry config --- .../sentiment/SentimentAnalysisClientImpl.java | 12 +++++++++++- .../src/main/resources/application.properties | 3 +++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java index 0cf57ff..3a6628d 100644 --- a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java @@ -1,16 +1,25 @@ package integration.samples.springboot.reactive.socialmedia.sentiment; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; +import reactor.util.retry.Retry; + +import java.time.Duration; @Service public class SentimentAnalysisClientImpl implements SentimentAnalysisClient { private final WebClient sentimentClient; + @Value("${sentiment-api.maxRetryAttempts}") + private int maxRetryAttempts; + @Value("${sentiment-api.waitDuration}") + private int waitDuration; + @Autowired public SentimentAnalysisClientImpl() { this.sentimentClient = WebClient.builder().baseUrl("http://localhost:8088").build(); @@ -23,6 +32,7 @@ public Mono retrieveSentiment(String content) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromValue(content)) .retrieve() - .bodyToMono(Sentiment.class); + .bodyToMono(Sentiment.class) + .retryWhen(Retry.fixedDelay(maxRetryAttempts, Duration.ofSeconds(waitDuration))); } } diff --git a/rest-social-media/springboot-reactive/src/main/resources/application.properties b/rest-social-media/springboot-reactive/src/main/resources/application.properties index 6ab8ef0..e6d5a45 100644 --- a/rest-social-media/springboot-reactive/src/main/resources/application.properties +++ b/rest-social-media/springboot-reactive/src/main/resources/application.properties @@ -6,3 +6,6 @@ spring.r2dbc.password=dummypassword sentiment.moderate=true +sentiment-api.maxRetryAttempts=3 +sentiment-api.waitDuration=5s + From 81b30100b1a8c6e420a06f653a1ac2a781bf2cbb Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 14:04:14 +0530 Subject: [PATCH 16/24] Fix configurations --- .../src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/springboot-reactive/src/main/resources/application.properties b/rest-social-media/springboot-reactive/src/main/resources/application.properties index e6d5a45..2cf07e9 100644 --- a/rest-social-media/springboot-reactive/src/main/resources/application.properties +++ b/rest-social-media/springboot-reactive/src/main/resources/application.properties @@ -7,5 +7,5 @@ spring.r2dbc.password=dummypassword sentiment.moderate=true sentiment-api.maxRetryAttempts=3 -sentiment-api.waitDuration=5s +sentiment-api.waitDuration=5 From 3fdaba9394e0b196eddfbd75d25c49e7c4826707 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 14:05:21 +0530 Subject: [PATCH 17/24] Fix controller method mapping --- .../socialmedia/controller/SocialMediaController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java index 268af79..d342d68 100644 --- a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java @@ -147,7 +147,7 @@ public List retrieveUserPosts(@PathVariable int id) { content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDetails.class))}) }) - @PostMapping("/social-media/users/{id}/post") + @PostMapping("/social-media/users/{id}/posts") @Retry(name = "sentiment-api") public ResponseEntity createUserPost(@PathVariable int id, @Valid @RequestBody Post post) { Optional user = userRepository.findById(id); From 745a0aeb3a489080aeecaf7436ead67f2f8e70d6 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 14:05:55 +0530 Subject: [PATCH 18/24] Update VSCode REST client configs --- rest-social-media/springboot-social-media.http | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/springboot-social-media.http b/rest-social-media/springboot-social-media.http index cc19b69..9c89fec 100644 --- a/rest-social-media/springboot-social-media.http +++ b/rest-social-media/springboot-social-media.http @@ -14,7 +14,7 @@ GET http://localhost:8087/social-media/users GET http://localhost:8087/social-media/users/1 ### Create a post -POST http://localhost:8087/social-media/users/1/post +POST http://localhost:8087/social-media/users/1/posts content-type: application/json { From 2f758f7db73932cf7edd9b5993275cbae5c992ac Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 14:37:39 +0530 Subject: [PATCH 19/24] Update SQL queries --- .../ballerina/social_media_service.bal | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/rest-social-media/ballerina/social_media_service.bal b/rest-social-media/ballerina/social_media_service.bal index 5246139..2ff4549 100644 --- a/rest-social-media/ballerina/social_media_service.bal +++ b/rest-social-media/ballerina/social_media_service.bal @@ -56,7 +56,7 @@ service SocialMedia /social\-media on socialMediaListener { # # + return - The list of users or error message resource function get users() returns User[]|error { - stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.user_details`); + stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.users`); return from User user in userStream select user; } @@ -66,7 +66,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID of the user to be retrived # + return - A specific user or error message resource function get users/[int id]() returns User|UserNotFound|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE ID = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE ID = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -84,7 +84,7 @@ service SocialMedia /social\-media on socialMediaListener { # + return - The created message or error message resource function post users(@http:Payload NewUser newUser) returns http:Created|error { _ = check self.socialMediaDb->execute(` - INSERT INTO social_media_database.user_details(birth_date, name) + INSERT INTO social_media_database.users(birth_date, name) VALUES (${newUser.birthDate}, ${newUser.name});`); return http:CREATED; } @@ -95,7 +95,7 @@ service SocialMedia /social\-media on socialMediaListener { # + return - The success message or error message resource function delete users/[int id]() returns http:NoContent|error { _ = check self.socialMediaDb->execute(` - DELETE FROM social_media_database.user_details WHERE id = ${id};`); + DELETE FROM social_media_database.users WHERE id = ${id};`); return http:NO_CONTENT; } @@ -104,7 +104,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID for which posts are retrieved # + return - A list of posts or error message resource function get users/[int id]/posts() returns Post[]|UserNotFound|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE id = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE id = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -113,7 +113,7 @@ service SocialMedia /social\-media on socialMediaListener { return userNotFound; } - stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.post WHERE user_id = ${id}`); + stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.posts WHERE user_id = ${id}`); Post[]|error posts = from Post post in postStream select post; return posts; @@ -124,7 +124,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID for which the post is created # + return - The created message or error message resource function post users/[int id]/posts(@http:Payload NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user_details WHERE id = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE id = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -146,7 +146,7 @@ service SocialMedia /social\-media on socialMediaListener { } _ = check self.socialMediaDb->execute(` - INSERT INTO social_media_database.post(description, user_id) + INSERT INTO social_media_database.posts(description, user_id) VALUES (${newPost.description}, ${id});`); return http:CREATED; } From 1564c0707a3280c9116e9e8e51c27d737adef66c Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Tue, 11 Jul 2023 14:39:05 +0530 Subject: [PATCH 20/24] Refactor SQL queries --- .../ballerina/social_media_service.bal | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/rest-social-media/ballerina/social_media_service.bal b/rest-social-media/ballerina/social_media_service.bal index 2ff4549..2b2d7e3 100644 --- a/rest-social-media/ballerina/social_media_service.bal +++ b/rest-social-media/ballerina/social_media_service.bal @@ -56,7 +56,7 @@ service SocialMedia /social\-media on socialMediaListener { # # + return - The list of users or error message resource function get users() returns User[]|error { - stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.users`); + stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.user`); return from User user in userStream select user; } @@ -66,7 +66,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID of the user to be retrived # + return - A specific user or error message resource function get users/[int id]() returns User|UserNotFound|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE ID = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE ID = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -84,7 +84,7 @@ service SocialMedia /social\-media on socialMediaListener { # + return - The created message or error message resource function post users(@http:Payload NewUser newUser) returns http:Created|error { _ = check self.socialMediaDb->execute(` - INSERT INTO social_media_database.users(birth_date, name) + INSERT INTO social_media_database.user(birth_date, name) VALUES (${newUser.birthDate}, ${newUser.name});`); return http:CREATED; } @@ -95,7 +95,7 @@ service SocialMedia /social\-media on socialMediaListener { # + return - The success message or error message resource function delete users/[int id]() returns http:NoContent|error { _ = check self.socialMediaDb->execute(` - DELETE FROM social_media_database.users WHERE id = ${id};`); + DELETE FROM social_media_database.user WHERE id = ${id};`); return http:NO_CONTENT; } @@ -104,7 +104,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID for which posts are retrieved # + return - A list of posts or error message resource function get users/[int id]/posts() returns Post[]|UserNotFound|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE id = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE id = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -113,7 +113,7 @@ service SocialMedia /social\-media on socialMediaListener { return userNotFound; } - stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.posts WHERE user_id = ${id}`); + stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.post WHERE user_id = ${id}`); Post[]|error posts = from Post post in postStream select post; return posts; @@ -124,7 +124,7 @@ service SocialMedia /social\-media on socialMediaListener { # + id - The user ID for which the post is created # + return - The created message or error message resource function post users/[int id]/posts(@http:Payload NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { - User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.users WHERE id = ${id}`); + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE id = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); UserNotFound userNotFound = { @@ -146,7 +146,7 @@ service SocialMedia /social\-media on socialMediaListener { } _ = check self.socialMediaDb->execute(` - INSERT INTO social_media_database.posts(description, user_id) + INSERT INTO social_media_database.post(description, user_id) VALUES (${newPost.description}, ${id});`); return http:CREATED; } From 87117616e269a9c005ed0ed29c0bb7a4d66a3d7b Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Thu, 27 Jul 2023 13:51:44 +0530 Subject: [PATCH 21/24] Incorporate review suggestions --- .../ballerina/response_error_interceptor.bal | 2 +- .../ballerina/social_media_service.bal | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/rest-social-media/ballerina/response_error_interceptor.bal b/rest-social-media/ballerina/response_error_interceptor.bal index 10a7a13..38852ea 100644 --- a/rest-social-media/ballerina/response_error_interceptor.bal +++ b/rest-social-media/ballerina/response_error_interceptor.bal @@ -21,7 +21,7 @@ import ballerina/constraint; service class ResponseErrorInterceptor { *http:ResponseErrorInterceptor; - remote function interceptResponseError(http:RequestContext ctx, error err) + remote function interceptResponseError(error err) returns SocialMediaBadReqeust|SocialMediaServerError { ErrorDetails errorDetails = buildErrorPayload(err.message(), ""); diff --git a/rest-social-media/ballerina/social_media_service.bal b/rest-social-media/ballerina/social_media_service.bal index 2b2d7e3..de3eea6 100644 --- a/rest-social-media/ballerina/social_media_service.bal +++ b/rest-social-media/ballerina/social_media_service.bal @@ -33,9 +33,7 @@ type DataBaseConfig record {| |}; configurable DataBaseConfig databaseConfig = ?; -listener http:Listener socialMediaListener = new (9090, - interceptors = [new ResponseErrorInterceptor()] -); +listener http:Listener socialMediaListener = new (9090); service SocialMedia /social\-media on socialMediaListener { @@ -51,6 +49,11 @@ service SocialMedia /social\-media on socialMediaListener { ); log:printInfo("Social media service started"); } + + // Service-level error interceptors can handle errors occurred during the service execution. + public function createInterceptors() returns ResponseErrorInterceptor { + return new ResponseErrorInterceptor(); + } # Get all the users # @@ -73,16 +76,15 @@ service SocialMedia /social\-media on socialMediaListener { body: errorDetails }; return userNotFound; - } else { - return result; } + return result; } # Create a new user # # + newUser - The user details of the new user # + return - The created message or error message - resource function post users(@http:Payload NewUser newUser) returns http:Created|error { + resource function post users(NewUser newUser) returns http:Created|error { _ = check self.socialMediaDb->execute(` INSERT INTO social_media_database.user(birth_date, name) VALUES (${newUser.birthDate}, ${newUser.name});`); @@ -123,7 +125,7 @@ service SocialMedia /social\-media on socialMediaListener { # # + id - The user ID for which the post is created # + return - The created message or error message - resource function post users/[int id]/posts(@http:Payload NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { + resource function post users/[int id]/posts(NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE id = ${id}`); if result is sql:NoRowsError { ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); From b9b33169dfe672d3bb6a58aef5b1a4fde1d98b52 Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Thu, 27 Jul 2023 13:57:08 +0530 Subject: [PATCH 22/24] Refactor response-error interceptor --- rest-social-media/ballerina/response_error_interceptor.bal | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/rest-social-media/ballerina/response_error_interceptor.bal b/rest-social-media/ballerina/response_error_interceptor.bal index 38852ea..7afbd14 100644 --- a/rest-social-media/ballerina/response_error_interceptor.bal +++ b/rest-social-media/ballerina/response_error_interceptor.bal @@ -15,17 +15,16 @@ // under the License. import ballerina/http; -import ballerina/constraint; // Handle listener errors service class ResponseErrorInterceptor { *http:ResponseErrorInterceptor; - remote function interceptResponseError(error err) + remote function interceptResponseError(http:Request req, error err) returns SocialMediaBadReqeust|SocialMediaServerError { - ErrorDetails errorDetails = buildErrorPayload(err.message(), ""); + ErrorDetails errorDetails = buildErrorPayload(err.message(), req.rawPath); - if err is constraint:Error { + if err is http:PayloadValidationError { SocialMediaBadReqeust socialMediaBadRequest = { body: errorDetails }; From d5a67e32d8f6e96f97721bb0c97cf79234e3c39e Mon Sep 17 00:00:00 2001 From: ayeshLK Date: Thu, 27 Jul 2023 14:12:55 +0530 Subject: [PATCH 23/24] Update social-media service type --- rest-social-media/ballerina/social_media_service_desc.bal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/ballerina/social_media_service_desc.bal b/rest-social-media/ballerina/social_media_service_desc.bal index fd0acc5..a3c21c4 100644 --- a/rest-social-media/ballerina/social_media_service_desc.bal +++ b/rest-social-media/ballerina/social_media_service_desc.bal @@ -20,7 +20,7 @@ import ballerina/sql; import ballerina/time; type SocialMedia service object { - *http:Service; + *http:InterceptableService; // users resource resource function get users() returns User[]|error; From d98127aa1df1184700b1df0942ddc7a1789649cd Mon Sep 17 00:00:00 2001 From: Anupama Pathirage Date: Tue, 26 Nov 2024 09:21:54 -0600 Subject: [PATCH 24/24] Update rest-social-media/ballerina-social-media.http Co-authored-by: Lakshan Weerasinghe <46857198+LakshanWeerasinghe@users.noreply.github.com> --- rest-social-media/ballerina-social-media.http | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest-social-media/ballerina-social-media.http b/rest-social-media/ballerina-social-media.http index 6f60274..46c6f56 100644 --- a/rest-social-media/ballerina-social-media.http +++ b/rest-social-media/ballerina-social-media.http @@ -29,4 +29,4 @@ content-type: application/json } ### Delete a user -DELETE http://localhost:9090/social-media/users/1 \ No newline at end of file +DELETE http://localhost:9090/social-media/users/1