diff --git a/README.md b/README.md index 680af7b..606464c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Demo project for running labs to evaluate Copilot viability ## Goal -The goal of a GitHub Copilot Hackaton is to learn how to use it, using an exercise that consist of building a web server using Nodejs with different functionalities, a .NET Web API or a Java Spring Boot API. +The goal of a GitHub Copilot Hackaton is to learn how to use it, using an exercise that consist of building a web server using Nodejs with different functionalities, a .NET Web API or a Java Rest API (either Spring Boot or Quarkus). GitHub Copilot is an AI-powered code assistant that helps developers write better code faster. It uses machine learning models trained on billions of lines of code to suggest whole lines or entire functions based on the context of what you’re working on. By using Copilot, you can learn how to write better code and improve your productivity. @@ -69,3 +69,4 @@ Run: - [Node Server](./exercisefiles/node/README.md) - [.NET Web API](./exercisefiles/dotnet/README.md) - [Java Spring Boot](./exercisefiles/springboot/README.md) +- [Java Quarkus](./exercisefiles/quarkus/README.md) diff --git a/completesolution/quarkus/README.md b/completesolution/quarkus/README.md new file mode 100644 index 0000000..2ae464d --- /dev/null +++ b/completesolution/quarkus/README.md @@ -0,0 +1,85 @@ +# Quarkus REST API Exercise + +## Goal + +The goal of this exercise is to learn how to use GitHub Copilot, using an exercise that consist of building a REST API using [Quarkus](https://quarkus.io/). + +## Exercises + +We have created a Quarkus project with some files already created, you can find the project in the folder **exercisefiles/quarkus**. + +Let's start copiloting!!! + +### 1. Create the code to handle a simple GET request + +Move to the 'DemoResource.java' file and start writing the code to handle a simple GET request. In this first exercise, we have provided a comment that describes the code you need to generate. Just press enter and wait a couple of seconds, Copilot will generate the code for you. If you are not happy with the code generated, you can press enter again and Copilot will generate a new code + +There is already a unit test implemented for this exercise, you can run it using the command `mvn test` before and after to validate that the code generated by Copilot is correct. + +Then, create a new unit test for the case when no key is provided in the request. + +After every exercise, feel free to package and run your application to test it. + +Package: `mvn package` + +Run: `mvn quarkus:dev` + +Test: `curl -v http://localhost:8080/hello?key=world` + +### 2. Dates comparison + +New operation under /diffdates that calculates the difference between two dates. The operation should receive two dates as parameter in format dd-MM-yyyy and return the difference in days. + +Additionally, create a unit test that validates the operation. + +From now on, you will have to create the unit tests for every new operation. Wasn't it easy with Copilot? + +### 3. Validate the format of a spanish phone + +Validate the format of a spanish phone number (+34 prefix, then 9 digits, starting with 6, 7 or 9). The operation should receive a phone number as parameter and return true if the format is correct, false otherwise. + +### 4. Validate the format of a spanish DNI + +Validate the format of a spanish DNI (8 digits and 1 letter). The operation should receive a DNI as parameter and return true if the format is correct, false otherwise. + +### 5. From color name to hexadecimal code + +Based on existing colors.json file under resources, given the name of the color as path parameter, return the hexadecimal code. If the color is not found, return 404 + +Hint: Use TDD. Start by creating the unit test and then implement the code. + +### 6. Jokes creator + +Create a new operation that call the API https://api.chucknorris.io/jokes/random and return the joke. + +### 7. URL parsing + +Given a url as query parameter, parse it and return the protocol, host, port, path and query parameters. The response should be in Json format. + +### 8. List files and folders + +List files and folders under a given path. The path should be a query parameter. The response should be in Json format. + +### 9. Word counting + +Given the path of a file and count the number of occurrence of a provided word. The path and the word should be query parameters. The response should be in Json format. + +### 10. Zipping + +Create a zip file with the content of a given folder. The path of the folder should be a query parameter. + +### 11. Containerize the application + +Use the Dockerfile provided to create a docker image of the application. In this case, the full content is provided, but in order build, run and test the docker image, you will use Copilot as well to generate the commands. + +I have created a DOCKER.md file where we will document the steps to build the application (native), build the container image, yun the container and test the container. + + + + + + + + + + diff --git a/completesolution/quarkus/copilot-demo/.dockerignore b/completesolution/quarkus/copilot-demo/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/completesolution/quarkus/copilot-demo/.gitignore b/completesolution/quarkus/copilot-demo/.gitignore new file mode 100644 index 0000000..8c7863e --- /dev/null +++ b/completesolution/quarkus/copilot-demo/.gitignore @@ -0,0 +1,43 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env + +# Plugin directory +/.quarkus/cli/plugins/ diff --git a/completesolution/quarkus/copilot-demo/.mvn/wrapper/.gitignore b/completesolution/quarkus/copilot-demo/.mvn/wrapper/.gitignore new file mode 100644 index 0000000..e72f5e8 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/completesolution/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java b/completesolution/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..84d1e60 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,98 @@ +/* + * 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 + * + * 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 java.io.IOException; +import java.io.InputStream; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +public final class MavenWrapperDownloader +{ + private static final String WRAPPER_VERSION = "3.2.0"; + + private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( "MVNW_VERBOSE" ) ); + + public static void main( String[] args ) + { + log( "Apache Maven Wrapper Downloader " + WRAPPER_VERSION ); + + if ( args.length != 2 ) + { + System.err.println( " - ERROR wrapperUrl or wrapperJarPath parameter missing" ); + System.exit( 1 ); + } + + try + { + log( " - Downloader started" ); + final URL wrapperUrl = new URL( args[0] ); + final String jarPath = args[1].replace( "..", "" ); // Sanitize path + final Path wrapperJarPath = Paths.get( jarPath ).toAbsolutePath().normalize(); + downloadFileFromURL( wrapperUrl, wrapperJarPath ); + log( "Done" ); + } + catch ( IOException e ) + { + System.err.println( "- Error downloading: " + e.getMessage() ); + if ( VERBOSE ) + { + e.printStackTrace(); + } + System.exit( 1 ); + } + } + + private static void downloadFileFromURL( URL wrapperUrl, Path wrapperJarPath ) + throws IOException + { + log( " - Downloading to: " + wrapperJarPath ); + if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null ) + { + final String username = System.getenv( "MVNW_USERNAME" ); + final char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray(); + Authenticator.setDefault( new Authenticator() + { + @Override + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication( username, password ); + } + } ); + } + try ( InputStream inStream = wrapperUrl.openStream() ) + { + Files.copy( inStream, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING ); + } + log( " - Downloader complete" ); + } + + private static void log( String msg ) + { + if ( VERBOSE ) + { + System.out.println( msg ); + } + } + +} diff --git a/completesolution/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties b/completesolution/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..70f4f50 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# 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 +# +# 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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.8/apache-maven-3.8.8-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/completesolution/quarkus/copilot-demo/DOCKER.md b/completesolution/quarkus/copilot-demo/DOCKER.md new file mode 100644 index 0000000..67c8d51 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/DOCKER.md @@ -0,0 +1,26 @@ +# Build a Quarkus native image + +## Build the native executable + +```bash +mvn clean package -Pnative +``` + +## Build the docker image using the Dockerfile.native-micro + +```bash +docker build -f Dockerfile.native-micro -t quarkus/quarkus-native-micro . +``` + +## Run the docker image + +```bash +docker run -i --rm -p 8080:8080 quarkus/quarkus-native-micro +``` + +## Test the application + +```bash +curl -v http://localhost:8080/hello +``` + diff --git a/completesolution/quarkus/copilot-demo/Dockerfile.native-micro b/completesolution/quarkus/copilot-demo/Dockerfile.native-micro new file mode 100644 index 0000000..1807ff8 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/Dockerfile.native-micro @@ -0,0 +1,16 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# It uses a micro base image, tuned for Quarkus native executables. +# +### +FROM quay.io/quarkus/quarkus-micro-image:2.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/completesolution/quarkus/copilot-demo/mvnw b/completesolution/quarkus/copilot-demo/mvnw new file mode 100644 index 0000000..8d937f4 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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/completesolution/quarkus/copilot-demo/mvnw.cmd b/completesolution/quarkus/copilot-demo/mvnw.cmd new file mode 100644 index 0000000..c4586b5 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/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 http://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/completesolution/quarkus/copilot-demo/pom.xml b/completesolution/quarkus/copilot-demo/pom.xml new file mode 100644 index 0000000..690d663 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + com.microsoft.hackathon.quarkus + copilot-demo + 1.0.0-SNAPSHOT + + 3.11.0 + 17 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.2.0.Final + true + 3.0.0 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-rest-client + + + io.quarkus + quarkus-rest-client-jackson + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + + native + + + native + + + + false + native + + + + diff --git a/completesolution/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java b/completesolution/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java new file mode 100644 index 0000000..64eb811 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java @@ -0,0 +1,273 @@ +package com.microsoft.hackathon.quarkus; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import io.quarkus.fs.util.ZipUtils; + + + + + +/* +* The Demo resource should be mapped to the root path. +* +* Create a GET operation to return the value of a key passed as query parameter in the request. +* +* If the key is not passed, return "key not passed". +* If the key is passed, return "hello ". +* +*/ + +@Path("/") +public class DemoResource { + + @GET + @Path("/hello") + @Produces(MediaType.TEXT_PLAIN) + public String hello(@QueryParam("key") String key) { + if (key == null) { + return "key not passed"; + } else { + return "hello " + key; + } + } + + // New operation under /diffdates that calculates the difference between two dates. The operation should receive two dates as parameter in format dd-MM-yyyy and return the difference in days. + + @GET + @Path("/diffdates") + @Produces(MediaType.TEXT_PLAIN) + public String diffdates(@QueryParam("date1") String date1, @QueryParam("date2") String date2) { + Objects.requireNonNull(date1, "date1 must not be null"); + Objects.requireNonNull(date2, "date2 must not be null"); + + try { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); + Date date1Obj = dateFormat.parse(date1); + Date date2Obj = dateFormat.parse(date2); + long diffMillis = Math.abs(date1Obj.getTime() - date2Obj.getTime()); + long diffDays = diffMillis / (24 * 60 * 60 * 1000); + return String.valueOf(diffDays); + } catch (Exception e) { + return "invalid date format"; + } + } + + // Validate the format of a spanish phone number (+34 prefix, then 9 digits, starting with 6, 7 or 9). The operation should receive a phone number as parameter and return true if the format is correct, false otherwise. + + @GET + @Path("/validatephone") + @Produces(MediaType.TEXT_PLAIN) + public boolean validatephone(@QueryParam("phone") String phone) { + Objects.requireNonNull(phone, "phone must not be null"); + if (!phone.matches("\\+34[679]\\d{8}")) { + return false; + } + + return true; + } + + // Validate the format of a spanish DNI (8 digits and 1 letter). The operation should receive a DNI as parameter and return true if the format is correct, false otherwise. + + @GET + @Path("/validatedni") + @Produces(MediaType.TEXT_PLAIN) + public boolean validatedni(@QueryParam("dni") String dni) { + Objects.requireNonNull(dni, "dni must not be null"); + + if (!dni.matches("\\d{8}[A-Z]")) { + return false; + } + + return true; + } + + // Based on existing colors.json file under resources, given the name of the color as path parameter, return the hexadecimal code. If the color is not found, return 404 + + @GET + @Path("/hexcolor") + @Produces(MediaType.TEXT_PLAIN) + public Response color(@QueryParam("name") String name) { + Objects.requireNonNull(name, "name must not be null"); + ObjectMapper mapper = new ObjectMapper(); + try { + InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("colors.json"); + JsonNode root = mapper.readTree(inputStream); + for (JsonNode color : root) { + if (color.get("color").asText().equals(name)) { + ObjectNode code = (ObjectNode) color.get("code"); + return Response.ok(code.get("hex").asText()).build(); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + // return http 404 + return Response.status(Response.Status.NOT_FOUND).build(); + } + + + // Create a new operation that call the API https://api.chucknorris.io/jokes/random and return the joke. + + @GET + @Path("/chucknorris") + @Produces(MediaType.TEXT_PLAIN) + public String chucknorris() { + // create a new instance of the Resteasy client + Client client = ClientBuilder.newClient(); + // create a new target + WebTarget target = client.target("https://api.chucknorris.io/jokes/random"); + // send the request and get the response + Response response = target.request(MediaType.APPLICATION_JSON).get(); + // parse the response + ObjectMapper mapper = new ObjectMapper(); + try { + JsonNode root = mapper.readTree(response.readEntity(String.class)); + return root.get("value").asText(); + } catch (IOException e) { + e.printStackTrace(); + } + return "error"; + } + + // Given a url as query parameter, parse it and return the protocol, host, port, path and query parameters. The response should be in Json format. + + @GET + @Path("/parseurl") + @Produces(MediaType.APPLICATION_JSON) + public Response parseurl(@QueryParam("url") String url) { + Objects.requireNonNull(url, "url must not be null"); + ObjectMapper mapper = new ObjectMapper(); + try { + URL urlNode = new URL(url); + JsonNode root = mapper.createObjectNode(); + ((ObjectNode) root).put("protocol", urlNode.getProtocol()); + ((ObjectNode) root).put("host", urlNode.getHost()); + ((ObjectNode) root).put("port", urlNode.getPort()); + ((ObjectNode) root).put("path", urlNode.getPath()); + ((ObjectNode) root).put("query", urlNode.getQuery()); + return Response.ok(root).build(); + } catch (IOException e) { + e.printStackTrace(); + } + // return http 500 + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + + // List files and folders under a given path. The path should be a query parameter. The response should be in Json format. + + @GET + @Path("/listfiles") + @Produces(MediaType.APPLICATION_JSON) + public Response listfiles(@QueryParam("path") String path) { + Objects.requireNonNull(path, "path must not be null"); + ObjectMapper mapper = new ObjectMapper(); + try { + List fileList = new ArrayList<>(); + Files.walk(Paths.get(path)) + .forEach(file -> { + ObjectNode fileNode = mapper.createObjectNode(); + fileNode.put("path", file.toString()); + fileNode.put("isDirectory", file.toFile().isDirectory()); + fileList.add(fileNode); + }); + + return Response.ok(fileList).build(); + } catch (Exception e) { + e.printStackTrace(); + } + // return http 500 + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + + // Given the path of a file and count the number of occurrence of a provided word. The path and the word should be query parameters. The response should be in Json format. + + @GET + @Path("/countword") + @Produces(MediaType.APPLICATION_JSON) + public Response countWord(@QueryParam("path") String path, @QueryParam("word") String word) { + Objects.requireNonNull(path, "path must not be null"); + Objects.requireNonNull(word, "word must not be null"); + java.nio.file.Path filePath = Paths.get(path); + String content; + int count = 0; + try { + content = Files.readString(filePath); + String[] words = content.split("\\s+"); + for (String w : words) { + if (w.equals(word)) { + count++; + } + } + } catch (IOException e) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + + ObjectMapper mapper = new ObjectMapper(); + ObjectNode responseNode = mapper.createObjectNode(); + responseNode.put("count", count); + return Response.ok(responseNode).build(); + } + + // Create a zip file with the content of a given folder. The path of the folder should be a query parameter. + + @GET + @Path("/zipfolder") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response zipFolder(@QueryParam("path") String path) { + Objects.requireNonNull(path, "path must not be null"); + java.nio.file.Path folderPath = Paths.get(path); + File folder = folderPath.toFile(); + if (!folder.exists()) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + if (!folder.isDirectory()) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + try { + // create a zip file from the folder + java.nio.file.Path zipPath = folderPath.getParent().resolve(folderPath.getFileName() + ".zip"); + ZipUtils.zip(folderPath, zipPath); + // return the zip file + InputStream inputStream = new FileInputStream(zipPath.toFile()); + Response.ResponseBuilder response = Response.ok(inputStream); + response.type("application/zip"); + response.header("Content-Disposition", "attachment; filename=\"" + folderPath.getFileName() + ".zip\""); + // remove the zip file + Files.delete(zipPath); + return response.build(); + } catch (IOException e) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } + +} + + + + diff --git a/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json b/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json new file mode 100644 index 0000000..9d8e8ad --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json @@ -0,0 +1,56 @@ + [ + { + "color": "black", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,0,1], + "hex": "#000000" + } + }, + { + "color": "white", + "category": "value", + "code": { + "rgba": [255,255,255,1], + "hex": "#FFFFFF" + } + }, + { + "color": "red", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,0,0,1], + "hex": "#FF0000" + } + }, + { + "color": "blue", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,255,1], + "hex": "#0000FF" + } + }, + { + "color": "yellow", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,255,0,1], + "hex": "#FFFF00" + } + }, + { + "color": "green", + "category": "hue", + "type": "secondary", + "code": { + "rgba": [0,255,0,1], + "hex": "#00FF00" + } + } + ] + \ No newline at end of file diff --git a/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html b/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html new file mode 100644 index 0000000..98c539e --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,284 @@ + + + + + copilot-demo - 1.0.0-SNAPSHOT + + + +
+
+
+ + + + + quarkus_logo_horizontal_rgb_1280px_reverse + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+
+

