diff --git a/.github/workflows/check_lesson_09_pr.yaml b/.github/workflows/check_lesson_09_pr.yaml new file mode 100644 index 000000000..c7672772b --- /dev/null +++ b/.github/workflows/check_lesson_09_pr.yaml @@ -0,0 +1,27 @@ +name: Check Lesson 09 Pull Request + +on: + pull_request: + branches: [ "main" ] + paths: + - "lesson_09/types/**" + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + - name: Build Lesson 09 with Gradle + working-directory: ./lesson_09/types + run: ./gradlew check \ No newline at end of file diff --git a/.github/workflows/check_push.yml b/.github/workflows/check_push.yml index eeba200e6..32690597d 100644 --- a/.github/workflows/check_push.yml +++ b/.github/workflows/check_push.yml @@ -7,6 +7,9 @@ on: - "lib/**" - "lesson_02/quiz/**" - "lesson_03/quiz/**" + - "lesson_06/expression/**" + - "lesson_07/conditionals/**" + - "lesson_09/types/**" jobs: build: @@ -68,4 +71,8 @@ jobs: npm ci npm run compile + - name: Build Lesson 09 with Gradle + working-directory: ./lesson_09/types + run: ./gradlew check + diff --git a/lesson_09/README.md b/lesson_09/README.md index e50d276d7..4400ddf37 100644 --- a/lesson_09/README.md +++ b/lesson_09/README.md @@ -10,4 +10,23 @@ Please review the following resources before lecture: ## Homework -TODO(anthonydmays): Finish this. \ No newline at end of file +- [ ] Complete [data types exercise](#choosing-the-right-data-types). + +### Choosing the Right Data Types + +For this exercise, you will use your knowledge of data types to identify the appropriate type to store and process data. You will run a program to generate a unique file with sample data, then write code to provide the correct data type of each column. + +1. Execute the app providing a unique provider name. + +```bash +./gradlew bootRun --args="yourprovidername" # Substitute with your own value +``` +2. Examine the file that was created for you in the [resources/data][resources-folder] folder. The file will be formatted using the [JSON][json-link] data format. +3. Next, you will create a `DataProvider` implementation that will provide information about the data types for the columns in the file (e.g. `column1`, `column2`, etc.). You can view the example [AnthonyMaysProvider.java][example-file] file. +4. Customize the data types map by choosing the closest appropriate data type of each column. Each data type should only be used **once**. +5. As usual, make sure to apply the formatter and run the tests to confirm that you've implemented everything correctly. +6. You are to submit a PR with your `DataProvider` implementation and the generated `.json` file that was produced for you. All build checks must pass in order to receive full credit. + +[json-link]: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON +[resources-folder]: ./types/types_app/src/main/resources/data/ +[example-file]: ./types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/AnthonyMaysProvider.java diff --git a/lesson_09/types/.gitattributes b/lesson_09/types/.gitattributes new file mode 100644 index 000000000..097f9f98d --- /dev/null +++ b/lesson_09/types/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/lesson_09/types/.gitignore b/lesson_09/types/.gitignore new file mode 100644 index 000000000..1b6985c00 --- /dev/null +++ b/lesson_09/types/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/lesson_09/types/gradle/wrapper/gradle-wrapper.jar b/lesson_09/types/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..ccebba771 Binary files /dev/null and b/lesson_09/types/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lesson_09/types/gradle/wrapper/gradle-wrapper.properties b/lesson_09/types/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..bdc9a83b1 --- /dev/null +++ b/lesson_09/types/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/lesson_09/types/gradlew b/lesson_09/types/gradlew new file mode 100755 index 000000000..79a61d421 --- /dev/null +++ b/lesson_09/types/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/lesson_09/types/gradlew.bat b/lesson_09/types/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/lesson_09/types/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lesson_09/types/settings.gradle.kts b/lesson_09/types/settings.gradle.kts new file mode 100644 index 000000000..d549f8109 --- /dev/null +++ b/lesson_09/types/settings.gradle.kts @@ -0,0 +1,13 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html + */ + +includeBuild("../../lib/java/codedifferently-instructional") + +rootProject.name = "lesson_09" +include("types_app") diff --git a/lesson_09/types/types_app/build.gradle.kts b/lesson_09/types/types_app/build.gradle.kts new file mode 100644 index 000000000..75d26ef3a --- /dev/null +++ b/lesson_09/types/types_app/build.gradle.kts @@ -0,0 +1,64 @@ +plugins { + // Apply the application plugin to add support for building a CLI application in Java. + application + eclipse + id("com.diffplug.spotless") version "6.25.0" + id("org.springframework.boot") version "3.2.2" + id("com.adarshr.test-logger") version "4.0.0" +} + +apply(plugin = "io.spring.dependency-management") + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + // Use JUnit Jupiter for testing. + testImplementation("com.codedifferently.instructional:instructional-lib") + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.assertj:assertj-core:3.25.1") + testImplementation("at.favre.lib:bcrypt:0.10.2") + + // This dependency is used by the application. + implementation("com.codedifferently.instructional:instructional-lib") + implementation("com.google.guava:guava:31.1-jre") + implementation("com.google.code.gson:gson:2.10.1") + implementation("org.projectlombok:lombok:1.18.30") + implementation("org.springframework.boot:spring-boot-starter") +} + +application { + // Define the main class for the application. + mainClass.set("com.codedifferently.lesson9.Lesson9") +} + +tasks.named("test") { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} + + +configure { + + format("misc", { + // define the files to apply `misc` to + target("*.gradle", ".gitattributes", ".gitignore") + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithTabs() // or spaces. Takes an integer argument if you don't like 4 + endWithNewline() + }) + + java { + // don't need to set target, it is inferred from java + + // apply a specific flavor of google-java-format + googleJavaFormat() + // fix formatting of type annotations + formatAnnotations() + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/Lesson9.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/Lesson9.java new file mode 100644 index 000000000..537012759 --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/Lesson9.java @@ -0,0 +1,41 @@ +package com.codedifferently.lesson9; + +import com.codedifferently.lesson9.generator.SampleFileGenerator; +import java.io.File; +import java.nio.file.Paths; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SpringBootApplication(scanBasePackages = "com.codedifferently") +public class Lesson9 implements CommandLineRunner { + + public static void main(String[] args) { + var application = new SpringApplication(Lesson9.class); + application.run(args); + } + + public void run(String... args) throws Exception { + if (args.length == 0) { + return; + } + + var providerName = args[0]; + if (providerName == null) { + throw new IllegalArgumentException("Provider name is required"); + } + + String path = getDataPath(); + var fileGenerator = new SampleFileGenerator(); + fileGenerator.createTestFile(path, providerName); + } + + private static String getDataPath() { + String[] pathParts = { + Paths.get("").toAbsolutePath().toString(), "src", "main", "resources", "data" + }; + return String.join(File.separator, pathParts); + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/AnthonyMaysProvider.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/AnthonyMaysProvider.java new file mode 100644 index 000000000..437665660 --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/AnthonyMaysProvider.java @@ -0,0 +1,22 @@ +package com.codedifferently.lesson9.dataprovider; + +import java.util.Map; +import org.springframework.stereotype.Service; + +@Service +public class AnthonyMaysProvider extends DataProvider { + public String getProviderName() { + return "anthonymays"; + } + + public Map getColumnTypeByName() { + return Map.of( + "column1", Integer.class, + "column2", String.class, + "column3", Boolean.class, + "column4", Float.class, + "column5", Double.class, + "column6", Long.class, + "column7", Short.class); + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/DataProvider.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/DataProvider.java new file mode 100644 index 000000000..595357609 --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/dataprovider/DataProvider.java @@ -0,0 +1,51 @@ +package com.codedifferently.lesson9.dataprovider; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * This class is a base class for data providers. It provides a method for parsing data from a list + * of maps. + */ +public abstract class DataProvider { + /** Returns the name of the provider. */ + public abstract String getProviderName(); + + /** Gets a map of column types keyed by column name. */ + public abstract Map getColumnTypeByName(); + + /** + * Given a list of data objects, returns the list with values converted to the appropriate type. + * + * @param data A list of data objects containing values keyed by column name. + * @return A new list with object values converted to the appropriate type. + */ + public List> parseData(List> data) throws Exception { + Map columnTypeByName = getColumnTypeByName(); + return data.stream().map(row -> parseRow(columnTypeByName, row)).collect(Collectors.toList()); + } + + /** + * Parses a single row of data using the provided column types mapping. + * + * @param columnTypeByName A map containing the type of a column keyed by its name. + * @param row A bag of values keyed by column name. + * @return A new list of data values converted to the appropriate type. + */ + private Map parseRow( + Map columnTypeByName, Map row) { + var parsedRow = new java.util.HashMap(); + row.forEach( + (key, value) -> { + Class type = columnTypeByName.get(key); + try { + parsedRow.put(key, type.getConstructor(String.class).newInstance(value)); + } catch (Exception e) { + throw new RuntimeException( + "Error parsing data for " + key + " as type " + type.getName()); + } + }); + return parsedRow; + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/Generators.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/Generators.java new file mode 100644 index 000000000..77df54539 --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/Generators.java @@ -0,0 +1,66 @@ +package com.codedifferently.lesson9.generator; + +import com.google.common.base.Joiner; +import java.util.Collections; +import java.util.stream.Collectors; + +public class Generators { + + public static class IntValueGenerator implements ValueGenerator { + public String generateValue() { + int minValue = (int) Short.MAX_VALUE + 1; + var maxValue = Integer.MAX_VALUE; + var value = (int) (minValue + Math.random() * (maxValue - minValue - 1)); + return Integer.toString(value); + } + } + + public static class StringValueGenerator implements ValueGenerator { + public String generateValue() { + var chars = + "abcdefghijklmnopqrstuvwxyz1234567890" + .chars() + .mapToObj(c -> (char) c) + .collect(Collectors.toList()); + Collections.shuffle(chars); + int minLength = 5 + (int) (Math.random() * 8); + return Joiner.on("").join(chars.subList(0, minLength)); + } + } + + public static class DoubleValueGenerator implements ValueGenerator { + public String generateValue() { + return Math.random() * Double.MAX_VALUE - 0.123456789012345d + ""; + } + } + + public static class ShortValueGenerator implements ValueGenerator { + public String generateValue() { + short minValue = 1; + var maxValue = Short.MAX_VALUE; + var value = (short) (minValue + Math.random() * (maxValue - minValue - 1)); + return Short.toString(value); + } + } + + public static class LongValueGenerator implements ValueGenerator { + public String generateValue() { + long minValue = Integer.MAX_VALUE + 1L; + var maxValue = Long.MAX_VALUE; + var value = (long) (minValue + Math.random() * (maxValue - minValue - 1)); + return Long.toString(value); + } + } + + public static class FloatValueGenerator implements ValueGenerator { + public String generateValue() { + return (float) (Math.random() * Float.MAX_VALUE) + ""; + } + } + + public static class BooleanValueGenerator implements ValueGenerator { + public String generateValue() { + return Math.random() > 0.5 ? "true" : "false"; + } + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/SampleFileGenerator.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/SampleFileGenerator.java new file mode 100644 index 000000000..263d0804c --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/SampleFileGenerator.java @@ -0,0 +1,75 @@ +package com.codedifferently.lesson9.generator; + +import com.codedifferently.lesson9.generator.Generators.*; +import com.google.gson.GsonBuilder; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** A class to generate a sample file with random data. */ +public class SampleFileGenerator { + + private static final ValueGenerator[] GENERATORS = { + new IntValueGenerator(), + new StringValueGenerator(), + new DoubleValueGenerator(), + new ShortValueGenerator(), + new LongValueGenerator(), + new FloatValueGenerator(), + new BooleanValueGenerator() + }; + + /** + * Create a test file with sample data. + * + * @param path the path to the directory where the file will be created + * @param providerName the name of the provider + */ + public void createTestFile(String path, String providerName) { + var generators = getShuffledGenerators(); + ArrayList> rows = createSampleData(generators); + saveToJsonFile(path, providerName, rows); + } + + private List getShuffledGenerators() { + var generators = Arrays.asList(GENERATORS); + Collections.shuffle(generators); + return generators; + } + + private ArrayList> createSampleData(List generators) { + var rows = new ArrayList>(); + for (var i = 0; i < 10; ++i) { + Map row = createRow(generators); + rows.add(createRow(generators)); + } + return rows; + } + + private Map createRow(List generators) { + var row = new LinkedHashMap(); + for (int i = 0; i < GENERATORS.length; ++i) { + var columnIndex = i + 1; + row.put("column" + columnIndex, GENERATORS[i].generateValue()); + } + return row; + } + + private void saveToJsonFile( + String path, String providerName, ArrayList> rows) { + var file = new File(path + File.separator + providerName + ".json"); + file.getParentFile().mkdirs(); + var gson = new GsonBuilder().setPrettyPrinting().create(); + try (var writer = new FileWriter(file, false)) { + writer.write(gson.toJson(rows)); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/ValueGenerator.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/ValueGenerator.java new file mode 100644 index 000000000..5106aa19c --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/generator/ValueGenerator.java @@ -0,0 +1,5 @@ +package com.codedifferently.lesson9.generator; + +public interface ValueGenerator { + String generateValue(); +} diff --git a/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/loader/DataFileLoader.java b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/loader/DataFileLoader.java new file mode 100644 index 000000000..9382ad51f --- /dev/null +++ b/lesson_09/types/types_app/src/main/java/com/codedifferently/lesson9/loader/DataFileLoader.java @@ -0,0 +1,32 @@ +package com.codedifferently.lesson9.loader; + +import com.codedifferently.lesson9.dataprovider.DataProvider; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.List; +import java.util.Map; + +public final class DataFileLoader { + + private final DataProvider dataProvider; + + public DataFileLoader(DataProvider dataProvider) { + this.dataProvider = dataProvider; + } + + public List> readData() throws IOException { + var filename = + File.separator + + String.join(File.separator, "data", dataProvider.getProviderName() + ".json"); + var gson = new Gson(); + try (var reader = new InputStreamReader(this.getClass().getResourceAsStream(filename))) { + var typeToken = new TypeToken>>() {}.getType(); + return gson.fromJson(reader, typeToken); + } catch (IOException e) { + throw new IOException("Error reading data from " + filename, e); + } + } +} diff --git a/lesson_09/types/types_app/src/main/resources/application.yml b/lesson_09/types/types_app/src/main/resources/application.yml new file mode 100644 index 000000000..e69de29bb diff --git a/lesson_09/types/types_app/src/main/resources/data/anthonymays.json b/lesson_09/types/types_app/src/main/resources/data/anthonymays.json new file mode 100644 index 000000000..04cd5e30e --- /dev/null +++ b/lesson_09/types/types_app/src/main/resources/data/anthonymays.json @@ -0,0 +1,92 @@ +[ + { + "column1": "834643072", + "column2": "fqg3t08", + "column3": "true", + "column4": "1.9978474E38", + "column5": "5.904330402434743E306", + "column6": "1366880876819581184", + "column7": "32238" + }, + { + "column1": "626423985", + "column2": "vigcdanxz", + "column3": "true", + "column4": "3.1219015E38", + "column5": "7.825662332684306E307", + "column6": "8911588992481299456", + "column7": "5360" + }, + { + "column1": "801829168", + "column2": "k6l7n12hto", + "column3": "false", + "column4": "2.059369E37", + "column5": "8.483538926727346E307", + "column6": "7067773515773391872", + "column7": "13178" + }, + { + "column1": "1730283217", + "column2": "wj8t9ofhn", + "column3": "true", + "column4": "3.1412757E38", + "column5": "6.586069274381104E307", + "column6": "2602724287439241216", + "column7": "22549" + }, + { + "column1": "1899052123", + "column2": "ve6rqjpf", + "column3": "true", + "column4": "1.4923796E38", + "column5": "1.242486318679349E308", + "column6": "1326294026127775488", + "column7": "4171" + }, + { + "column1": "1506630850", + "column2": "1jfl2cv8rh", + "column3": "true", + "column4": "7.4418154E37", + "column5": "4.250680596472136E307", + "column6": "3186885665368806400", + "column7": "10340" + }, + { + "column1": "397155933", + "column2": "7xfhym", + "column3": "false", + "column4": "3.239616E38", + "column5": "1.267642872799188E307", + "column6": "2110299146438134272", + "column7": "31380" + }, + { + "column1": "195489533", + "column2": "naboyjp", + "column3": "false", + "column4": "4.1123093E37", + "column5": "1.1978463760616652E308", + "column6": "3713931359377831936", + "column7": "23955" + }, + { + "column1": "867425141", + "column2": "c9w08yn3u4qt", + "column3": "false", + "column4": "2.2248801E38", + "column5": "1.5702466762995826E308", + "column6": "4386039230401549312", + "column7": "26860" + }, + { + "column1": "322265089", + "column2": "wiumcb8e7", + "column3": "false", + "column4": "2.0096116E38", + "column5": "1.6862242063030766E308", + "column6": "68879250147804848", + "column7": "13973" + } +] diff --git a/lesson_09/types/types_app/src/test/java/com/codedifferently/lesson9/Lesson9Test.java b/lesson_09/types/types_app/src/test/java/com/codedifferently/lesson9/Lesson9Test.java new file mode 100644 index 000000000..397136446 --- /dev/null +++ b/lesson_09/types/types_app/src/test/java/com/codedifferently/lesson9/Lesson9Test.java @@ -0,0 +1,97 @@ +package com.codedifferently.lesson9; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.codedifferently.lesson9.dataprovider.DataProvider; +import com.codedifferently.lesson9.loader.DataFileLoader; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; + +@SpringBootTest +@ContextConfiguration(classes = Lesson9.class) +@ExtendWith(SoftAssertionsExtension.class) +class Lesson9Test { + @Autowired private List dataProviders; + + @Test + void testDataProvider_filesLoad() throws IOException { + assertThat(dataProviders.size()).isGreaterThanOrEqualTo(1); + for (DataProvider provider : dataProviders) { + // Arrange + var loader = new DataFileLoader(provider); + + // Act + List> data = loader.readData(); + + // Assert + assertThat(data).as("File should return data.").isNotNull(); + assertThat(data.size()).as("File should have 10 rows.").isEqualTo(10); + } + } + + @Test + void testDataProvider_namesAreUnique() { + Set providerNames = + dataProviders.stream().map(p -> p.getProviderName()).collect(Collectors.toSet()); + + assertThat(providerNames.size()) + .as("Data provider names must be unique.") + .isEqualTo(dataProviders.size()); + } + + @Test + void testDataProvider_configuredCorrectly() throws IOException { + for (DataProvider provider : dataProviders) { + System.out.println("Checking provider " + provider.getProviderName()); + + // Arrange + var loader = new DataFileLoader(provider); + List> data = loader.readData(); + + // Act + Map columnTypeByName = provider.getColumnTypeByName(); + + // Assert + assertThat(columnTypeByName.size()) + .as("Number of column types must match number of columns in file.") + .isEqualTo(data.get(0).size()); + Set uniqueColumnTypes = + columnTypeByName.entrySet().stream() + .map(c -> c.getValue().getName()) + .collect(Collectors.toSet()); + assertThat(uniqueColumnTypes.size()) + .as("Each column should be a different type.") + .isEqualTo(columnTypeByName.size()); + } + } + + @Test + void testDataProvider_correctlyParsesData() throws Exception { + for (DataProvider provider : dataProviders) { + // Arrange + var loader = new DataFileLoader(provider); + List> data = loader.readData(); + + // Act + List> parsedData = provider.parseData(data); + + // Assert + for (var i = 0; i < data.size(); ++i) { + Map row = data.get(0); + Map parsed = parsedData.get(0); + for (String key : row.keySet()) { + assertThat(parsed.get(key).toString()).isEqualTo(row.get(key)); + } + } + } + } +} diff --git a/lesson_10/README.md b/lesson_10/README.md new file mode 100644 index 000000000..376d40957 --- /dev/null +++ b/lesson_10/README.md @@ -0,0 +1,13 @@ +# Lesson 10: Libraries and APIs + +## Pre-work + +Please review the following resources before lecture: + +* [What is CSV file (overview) (Video)](https://www.youtube.com/watch?v=OGOD2Fqy5k8) +* [Typescript Guide - Lesson 96 Reading CSV Files (Video)](https://www.youtube.com/watch?v=bbvECy0ICuo) +* [How to Parse / Read CSV File | Javascript & Node.js (Video)](https://www.youtube.com/watch?v=5HGBG9AiIzo) + +## Homework + +TODO(anthonydmays): Complete this \ No newline at end of file