You just made a Quarkus application.

+

This page is served by Quarkus.

+ Visit the Dev UI +

This page: src/main/resources/META-INF/resources/index.html

+

App configuration: src/main/resources/application.properties

+

Static assets: src/main/resources/META-INF/resources/

+

Code: src/main/java

+

Dev UI V1: /q/dev-v1

+

Generated starter code:

+
    +
  • + RESTEasy JAX-RS Easily start your RESTful Web Services +
    @Path: /hello +
    Related guide +
  • + +
+
+
+

Selected extensions

+
    +
  • RESTEasy Classic (guide)
  • +
+
Documentation
+

Practical step-by-step guides to help you achieve a specific goal. Use them to help get your work + done.

+
Set up your IDE
+

Everyone has a favorite IDE they like to use to code. Learn how to configure yours to maximize your + Quarkus productivity.

+
+
+
+ + diff --git a/completesolution/quarkus/copilot-demo/src/main/resources/application.properties b/completesolution/quarkus/copilot-demo/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/completesolution/quarkus/copilot-demo/src/main/resources/colors.json b/completesolution/quarkus/copilot-demo/src/main/resources/colors.json new file mode 100644 index 0000000..9d8e8ad --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/main/resources/colors.json @@ -0,0 +1,56 @@ + [ + { + "color": "black", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,0,1], + "hex": "#000000" + } + }, + { + "color": "white", + "category": "value", + "code": { + "rgba": [255,255,255,1], + "hex": "#FFFFFF" + } + }, + { + "color": "red", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,0,0,1], + "hex": "#FF0000" + } + }, + { + "color": "blue", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,255,1], + "hex": "#0000FF" + } + }, + { + "color": "yellow", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,255,0,1], + "hex": "#FFFF00" + } + }, + { + "color": "green", + "category": "hue", + "type": "secondary", + "code": { + "rgba": [0,255,0,1], + "hex": "#00FF00" + } + } + ] + \ No newline at end of file diff --git a/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java b/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java new file mode 100644 index 0000000..9b7c530 --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java @@ -0,0 +1,8 @@ +package com.microsoft.hackathon.quarkus; + +import io.quarkus.test.junit.QuarkusIntegrationTest; + +@QuarkusIntegrationTest +public class DemoResourceIT extends DemoResourceTest { + // Execute the same tests but in packaged mode. +} diff --git a/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java b/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java new file mode 100644 index 0000000..31a9e3d --- /dev/null +++ b/completesolution/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java @@ -0,0 +1,200 @@ +package com.microsoft.hackathon.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +@QuarkusTest +public class DemoResourceTest { + + @Test + public void testHelloEndpoint() { + given() + .when().get("/hello?key=world") + .then() + .statusCode(200) + .body(is("hello world")); + } + + @Test + public void testHelloEndpointNoKey() { + given() + .when().get("/hello") + .then() + .statusCode(200) + .body(is("key not passed")); + } + + @Test + public void testDiffDatesEndpoint() { + given() + .when().get("/diffdates?date1=01-01-2021&date2=01-02-2021") + .then() + .statusCode(200) + .body(is("31")); + } + + @Test + public void testDiffDatesEndpointInvalidDate() { + given() + .when().get("/diffdates?date1=01-01201&date2=01-02-2021") + .then() + .statusCode(200) + .body(is("invalid date format")); + } + + @Test + public void testDiffDatesEndpointNoDate1() { + given() + .when().get("/diffdates?date2=01-02-2021") + .then() + .statusCode(500); + } + + @Test + public void testDiffDatesEndpointNoDate2() { + given() + .when().get("/diffdates?date1=01-02-2021") + .then() + .statusCode(500); + } + + @Test + public void testDiffDatesEndpointNoDates() { + given() + .when().get("/diffdates") + .then() + .statusCode(500); + } + + @Test + public void testValidatePhoneEndpoint() { + given() + .when().get("/validatephone?phone=+34666666666") + .then() + .statusCode(200) + .body(is("true")); + + given() + .when().get("/validatephone?phone=+34766666666") + .then() + .statusCode(200) + .body(is("true")); + + given() + .when().get("/validatephone?phone=+34966666666") + .then() + .statusCode(200) + .body(is("true")); + } + + @Test + public void testValidatePhoneEndpointInvalidPhone() { + given() + .when().get("/validatephone?phone=+3466666666") + .then() + .statusCode(200) + .body(is("false")); + } + + @Test + public void testValidatePhoneEndpointNoPhone() { + given() + .when().get("/validatephone") + .then() + .statusCode(500); + } + + + @Test + public void testValidatePhoneEndpointNoPrefix() { + given() + .when().get("/validatephone?phone=666666666") + .then() + .statusCode(200) + .body(is("false")); + } + + @Test + public void testValidateDNIEndpoint () { + given() + .when().get("/validatedni?dni=12345678Z") + .then() + .statusCode(200) + .body(is("true")); + } + + @Test + public void testValidateDNIEndpointInvalidDNI () { + given() + .when().get("/validatedni?dni=12345678") + .then() + .statusCode(200) + .body(is("false")); + } + + @Test + public void testValidateDNIEndpointNoDNI () { + given() + .when().get("/validatedni") + .then() + .statusCode(500); + } + + @Test + public void testGetHexColorEndpoint () { + given() + .when().get("/hexcolor?name=red") + .then() + .statusCode(200) + .body(is("#FF0000")); + } + + @Test + public void testGetHexColorEndpointInvalidColor () { + given() + .when().get("/hexcolor?name=red1") + .then() + .statusCode(404); + } + + @Test + public void testGetHexColorEndpointNoColor () { + given() + .when().get("/hexcolor") + .then() + .statusCode(500); + } + + @Test + public void testChuckNorrisEndpoint () { + given() + .when().get("/chucknorris") + .then() + .statusCode(200); + } + + @Test + public void testParseUrlEndpoint () { + given() + .when().get("/parseurl?url=https://learn.microsoft.com/en-us/azure/aks/concepts-clusters-workloads?source=recommendations") + .then() + .statusCode(200) + .body("protocol", is("https")) + .body("host", is("learn.microsoft.com")) + .body("port", is(-1)) + .body("path", is("/en-us/azure/aks/concepts-clusters-workloads")) + .body("query", is("source=recommendations")); + } + + @Test + public void testParseUrlEndpointNoUrl () { + given() + .when().get("/parseurl") + .then() + .statusCode(500); + } + +} \ No newline at end of file diff --git a/completesolution/springboot/copilot-demo/Dockerfile b/completesolution/springboot/copilot-demo/Dockerfile index aa49f54..f83e60a 100644 --- a/completesolution/springboot/copilot-demo/Dockerfile +++ b/completesolution/springboot/copilot-demo/Dockerfile @@ -1 +1,5 @@ # Build a java application image based on openjdk 17 and run it on port 8080 +FROM openjdk:17-jdk-alpine +EXPOSE 8080 +COPY target/*.jar app.jar +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/completesolution/springboot/copilot-demo/pom.xml b/completesolution/springboot/copilot-demo/pom.xml index 3762aa7..b806182 100644 --- a/completesolution/springboot/copilot-demo/pom.xml +++ b/completesolution/springboot/copilot-demo/pom.xml @@ -27,6 +27,13 @@ spring-boot-starter-test test + + + org.json + json + 20230618 + + diff --git a/completesolution/springboot/copilot-demo/src/main/java/com/microsoft/hackathon/copilotdemo/controller/DemoController.java b/completesolution/springboot/copilot-demo/src/main/java/com/microsoft/hackathon/copilotdemo/controller/DemoController.java index 60068a5..dd255bf 100644 --- a/completesolution/springboot/copilot-demo/src/main/java/com/microsoft/hackathon/copilotdemo/controller/DemoController.java +++ b/completesolution/springboot/copilot-demo/src/main/java/com/microsoft/hackathon/copilotdemo/controller/DemoController.java @@ -1,8 +1,40 @@ package com.microsoft.hackathon.copilotdemo.controller; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Scanner; +import java.util.concurrent.TimeUnit; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + /* * Create a GET operation to return the value of a key passed as query parameter. @@ -10,3 +42,197 @@ * If the key is passed, return "hello ". * */ + +@RestController +public class DemoController { + + @GetMapping("/hello") + public String hello(@RequestParam(name = "key", required = false) String key) { + if (key == null) { + return "key not passed"; + } + return "hello " + key; + } + + // New operation under /diffdates that calculates the difference between two dates. The operation should receive two dates as parameter in format dd-MM-yyyy and return the difference in days. + @GetMapping("/diffdates") + public String diffdates(@RequestParam(name = "date1", required = false) String date1, @RequestParam(name = "date2", required = false) String date2) throws ParseException { + if (date1 == null || date2 == null) { + return "date not passed"; + } + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + Date date1Obj = sdf.parse(date1); + Date date2Obj = sdf.parse(date2); + long diffInMillies = Math.abs(date2Obj.getTime() - date1Obj.getTime()); + long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); + return "difference in days: " + diff; + } + + // Validate the format of a spanish phone number (+34 prefix, then 9 digits, starting with 6, 7 or 9). The operation should receive a phone number as parameter and return true if the format is correct, false otherwise. + @GetMapping("/validatephone") + public boolean validatephone(@RequestParam(name = "phone", required = false) String phone) { + if (phone == null || phone.isEmpty()) { + return false; + } + String regex = "^\\+34[679]\\d{8}$"; + return phone.matches(regex); + } + + // Validate the format of a spanish DNI (8 digits and 1 letter). The operation should receive a DNI as parameter and return true if the format is correct, false otherwise. + @GetMapping("/validatedni") + public boolean validatedni(@RequestParam(name = "dni", required = false) String dni) { + if (dni == null || dni.isEmpty()) { + return false; + } + String regex = "^\\d{8}[A-Z]$"; + return dni.matches(regex); + } + + //Based on existing colors.json file under resources, given the name of the color as path parameter, return the hexadecimal code. If the color is not found, return 404 + @GetMapping("/color/{name}") + public ResponseEntity color(@PathVariable("name") String name) throws IOException { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream("colors.json"); + ObjectMapper objectMapper = new ObjectMapper(); + // create JsonNode from mapper + JsonNode rootNode = objectMapper.readTree(inputStream); + for (JsonNode color : rootNode) { + // if color name is found, return the hex code + if (color.get("color").asText().equals(name)) { + return new ResponseEntity(color.get("code").get("hex").asText(), HttpStatus.OK); + } + } + return new ResponseEntity("Color not found", HttpStatus.NOT_FOUND); + } + + // new operation that call the API https://api.chucknorris.io/jokes/random and return the joke + @GetMapping("/joke") + public String getJoke() { + RestTemplate restTemplate = new RestTemplate(); + String url = "https://api.chucknorris.io/jokes/random"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + // parse response to get the value + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode rootNode; + try { + rootNode = objectMapper.readTree(response.getBody()); + return rootNode.get("value").asText(); + } catch (IOException e) { + return new String("Error getting joke"); + } + } + + + // Given a url as query parameter, parse it and return the protocol, host, port, path and query parameters. The response should be in Json format. + @GetMapping("/parseurl") + public String parseurl(@RequestParam(name = "url", required = false) String url) throws MalformedURLException { + if (url == null || url.isEmpty()) { + return "url not passed"; + } + URL urlObj = new URL(url); + String protocol = urlObj.getProtocol(); + String host = urlObj.getHost(); + int port = urlObj.getPort(); + String path = urlObj.getPath(); + String query = urlObj.getQuery(); + return "{ \"protocol\": \"" + protocol + "\", \"host\": \"" + host + "\", \"port\": \"" + port + "\", \"path\": \"" + path + "\", \"query\": \"" + query + "\" }"; + } + + // List files and folders under a given path. The path should be a query parameter. The response should be in Json format. + @GetMapping("/list-files") + public ResponseEntity listFiles(@RequestParam(name = "path") String pathString) { + try { + File path = new File(pathString); + if (!path.exists()) { + return ResponseEntity.notFound().build(); + } + if (!path.isDirectory()) { + return ResponseEntity.badRequest().body("Path is not a directory"); + } + File[] files = path.listFiles(); + JSONArray jsonArray = new JSONArray(); + for (File file : files) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", file.getName()); + jsonObject.put("isDirectory", file.isDirectory()); + jsonArray.put(jsonObject); + } + return ResponseEntity.ok(jsonArray.toString()); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error listing files"); + } + } + + // Given the path of a file and count the number of occurrence of a provided word. The path and the word should be query parameters. The response should be in Json format. + @GetMapping("/count-word") + public ResponseEntity countWord(@RequestParam(name = "path") String pathString, @RequestParam(name = "word") String word) { + try { + File file = new File(pathString); + if (!file.exists()) { + return ResponseEntity.notFound().build(); + } + if (!file.isFile()) { + return ResponseEntity.badRequest().body("Path is not a file"); + } + int count = 0; + try (Scanner scanner = new Scanner(file)) { + while (scanner.hasNext()) { + if (scanner.next().equals(word)) { + count++; + } + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("count", count); + return ResponseEntity.ok(jsonObject.toString()); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error counting word"); + } + } + + // Create a zip file with the content of a given folder. The path of the folder should be a query parameter. + @GetMapping("/zip-folder") + public ResponseEntity zipFolder(@RequestParam(name = "path") String pathString) { + try { + File folder = new File(pathString); + if (!folder.exists()) { + return ResponseEntity.notFound().build(); + } + if (!folder.isDirectory()) { + return ResponseEntity.badRequest().body(null); + } + String zipFileName = folder.getName() + ".zip"; + File zipFile = new File(zipFileName); + FileOutputStream fos = new FileOutputStream(zipFile); + ZipOutputStream zos = new ZipOutputStream(fos); + zipFolder(folder, folder.getName(), zos); + zos.close(); + fos.close(); + Path path = Paths.get(zipFileName); + ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path)); + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + zipFileName); + return ResponseEntity.ok().headers(headers).contentLength(zipFile.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(resource); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); + } + } + + private void zipFolder(File folder, String parentFolder, ZipOutputStream zos) throws IOException { + for (File file : folder.listFiles()) { + if (file.isDirectory()) { + zipFolder(file, parentFolder + "/" + file.getName(), zos); + } else { + ZipEntry zipEntry = new ZipEntry(parentFolder + "/" + file.getName()); + zos.putNextEntry(zipEntry); + FileInputStream fis = new FileInputStream(file); + byte[] buffer = new byte[1024]; + int length; + while ((length = fis.read(buffer)) > 0) { + zos.write(buffer, 0, length); + } + fis.close(); + } + } + } + +} diff --git a/completesolution/springboot/copilot-demo/src/test/java/com/microsoft/hackathon/copilotdemo/CopilotDemoApplicationTests.java b/completesolution/springboot/copilot-demo/src/test/java/com/microsoft/hackathon/copilotdemo/CopilotDemoApplicationTests.java index 060d615..4504806 100644 --- a/completesolution/springboot/copilot-demo/src/test/java/com/microsoft/hackathon/copilotdemo/CopilotDemoApplicationTests.java +++ b/completesolution/springboot/copilot-demo/src/test/java/com/microsoft/hackathon/copilotdemo/CopilotDemoApplicationTests.java @@ -1,5 +1,8 @@ package com.microsoft.hackathon.copilotdemo; +import static org.mockito.Mockito.mock; + +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; @@ -23,4 +26,143 @@ void hello() throws Exception { .andExpect(MockMvcResultMatchers.content().string("hello world")); } -} \ No newline at end of file + @Test + void helloNoKey() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/hello")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("key not passed")); + } + + @Test + void diffdates() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/diffdates?date1=01-01-2021&date2=01-02-2021")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("difference in days: 31")); + } + + @Test + void diffdatesNoDate1() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/diffdates?date2=01-02-2021")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("date not passed")); + } + + @Test + void diffdatesNoDate2() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/diffdates?date1=01-01-2021")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("date not passed")); + } + + @Test + void validatephone() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+34666666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("true")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+34766666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("true")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+34966666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("true")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+3466666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+346666666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+3466666666a")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone?phone=+34866666666")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + } + + @Test + void validatephoneNoPhone() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/validatephone")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + } + + @Test + void validatedni() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni?dni=12345678A")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("true")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni?dni=12345678a")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni?dni=1234567A")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni?dni=123456789A")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni?dni=12345678")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + + } + + @Test + void validatedniNoDni() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/validatedni")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("false")); + } + + // test for /color/{color} endpoint + @Test + void color() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/color/red")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("#FF0000")); + } + + @Test + void colorNotFound() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/color/purple")) + .andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void joke() throws Exception{ + mockMvc.perform(MockMvcRequestBuilders.get("/joke")) + .andExpect(MockMvcResultMatchers.status().isOk()) + // check that content is a string + .andExpect(MockMvcResultMatchers.content().string(Matchers.any(String.class))); + + } + + @Test + void parseUrl() throws Exception{ + mockMvc.perform(MockMvcRequestBuilders.get("/parseurl?url=https://learn.microsoft.com/en-us/azure/aks/concepts-clusters-workloads?source=recommendations")) + .andExpect(MockMvcResultMatchers.status().isOk()) + // validate json fields + .andExpect(MockMvcResultMatchers.jsonPath("$.protocol").value("https")) + .andExpect(MockMvcResultMatchers.jsonPath("$.host").value("learn.microsoft.com")) + .andExpect(MockMvcResultMatchers.jsonPath("$.path").value("/en-us/azure/aks/concepts-clusters-workloads")) + .andExpect(MockMvcResultMatchers.jsonPath("$.query").value("source=recommendations")); + + } + + @Test + void parseUrlNoUrl() throws Exception{ + mockMvc.perform(MockMvcRequestBuilders.get("/parseurl")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string("url not passed")); + } + +} diff --git a/exercisefiles/quarkus/README.md b/exercisefiles/quarkus/README.md new file mode 100644 index 0000000..2ae464d --- /dev/null +++ b/exercisefiles/quarkus/README.md @@ -0,0 +1,85 @@ +# Quarkus REST API Exercise + +## Goal + +The goal of this exercise is to learn how to use GitHub Copilot, using an exercise that consist of building a REST API using [Quarkus](https://quarkus.io/). + +## Exercises + +We have created a Quarkus project with some files already created, you can find the project in the folder **exercisefiles/quarkus**. + +Let's start copiloting!!! + +### 1. Create the code to handle a simple GET request + +Move to the 'DemoResource.java' file and start writing the code to handle a simple GET request. In this first exercise, we have provided a comment that describes the code you need to generate. Just press enter and wait a couple of seconds, Copilot will generate the code for you. If you are not happy with the code generated, you can press enter again and Copilot will generate a new code + +There is already a unit test implemented for this exercise, you can run it using the command `mvn test` before and after to validate that the code generated by Copilot is correct. + +Then, create a new unit test for the case when no key is provided in the request. + +After every exercise, feel free to package and run your application to test it. + +Package: `mvn package` + +Run: `mvn quarkus:dev` + +Test: `curl -v http://localhost:8080/hello?key=world` + +### 2. Dates comparison + +New operation under /diffdates that calculates the difference between two dates. The operation should receive two dates as parameter in format dd-MM-yyyy and return the difference in days. + +Additionally, create a unit test that validates the operation. + +From now on, you will have to create the unit tests for every new operation. Wasn't it easy with Copilot? + +### 3. Validate the format of a spanish phone + +Validate the format of a spanish phone number (+34 prefix, then 9 digits, starting with 6, 7 or 9). The operation should receive a phone number as parameter and return true if the format is correct, false otherwise. + +### 4. Validate the format of a spanish DNI + +Validate the format of a spanish DNI (8 digits and 1 letter). The operation should receive a DNI as parameter and return true if the format is correct, false otherwise. + +### 5. From color name to hexadecimal code + +Based on existing colors.json file under resources, given the name of the color as path parameter, return the hexadecimal code. If the color is not found, return 404 + +Hint: Use TDD. Start by creating the unit test and then implement the code. + +### 6. Jokes creator + +Create a new operation that call the API https://api.chucknorris.io/jokes/random and return the joke. + +### 7. URL parsing + +Given a url as query parameter, parse it and return the protocol, host, port, path and query parameters. The response should be in Json format. + +### 8. List files and folders + +List files and folders under a given path. The path should be a query parameter. The response should be in Json format. + +### 9. Word counting + +Given the path of a file and count the number of occurrence of a provided word. The path and the word should be query parameters. The response should be in Json format. + +### 10. Zipping + +Create a zip file with the content of a given folder. The path of the folder should be a query parameter. + +### 11. Containerize the application + +Use the Dockerfile provided to create a docker image of the application. In this case, the full content is provided, but in order build, run and test the docker image, you will use Copilot as well to generate the commands. + +I have created a DOCKER.md file where we will document the steps to build the application (native), build the container image, yun the container and test the container. + + + + + + + + + + diff --git a/exercisefiles/quarkus/copilot-demo/.dockerignore b/exercisefiles/quarkus/copilot-demo/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/exercisefiles/quarkus/copilot-demo/.gitignore b/exercisefiles/quarkus/copilot-demo/.gitignore new file mode 100644 index 0000000..8c7863e --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/.gitignore @@ -0,0 +1,43 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env + +# Plugin directory +/.quarkus/cli/plugins/ diff --git a/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/.gitignore b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/.gitignore new file mode 100644 index 0000000..e72f5e8 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..84d1e60 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,98 @@ +/* + * 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 + * + * 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 java.io.IOException; +import java.io.InputStream; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +public final class MavenWrapperDownloader +{ + private static final String WRAPPER_VERSION = "3.2.0"; + + private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( "MVNW_VERBOSE" ) ); + + public static void main( String[] args ) + { + log( "Apache Maven Wrapper Downloader " + WRAPPER_VERSION ); + + if ( args.length != 2 ) + { + System.err.println( " - ERROR wrapperUrl or wrapperJarPath parameter missing" ); + System.exit( 1 ); + } + + try + { + log( " - Downloader started" ); + final URL wrapperUrl = new URL( args[0] ); + final String jarPath = args[1].replace( "..", "" ); // Sanitize path + final Path wrapperJarPath = Paths.get( jarPath ).toAbsolutePath().normalize(); + downloadFileFromURL( wrapperUrl, wrapperJarPath ); + log( "Done" ); + } + catch ( IOException e ) + { + System.err.println( "- Error downloading: " + e.getMessage() ); + if ( VERBOSE ) + { + e.printStackTrace(); + } + System.exit( 1 ); + } + } + + private static void downloadFileFromURL( URL wrapperUrl, Path wrapperJarPath ) + throws IOException + { + log( " - Downloading to: " + wrapperJarPath ); + if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null ) + { + final String username = System.getenv( "MVNW_USERNAME" ); + final char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray(); + Authenticator.setDefault( new Authenticator() + { + @Override + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication( username, password ); + } + } ); + } + try ( InputStream inStream = wrapperUrl.openStream() ) + { + Files.copy( inStream, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING ); + } + log( " - Downloader complete" ); + } + + private static void log( String msg ) + { + if ( VERBOSE ) + { + System.out.println( msg ); + } + } + +} diff --git a/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..70f4f50 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# 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 +# +# 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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.8/apache-maven-3.8.8-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/exercisefiles/quarkus/copilot-demo/DOCKER.md b/exercisefiles/quarkus/copilot-demo/DOCKER.md new file mode 100644 index 0000000..f0bd0d9 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/DOCKER.md @@ -0,0 +1,15 @@ +# Build a Quarkus native image + +## Build the native executable + + +## Build the docker image using the Dockerfile.native-micro + + +## Run the docker image + + +## Test the application + + + diff --git a/exercisefiles/quarkus/copilot-demo/Dockerfile.native-micro b/exercisefiles/quarkus/copilot-demo/Dockerfile.native-micro new file mode 100644 index 0000000..1807ff8 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/Dockerfile.native-micro @@ -0,0 +1,16 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# It uses a micro base image, tuned for Quarkus native executables. +# +### +FROM quay.io/quarkus/quarkus-micro-image:2.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/exercisefiles/quarkus/copilot-demo/mvnw b/exercisefiles/quarkus/copilot-demo/mvnw new file mode 100644 index 0000000..8d937f4 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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/exercisefiles/quarkus/copilot-demo/mvnw.cmd b/exercisefiles/quarkus/copilot-demo/mvnw.cmd new file mode 100644 index 0000000..c4586b5 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/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 http://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/exercisefiles/quarkus/copilot-demo/pom.xml b/exercisefiles/quarkus/copilot-demo/pom.xml new file mode 100644 index 0000000..690d663 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/pom.xml @@ -0,0 +1,129 @@ + + + 4.0.0 + com.microsoft.hackathon.quarkus + copilot-demo + 1.0.0-SNAPSHOT + + 3.11.0 + 17 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.2.0.Final + true + 3.0.0 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-rest-client + + + io.quarkus + quarkus-rest-client-jackson + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + + native + + + native + + + + false + native + + + + diff --git a/exercisefiles/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java b/exercisefiles/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java new file mode 100644 index 0000000..3279987 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/main/java/com/microsoft/hackathon/quarkus/DemoResource.java @@ -0,0 +1,17 @@ +package com.microsoft.hackathon.quarkus; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; + +/* +* The Demo resource should be mapped to the root path. +* +* Create a GET operation to return the value of a key passed as query parameter in the request. +* +* If the key is not passed, return "key not passed". +* If the key is passed, return "hello ". +* +*/ diff --git a/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json b/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json new file mode 100644 index 0000000..9d8e8ad --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/colors.json @@ -0,0 +1,56 @@ + [ + { + "color": "black", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,0,1], + "hex": "#000000" + } + }, + { + "color": "white", + "category": "value", + "code": { + "rgba": [255,255,255,1], + "hex": "#FFFFFF" + } + }, + { + "color": "red", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,0,0,1], + "hex": "#FF0000" + } + }, + { + "color": "blue", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,255,1], + "hex": "#0000FF" + } + }, + { + "color": "yellow", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,255,0,1], + "hex": "#FFFF00" + } + }, + { + "color": "green", + "category": "hue", + "type": "secondary", + "code": { + "rgba": [0,255,0,1], + "hex": "#00FF00" + } + } + ] + \ No newline at end of file diff --git a/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html b/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html new file mode 100644 index 0000000..98c539e --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,284 @@ + + + + + copilot-demo - 1.0.0-SNAPSHOT + + + +
+
+
+ + + + + quarkus_logo_horizontal_rgb_1280px_reverse + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+
+

You just made a Quarkus application.

+

This page is served by Quarkus.

+ Visit the Dev UI +

This page: src/main/resources/META-INF/resources/index.html

+

App configuration: src/main/resources/application.properties

+

Static assets: src/main/resources/META-INF/resources/

+

Code: src/main/java

+

Dev UI V1: /q/dev-v1

+

Generated starter code:

+
    +
  • + RESTEasy JAX-RS Easily start your RESTful Web Services +
    @Path: /hello +
    Related guide +
  • + +
+
+
+

Selected extensions

+
    +
  • RESTEasy Classic (guide)
  • +
+
Documentation
+

Practical step-by-step guides to help you achieve a specific goal. Use them to help get your work + done.

+
Set up your IDE
+

Everyone has a favorite IDE they like to use to code. Learn how to configure yours to maximize your + Quarkus productivity.

+
+
+
+ + diff --git a/exercisefiles/quarkus/copilot-demo/src/main/resources/application.properties b/exercisefiles/quarkus/copilot-demo/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/exercisefiles/quarkus/copilot-demo/src/main/resources/colors.json b/exercisefiles/quarkus/copilot-demo/src/main/resources/colors.json new file mode 100644 index 0000000..9d8e8ad --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/main/resources/colors.json @@ -0,0 +1,56 @@ + [ + { + "color": "black", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,0,1], + "hex": "#000000" + } + }, + { + "color": "white", + "category": "value", + "code": { + "rgba": [255,255,255,1], + "hex": "#FFFFFF" + } + }, + { + "color": "red", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,0,0,1], + "hex": "#FF0000" + } + }, + { + "color": "blue", + "category": "hue", + "type": "primary", + "code": { + "rgba": [0,0,255,1], + "hex": "#0000FF" + } + }, + { + "color": "yellow", + "category": "hue", + "type": "primary", + "code": { + "rgba": [255,255,0,1], + "hex": "#FFFF00" + } + }, + { + "color": "green", + "category": "hue", + "type": "secondary", + "code": { + "rgba": [0,255,0,1], + "hex": "#00FF00" + } + } + ] + \ No newline at end of file diff --git a/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java b/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java new file mode 100644 index 0000000..9b7c530 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceIT.java @@ -0,0 +1,8 @@ +package com.microsoft.hackathon.quarkus; + +import io.quarkus.test.junit.QuarkusIntegrationTest; + +@QuarkusIntegrationTest +public class DemoResourceIT extends DemoResourceTest { + // Execute the same tests but in packaged mode. +} diff --git a/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java b/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java new file mode 100644 index 0000000..7de1701 --- /dev/null +++ b/exercisefiles/quarkus/copilot-demo/src/test/java/com/microsoft/hackathon/quarkus/DemoResourceTest.java @@ -0,0 +1,21 @@ +package com.microsoft.hackathon.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +@QuarkusTest +public class DemoResourceTest { + + @Test + public void testHelloEndpoint() { + given() + .when().get("/hello?key=world") + .then() + .statusCode(200) + .body(is("hello world")); + } + +} \ No newline at end of file diff --git a/exercisefiles/springboot/README.md b/exercisefiles/springboot/README.md index 11f5def..afc79e9 100644 --- a/exercisefiles/springboot/README.md +++ b/exercisefiles/springboot/README.md @@ -24,7 +24,7 @@ Package: `mvn package` Run: `mvn spring-boot:run` -Test: `curl -v http://localhost:8080/demo?key=1234` +Test: `curl -v http://localhost:8080/hello?key=world` ### 2. Dates comparison @@ -72,7 +72,7 @@ Create a zip file with the content of a given folder. The path of the folder sho Use the Dockerfile provided to create a docker image of the application. There are some comments in the Dockerfile that will help you to complete the exercise. -In order build, run and test the docker image, you can use Copilot as well to generate the commands. +In order to build, run and test the docker image, you can use Copilot as well to generate the commands. For instance, create a DOCKER.md file where you can store the commands to build, run and test the docker image. You will notice that Copilot will also help you to document your project and commands. @@ -86,4 +86,3 @@ Examples of steps to document: Build the container image, Run the container, Tes -