Merge branch 'master' into 'AddFeatureClass'

# Conflicts:
#   src/Server/src/main/java/greenify/server/data/model/User.java
#   src/Server/src/main/java/greenify/server/service/UserService.java
This commit is contained in:
Sem van der Hoeven
2019-03-17 16:37:45 +00:00
52 changed files with 1679 additions and 853 deletions

2
.gitignore vendored
View File

@@ -19,7 +19,7 @@
# Edit at https://www.gitignore.io/?templates=java,maven,eclipse,intellij,visualstudiocode # Edit at https://www.gitignore.io/?templates=java,maven,eclipse,intellij,visualstudiocode
### our project ### ### our project ###
# src/**/.idea/ src/**/.idea/
# src/**/.gradle/ # src/**/.gradle/

View File

@@ -1,188 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
This configuration file was written by the eclipse-cs plugin configuration editor
-->
<!--
Checkstyle-Configuration: TI1216
Description:
Checkstyle configurartion that checks the Google coding conventions (https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html).
-->
<module name="Checker">
<property name="severity" value="warning"/>
<property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="LineLength">
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
<property name="max" value="100"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly"/>
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notPreceded" value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
<message key="ws.notFollowed" value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="option" value="nl"/>
<property name="tokens" value="DOT"/>
</module>
<module name="SeparatorWrap">
<property name="option" value="EOL"/>
<property name="tokens" value="COMMA"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern" value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern" value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<property name="tokens" value="VARIABLE_DEF"/>
<message key="name.invalidPattern" value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
<message key="ws.followed" value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded" value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow" value="GenericWhitespace ''{0}'' should followed by whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="caseIndent" value="4"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="allowedAbbreviationLength" value="1"/>
<property name="ignoreFinal" value="false"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="customImportOrderRules" value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
<property name="specialImportsRegExp" value="com.google"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
</module>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments" value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
</module>
<module name="JavadocMethod">
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="scope" value="public"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern" value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
<module name="UnusedImports"/>
<module name="RedundantImport"/>
<module name="MethodLength"/>
<module name="ParameterNumber"/>
<module name="MethodCount">
<property name="maxTotal" value="50"/>
<property name="maxPrivate" value="50"/>
<property name="maxPackage" value="50"/>
<property name="maxProtected" value="50"/>
<property name="maxPublic" value="50"/>
</module>
<module name="AvoidNestedBlocks"/>
<module name="DeclarationOrder"/>
<module name="EmptyStatement"/>
<module name="IllegalThrows"/>
<module name="IllegalCatch"/>
<module name="MissingSwitchDefault"/>
<module name="StringLiteralEquality"/>
<module name="UnnecessaryParentheses"/>
<module name="CyclomaticComplexity"/>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="FileLength"/>
</module>

View File

@@ -16,45 +16,27 @@ apply plugin: 'eclipse'
apply plugin: 'idea' apply plugin: 'idea'
apply plugin: 'org.springframework.boot' apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management' apply plugin: 'io.spring.dependency-management'
apply plugin: 'jacoco'
apply plugin: 'checkstyle'
apply plugin: 'application' apply plugin: 'application'
application { application {
mainClassName = 'greenify.client.Application' mainClassName = 'greenify.server.Application'
}
//apply plugin: 'org.openjfx.javafxplugin'
tasks.withType(Checkstyle) {
reports {
html.destination rootProject.file("build/reports/checkstyle.html")
}
} }
repositories { repositories {
mavenCentral() mavenCentral()
} }
//client bootjar
bootJar { bootJar {
baseName = 'gs-consuming-rest' enabled = false
version = '0.1.0'
} }
//server bootjar jar {
bootJar { enabled = true
baseName = 'gs-rest-service'
version = '0.1.0'
} }
sourceCompatibility = 1.8 sourceCompatibility = 1.8
targetCompatibility = 1.8 targetCompatibility = 1.8
test {
useJUnitPlatform()
}
dependencies { dependencies {
compile("org.springframework.boot:spring-boot-starter") compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework:spring-web") compile("org.springframework:spring-web")
@@ -76,22 +58,6 @@ dependencies {
) )
} }
jacoco {
toolVersion = "0.8.3"
reportsDir = file("$buildDir/customJacocoReportDir")
}
jacocoTestReport {
reports {
xml.enabled false
csv.enabled false
html.destination file("${buildDir}/jacocoHtml")
}
}
task application(type: JavaExec, dependsOn: classes) {
main = 'Cient.Application'
}

View File

@@ -1,12 +0,0 @@
# Sprint Review
## Main problems Encountered
We have no problems so far. Everyone arrives on time and does the tasks assigned to them.
## Adjustments from previous sprints
Since this is the first review, there are no previous sprints yet
## Adjustments for next sprint
- Keep up the good work!

View File

@@ -1,14 +0,0 @@
# Sprint Review
## Main problems Encountered
### Problem 1: Kristin left the group
Kristin does not continue CSE and left our group. We'll work with five people from now on.
## Adjustments from previous sprints
We created the backlog before the sprint, which helps making clear what we're working on.
## Adjustments for next sprint
- Group made out of five
- Backlogs ready on time

View File

Before

Width:  |  Height:  |  Size: 81 KiB

After

Width:  |  Height:  |  Size: 81 KiB

View File

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

View File

@@ -0,0 +1,188 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
This configuration file was written by the eclipse-cs plugin configuration editor
-->
<!--
Checkstyle-Configuration: TI1216
Description:
Checkstyle configurartion that checks the Google coding conventions (https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html).
-->
<module name="Checker">
<property name="severity" value="warning"/>
<property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="LineLength">
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
<property name="max" value="100"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly"/>
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notPreceded" value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
<message key="ws.notFollowed" value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="option" value="nl"/>
<property name="tokens" value="DOT"/>
</module>
<module name="SeparatorWrap">
<property name="option" value="EOL"/>
<property name="tokens" value="COMMA"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern" value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern" value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<property name="tokens" value="VARIABLE_DEF"/>
<message key="name.invalidPattern" value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern" value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
<message key="ws.followed" value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded" value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow" value="GenericWhitespace ''{0}'' should followed by whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="caseIndent" value="4"/>
<property name="arrayInitIndent" value="4"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="allowedAbbreviationLength" value="1"/>
<property name="ignoreFinal" value="false"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<module name="CustomImportOrder">
<property name="customImportOrderRules" value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
<property name="specialImportsRegExp" value="com.google"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
</module>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments" value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
</module>
<module name="JavadocMethod">
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="scope" value="public"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern" value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
<module name="UnusedImports"/>
<module name="RedundantImport"/>
<module name="MethodLength"/>
<module name="ParameterNumber"/>
<module name="MethodCount">
<property name="maxTotal" value="50"/>
<property name="maxPrivate" value="50"/>
<property name="maxPackage" value="50"/>
<property name="maxProtected" value="50"/>
<property name="maxPublic" value="50"/>
</module>
<module name="AvoidNestedBlocks"/>
<module name="DeclarationOrder"/>
<module name="EmptyStatement"/>
<module name="IllegalThrows"/>
<module name="IllegalCatch"/>
<module name="MissingSwitchDefault"/>
<module name="StringLiteralEquality"/>
<module name="UnnecessaryParentheses"/>
<module name="CyclomaticComplexity"/>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="FileLength"/>
</module>

View File

@@ -0,0 +1,3 @@
<module name="SuppressionFilter">
<property name="file" value="quality/checkstyle/suppressions.xml" />
</module>

View File

@@ -3,10 +3,12 @@
<component name="CheckStyle-IDEA"> <component name="CheckStyle-IDEA">
<option name="configuration"> <option name="configuration">
<map> <map>
<entry key="active-configuration" value="LOCAL_FILE:C:/Users/ceren/Desktop/lastGreenify/template-master/quality/checkstyle/checkstyle.xml:cse" />
<entry key="checkstyle-version" value="8.16" /> <entry key="checkstyle-version" value="8.16" />
<entry key="copy-libs" value="true" /> <entry key="copy-libs" value="true" />
<entry key="location-0" value="BUNDLED:(bundled):Sun Checks" /> <entry key="location-0" value="BUNDLED:(bundled):Sun Checks" />
<entry key="location-1" value="BUNDLED:(bundled):Google Checks" /> <entry key="location-1" value="BUNDLED:(bundled):Google Checks" />
<entry key="location-2" value="LOCAL_FILE:C:/Users/ceren/Desktop/lastGreenify/template-master/quality/checkstyle/checkstyle.xml:cse" />
<entry key="scan-before-checkin" value="false" /> <entry key="scan-before-checkin" value="false" />
<entry key="scanscope" value="JavaOnly" /> <entry key="scanscope" value="JavaOnly" />
<entry key="suppress-errors" value="false" /> <entry key="suppress-errors" value="false" />

1
src/.idea/gradle.xml generated
View File

@@ -8,6 +8,7 @@
<option name="gradleHome" value="$USER_HOME$/scoop/apps/gradle/current" /> <option name="gradleHome" value="$USER_HOME$/scoop/apps/gradle/current" />
<option name="modules"> <option name="modules">
<set> <set>
<option value="$PROJECT_DIR$/.." />
<option value="$PROJECT_DIR$" /> <option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/Client" /> <option value="$PROJECT_DIR$/Client" />
<option value="$PROJECT_DIR$/Common" /> <option value="$PROJECT_DIR$/Common" />

6
src/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

908
src/.idea/workspace.xml generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,32 +13,27 @@ apply plugin: 'idea'
apply plugin: 'org.springframework.boot' apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management' apply plugin: 'io.spring.dependency-management'
apply plugin: 'jacoco' apply plugin: 'jacoco'
//apply plugin: 'checkstyle' apply plugin: 'checkstyle'
//
//checkstyle {
// version = '7.8.1'
// config = 'checkstyle/checkstyle.xml' as File
//}
//
//checkstyleMain {
// source ='src/main/java'
//}
//
//checkstyleTest {
// source ='src/test/java'
//}
//
//tasks.withType(Checkstyle) {
// reports {
// xml.enabled false
// html.enabled true
// html.stylesheet resources.text.fromFile('config/xsl/checkstyle-custom.xsl')
// }
//}
sourceCompatibility = 1.8 sourceCompatibility = 1.8
targetCompatibility = 1.8 targetCompatibility = 1.8
def configDir = "${project.rootDir}/quality"
checkstyle {
toolVersion '7.8.1'
configFile file("$configDir/checkstyle/checkstyle.xml")
configProperties.checkstyleSuppressionsPath = file("$configDir/checkstyle/suppressions.xml").absolutePath
}
checkstyleMain {
source ='src/main/java'
}
checkstyleTest {
source ='src/test/java'
}
test { test {
useJUnitPlatform() useJUnitPlatform()
} }

View File

@@ -10,51 +10,39 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import java.io.IOException;
@SpringBootApplication @SpringBootApplication
public class Application extends javafx.application.Application { public class Application extends javafx.application.Application {
private ConfigurableApplicationContext springContext; private static ConfigurableApplicationContext springContext;
private Parent rootNode;
private FXMLLoader fxmlLoader;
private static final Logger log = LoggerFactory.getLogger(Application.class); private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) { public static void main(String[] args) {
launch(args); launch(args);
} }
// @Bean /**
// public RestTemplate restTemplate(RestTemplateBuilder builder) { * This method takes an url and return a parent.
// return builder.build(); * @param url which is being loaded.
// } * @return parent object.
*/
public static Parent load(java.net.URL url) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(springContext::getBean);
loader.setLocation(url);
return loader.load();
}
@Override @Override
public void init() throws Exception { public void init() throws Exception {
springContext = SpringApplication.run(Application.class); springContext = SpringApplication.run(Application.class);
fxmlLoader = new FXMLLoader();
fxmlLoader.setControllerFactory(springContext::getBean);
} }
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
fxmlLoader.setLocation(this.getClass().getClassLoader().getResource("fxml/sample.fxml")); Parent rootNode = load(this.getClass().getClassLoader().getResource("fxml/sample.fxml"));
primaryStage.setTitle("Greenify");
// fxmlLoader.setLocation(
// this.getClass().getClassLoader().getResource("fxml/dashboard.fxml")
// );
rootNode = fxmlLoader.load();
// rootNode = FXMLLoader.load(
// this.getClass().getClassLoader().getResource("fxml/sample.fxml")
// );
primaryStage.setTitle("GoGreen");
Scene scene = new Scene(rootNode); Scene scene = new Scene(rootNode);
// scene.getStylesheets().add(
// getClass().getResource("stylesheets/dashboardStyle.css").toExternalForm()
// );
primaryStage.setScene(scene); primaryStage.setScene(scene);
primaryStage.show(); primaryStage.show();
} }
@@ -63,14 +51,4 @@ public class Application extends javafx.application.Application {
public void stop() { public void stop() {
springContext.stop(); springContext.stop();
} }
// @Bean
// public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
// return args -> {
// User user = restTemplate.getForObject(
// "http://localhost:8080/user", User.class);
// log.info(user.toString());
//
// };
// }
} }

View File

@@ -5,32 +5,29 @@ import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.AnchorPane; import javafx.scene.layout.AnchorPane;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class DashBoardController { public class DashBoardController {
@Autowired @Autowired
UserService userService; UserService userService;
@FXML private int count = 0;
public AnchorPane menuBar;
public AnchorPane dashboardPane;
public AnchorPane userPane;
public AnchorPane activitiesPane;
public Label welcomebacktext;
// public Button addActivityButton;
// public ComboBox addActivity;
@FXML @FXML
public Label dashboardText; private AnchorPane menuBar;
public Label activitiesText; private AnchorPane dashboardPane;
public Label userText; private AnchorPane userPane;
public Button dashboardButton; private AnchorPane activitiesPane;
public Button activitiesButton; private Label welcomebacktext;
public Button userButton; private Button dashboardButton;
private Button activitiesButton;
DropShadow shadow = new DropShadow(); private Button userButton;
private Button veganMealButton;
private Label counter;
private Label scoreField;
/** /**
* displays the dashboard pane. * displays the dashboard pane.
@@ -64,13 +61,17 @@ public class DashBoardController {
userPane.setVisible(true); userPane.setVisible(true);
activitiesPane.setVisible(false); activitiesPane.setVisible(false);
} }
// public void addShadow(MouseEvent event) {
// userButton.setEffect(shadow);
// }
//
// public void removeShadow(MouseEvent event) {
// userButton.setEffect(null);
//
// }
/**
* adds a vegetarian meal.
* @param event the event (clicking the button)
*/
public void addVeganMeal(ActionEvent event) {
count++;
counter.setText("Count: " + count);
System.out.println(userService);
userService.addVeganMeal(userService.currentUser.getId(),
userService.currentUser.getName());
System.out.println("Vegetarian meal is added");
}
} }

View File

@@ -0,0 +1,68 @@
package greenify.client.controller;
import greenify.client.rest.UserService;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class RegisterWindowController {
@Autowired
UserService userService;
@FXML
private TextField userNameText;
@FXML
private PasswordField passwordField;
@FXML
private PasswordField passwordField2;
@FXML
private Button signupButton;
/**
* signs the user up.
* @param event the click of the signup button
*/
@FXML
public void handleSignUpButton(ActionEvent event) {
//set the window to the current window (for displaying the alerts)
Window owner = signupButton.getScene().getWindow();
//check if the username field is empty
if (userNameText.getText().isEmpty()) {
//if so, display an alert
UserController.AlertHelper.showAlert(Alert.AlertType.ERROR, owner, "Username Error!",
"Please enter a username!");
return;
}
//check if the password field is empty
if (passwordField.getText().isEmpty()) {
//if so, display an alert
UserController.AlertHelper.showAlert(Alert.AlertType.ERROR, owner, "Password Error!",
"Please enter a password!");
return;
}
//check if the two password fields are equal
if (!passwordField.getText().equals(passwordField2.getText())) {
//if not, display an alert
UserController.AlertHelper.showAlert(Alert.AlertType.ERROR, owner, "Password Error!",
"Please make sure the passwords entered are the same!");
return;
}
userService.registerUser(userNameText.getText(), passwordField.getText());
//close the register window after the user has entered all the credentials
Stage current = (Stage) owner;
current.close();
}
}

View File

@@ -1,9 +1,9 @@
package greenify.client.controller; package greenify.client.controller;
import greenify.client.Application;
import greenify.client.rest.UserService; import greenify.client.rest.UserService;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent; import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
@@ -24,29 +24,10 @@ public class UserController {
@FXML @FXML
private TextField usernameField; private TextField usernameField;
@FXML
private PasswordField passwordField; private PasswordField passwordField;
@FXML
private Button loginButton; private Button loginButton;
@FXML
private Button signupButton; private Button signupButton;
// @Value("${my.url}")
// private String myUrl;
// @FXML
// private void initialize(ActionEvent event) throws IOException {
// Parent parent = FXMLLoader.load(getClass().getResource("sample.fxml"));
// Scene scene = new Scene(parent);
// Stage app_stage = (Stage)((Node) event.getSource()).getScene().getWindow();
// app_stage.setScene(scene);
// app_stage.show();
// }
@FXML @FXML
protected void handleLoginButtonAction(ActionEvent event) throws IOException { protected void handleLoginButtonAction(ActionEvent event) throws IOException {
Window owner = loginButton.getScene().getWindow(); Window owner = loginButton.getScene().getWindow();
@@ -55,7 +36,6 @@ public class UserController {
"Please enter your username"); "Please enter your username");
return; return;
} else { } else {
// newUser.setUsername(usernameField.getText());
System.out.println("Username is " + usernameField.getText()); System.out.println("Username is " + usernameField.getText());
} }
if (passwordField.getText().isEmpty()) { if (passwordField.getText().isEmpty()) {
@@ -63,22 +43,11 @@ public class UserController {
"Please enter a password"); "Please enter a password");
return; return;
} else { } else {
// newUser.setPassword(passwordField.getText());
System.out.println("Password is " + passwordField.getText()); System.out.println("Password is " + passwordField.getText());
} }
userService.loginUser(usernameField.getText(), passwordField.getText());
userService.registerUser(usernameField.getText(), passwordField.getText()); Stage current = (Stage) owner;
current.close();
// load the dashboard stage
// Parent parent = FXMLLoader.load(
// this.getClass().getClassLoader().getResource("/fxml/dashboard.fxml")
// );
//
// Scene scene = new Scene(parent);
// Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
// app_stage.setScene(scene);
// app_stage.setFullScreen(true);
// app_stage.show();
openDashboard(); openDashboard();
} }
@@ -89,17 +58,16 @@ public class UserController {
* @author sem * @author sem
*/ */
public void openDashboard() throws IOException { public void openDashboard() throws IOException {
Parent dash = FXMLLoader.load( Parent dash = Application.load(this.getClass().getClassLoader()
this.getClass().getClassLoader().getResource("fxml/Dashboard.fxml") .getResource("fxml/dashboard.fxml"));
);
Scene scene = new Scene(dash); Scene scene = new Scene(dash);
scene.getStylesheets().add(getClass().getClassLoader()
.getResource("stylesheets/dashboardStyle.css").toExternalForm());
Stage appStage = new Stage(); Stage appStage = new Stage();
appStage.setScene(scene); appStage.setScene(scene);
// app_stage.setFullScreen(true);
appStage.show(); appStage.show();
} }
public static class AlertHelper { public static class AlertHelper {
/** /**
* alerts for the login screen. * alerts for the login screen.
@@ -121,4 +89,19 @@ public class UserController {
} }
} }
/**
* The method handles register button.
* @param event User clicks to the button
* @throws Exception when the file couldn't find
*/
public void handleRegisterButtonAction(ActionEvent event) throws Exception {
Parent registerWindow = Application.load(this.getClass().getClassLoader()
.getResource("fxml/RegisterWindow.fxml"));
Scene registerScene = new Scene(registerWindow);
Stage registerStage = new Stage();
registerStage.setScene(registerScene);
registerStage.setTitle("Enter register credentials");
registerStage.show();
}
} }

View File

@@ -1,21 +1,25 @@
package greenify.client.rest; package greenify.client.rest;
import greenify.common.UserDTO; import greenify.common.UserDto;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.http.*; import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
@Component @Service
public class UserService { public class UserService {
@Autowired @Autowired
RestTemplate restTemplate; RestTemplate restTemplate;
public UserDto currentUser;
@Bean @Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build(); return builder.build();
} }
@@ -25,7 +29,7 @@ public class UserService {
* @param password the password of the user * @param password the password of the user
* @return a userDTO * @return a userDTO
*/ */
public UserDTO registerUser(String name, String password) { public UserDto registerUser(String name, String password) {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/registerUser") UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/registerUser")
@@ -33,6 +37,46 @@ public class UserService {
.queryParam("password", password); .queryParam("password", password);
HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<?> entity = new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri()); System.out.println(builder.build().encode().toUri());
return this.restTemplate.getForObject(builder.build().encode().toUri(), UserDTO.class); UserDto result = this.restTemplate.getForObject(builder.build()
.encode().toUri(), UserDto.class);
this.currentUser = result;
return result;
}
/**
* sign ins the user.
* @param name the username of the user
* @param password the password of the user
* @return a userDTO
*/
public UserDto loginUser(String name, String password) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/loginUser")
.queryParam("name", name)
.queryParam("password", password);
HttpEntity<?> entity = new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri());
UserDto result = this.restTemplate.getForObject(builder.build()
.encode().toUri(), UserDto.class);
this.currentUser = result;
return result;
}
/**
* a user adds vegan meal.
* @param id the id of the user
* @param name the username of the user
* @return a userDTO
*/
public UserDto addVeganMeal(Long id, String name) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/addVeganMeal")
.queryParam("id", id)
.queryParam("name", name);
HttpEntity<?> entity = new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri());
return this.restTemplate.getForObject(builder.build().encode().toUri(), UserDto.class);
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

View File

@@ -0,0 +1 @@
logging.level.org.springframework.beans.factory=DEBUG

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.*?>
<AnchorPane prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.RegisterWindowController">
<children>
<ImageView fitHeight="312.0" fitWidth="300.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../registerBackground.png" />
</image>
</ImageView>
<Text fill="#00650d" layoutX="103.0" layoutY="42.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Register">
<font>
<Font size="26.0" />
</font>
</Text>
<TextField fx:id="userNameText" layoutX="69.0" layoutY="94.0" promptText="Username">
<font>
<Font size="13.0" />
</font>
</TextField>
<Button fx:id="signupButton" layoutX="115.0" layoutY="229.0" mnemonicParsing="false" onAction="#handleSignUpButton" style="-fx-background-color: #005e07;" text="Sign up!" textFill="#c4eec9">
<font>
<Font name="Corbel Bold" size="14.0" />
</font>
</Button>
<PasswordField fx:id="passwordField" layoutX="69.0" layoutY="138.0" promptText="Password">
<font>
<Font size="13.0" />
</font>
</PasswordField>
<PasswordField fx:id="passwordField2" layoutX="69.0" layoutY="182.0" promptText="Re-enter password">
<font>
<Font size="13.0" />
</font>
</PasswordField>
</children>
</AnchorPane>

View File

@@ -1,38 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import javafx.collections.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<?import javafx.collections.FXCollections?> <?import javafx.scene.shape.Line?>
<?import javafx.scene.text.*?>
<AnchorPane prefHeight="602.0" prefWidth="926.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.DashBoardController"> <AnchorPane prefHeight="602.0" prefWidth="934.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.DashBoardController">
<children> <children>
<AnchorPane fx:id="menuBar" prefHeight="603.0" prefWidth="216.0" style="-fx-background-color: #545b4f;"> <AnchorPane fx:id="menuBar" prefHeight="603.0" prefWidth="216.0" style="-fx-background-color: #5a635c;">
<children> <children>
<Label alignment="CENTER" contentDisplay="CENTER" layoutY="-2.0" prefHeight="90.0" prefWidth="216.0" text="Go Green" textAlignment="CENTER" textFill="#07a11c"> <Label alignment="CENTER" contentDisplay="CENTER" layoutY="-2.0" prefHeight="90.0" prefWidth="216.0" text="Go Green" textAlignment="CENTER" textFill="#71bc84">
<font> <font>
<Font size="36.0" /> <Font size="36.0" />
</font> </font>
</Label> </Label>
<Button fx:id="dashboardButton" layoutY="88.0" mnemonicParsing="false" onAction="#displayDashboard" prefHeight="45.0" prefWidth="216.0" style="-fx-background-color: #5a635c;" text="dashboard"> <Button fx:id="dashboardButton" layoutY="88.0" mnemonicParsing="false" onAction="#displayDashboard" prefHeight="45.0" prefWidth="216.0" text="dashboard">
<font> <font>
<Font size="21.0" /> <Font size="21.0" />
</font> </font>
</Button> </Button>
<Button fx:id="activitiesButton" layoutY="133.0" mnemonicParsing="false" onAction="#displayActivities" prefHeight="45.0" prefWidth="216.0" style="-fx-background-color: #5a635c;" text="activities"> <Button fx:id="activitiesButton" layoutY="133.0" mnemonicParsing="false" onAction="#displayActivities" prefHeight="45.0" prefWidth="216.0" text="activities">
<font> <font>
<Font size="21.0" /> <Font size="21.0" />
</font> </font>
</Button> </Button>
<Button fx:id="userButton" layoutY="178.0" mnemonicParsing="false" onAction="#displayUser" prefHeight="45.0" prefWidth="216.0" style="-fx-background-color: #5a635c;" text="you"> <Button fx:id="userButton" layoutY="178.0" mnemonicParsing="false" onAction="#displayUser" prefHeight="45.0" prefWidth="216.0" text="you">
<font> <font>
<Font size="21.0" /> <Font size="21.0" />
</font> </font>
</Button> </Button>
<Line endX="104.0" layoutX="102.0" layoutY="133.0" scaleY="0.7" startX="-100.0" stroke="#e3ffe8" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" />
<Line endX="104.0" layoutX="105.0" layoutY="178.0" scaleY="0.7" startX="-100.0" stroke="#e3ffe8" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" />
</children></AnchorPane> </children></AnchorPane>
<AnchorPane fx:id="activitiesPane" layoutX="214.0" prefHeight="603.0" prefWidth="711.0" visible="false"> <AnchorPane fx:id="activitiesPane" layoutX="214.0" prefHeight="603.0" prefWidth="711.0" visible="false">
<children> <children>
@@ -41,6 +40,16 @@
<Font size="30.0" /> <Font size="30.0" />
</font> </font>
</Text> </Text>
<Button fx:id="veganMealButton" layoutX="60.0" layoutY="116.0" mnemonicParsing="false" style="-fx-background-color: #009623; -fx-border-radius: 25px;" onAction="#addVeganMeal" text="Add a vegetarian meal" textFill="#e0ffe1">
<font>
<Font size="14.0" />
</font>
</Button>
<Label fx:id="counter" layoutX="288.0" layoutY="110.0" prefHeight="44.0" prefWidth="115.0" text="Count: ">
<font>
<Font size="25.0" />
</font>
</Label>
</children></AnchorPane> </children></AnchorPane>
<AnchorPane fx:id="userPane" layoutX="215.0" layoutY="-1.0" prefHeight="603.0" prefWidth="711.0" visible="false"> <AnchorPane fx:id="userPane" layoutX="215.0" layoutY="-1.0" prefHeight="603.0" prefWidth="711.0" visible="false">
<children> <children>
@@ -49,6 +58,20 @@
<Font size="30.0" /> <Font size="30.0" />
</font> </font>
</Text> </Text>
<VBox layoutX="517.0" layoutY="28.0" prefHeight="53.0" prefWidth="100.0" style="-fx-background-color: #daefdf; -fx-border-radius: 20%;">
<children>
<Text fill="#004d11" strokeType="OUTSIDE" strokeWidth="0.0" text="Score" textAlignment="CENTER" wrappingWidth="100.79296875">
<font>
<Font size="24.0" />
</font>
</Text>
<Label fx:id="scoreField" alignment="CENTER" contentDisplay="CENTER" prefHeight="17.0" prefWidth="101.0" text="score" textAlignment="CENTER">
<font>
<Font size="18.0" />
</font>
</Label>
</children>
</VBox>
</children></AnchorPane> </children></AnchorPane>
<AnchorPane fx:id="dashboardPane" layoutX="215.0" prefHeight="603.0" prefWidth="711.0"> <AnchorPane fx:id="dashboardPane" layoutX="215.0" prefHeight="603.0" prefWidth="711.0">
<children> <children>
@@ -58,18 +81,18 @@
<Font size="30.0" /> <Font size="30.0" />
</font> </font>
</Label> </Label>
<Button layoutX="583.0" layoutY="41.0" mnemonicParsing="false" style="-fx-background-color: #167526;" text="+" textFill="#e0fcdb"> <Button layoutX="567.0" layoutY="26.0" mnemonicParsing="false" onAction="#displayActivities" prefHeight="74.0" prefWidth="62.0" style="-fx-border-radius: 20px; -fx-padding: 0px 0px 0px 0px; -fx-background-color: transparent;" textFill="#e0fcdb">
<font> <font>
<Font name="Eras Bold ITC" size="28.0" /> <Font name="Eras Bold ITC" size="28.0" />
</font> </font>
<graphic>
<ImageView fitHeight="81.0" fitWidth="74.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@../addActivity1.png" />
</image>
</ImageView>
</graphic>
</Button> </Button>
<!--<ComboBox fx:id="addActivity" layoutX="532.0" layoutY="28.0" prefWidth="150.0" promptText="Add an Activity" style="-fx-background-color: #1f951f;">-->
<!--<items>-->
<!--<FXCollections fx:factory="observableArrayList">-->
<!--<String fx:value="Ate a vegetarian meal" />-->
<!--</FXCollections>-->
<!--</items>-->
<!--</ComboBox>-->
</children> </children>
</AnchorPane> </AnchorPane>
</children> </children>

View File

@@ -1,18 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?> <?import javafx.scene.control.*?>
<?import javafx.scene.control.Hyperlink?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?> <?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?> <?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?> <?import javafx.scene.text.*?>
<?import javafx.scene.text.Text?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="602.0" prefWidth="934.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.UserController">
<AnchorPane fx:controller="greenify.client.controller.UserController" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="574.0" prefWidth="934.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1">
<children> <children>
<ImageView fitHeight="574.0" fitWidth="943.0" layoutX="-1.0" pickOnBounds="true"> <ImageView fitHeight="600.0" fitWidth="943.0" layoutX="-1.0" pickOnBounds="true">
<image> <image>
<Image url="@../pinkleaf.jpg" /> <Image url="@../pinkleaf.jpg" />
</image></ImageView> </image></ImageView>
@@ -21,19 +16,19 @@
<Font name="Californian FB" size="72.0" /> <Font name="Californian FB" size="72.0" />
</font> </font>
</Text> </Text>
<Button fx:id="loginButton" layoutX="419.0" layoutY="274.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="96.0" text="Login" textAlignment="CENTER" onAction="#handleLoginButtonAction"/> <Button fx:id="loginButton" layoutX="419.0" layoutY="274.0" mnemonicParsing="false" onAction="#handleLoginButtonAction" prefHeight="26.0" prefWidth="96.0" text="Login" textAlignment="CENTER" />
<Button fx:id="signupButton" layoutX="49.0" layoutY="52.0" mnemonicParsing="false" prefHeight="6.0" prefWidth="61.0" text="Sign UP"/> <Button fx:id="signupButton" layoutX="42.0" layoutY="52.0" mnemonicParsing="false" onAction="#handleRegisterButtonAction" prefHeight="10.0" prefWidth="96.0" text="Sign up!" />
<PasswordField fx:id="passwordField" layoutX="318.0" layoutY="210.0" prefHeight="42.0" prefWidth="303.0" promptText="Password" /> <PasswordField fx:id="passwordField" layoutX="318.0" layoutY="210.0" prefHeight="42.0" prefWidth="303.0" promptText="Password" />
<Hyperlink layoutX="392.0" layoutY="308.0" prefHeight="42.0" prefWidth="173.0" text="Forgot Password?" textAlignment="CENTER" textFill="WHITE" textOverrun="LEADING_WORD_ELLIPSIS"> <Hyperlink layoutX="392.0" layoutY="308.0" prefHeight="42.0" prefWidth="173.0" text="Forgot Password?" textAlignment="CENTER" textFill="WHITE" textOverrun="LEADING_WORD_ELLIPSIS">
<font> <font>
<Font name="Bodoni MT Bold" size="18.0" /> <Font name="Bodoni MT Bold" size="18.0" />
</font> </font>
</Hyperlink> </Hyperlink>
<Text fill="#23773d" layoutX="7.0" layoutY="40.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Not Member?" textAlignment="CENTER" wrappingWidth="146.13673400878906"> <Text fill="#23773d" layoutX="20.0" layoutY="40.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Not Member?" textAlignment="CENTER" wrappingWidth="146.13673400878906">
<font> <font>
<Font name="Californian FB" size="14.0" /> <Font name="Californian FB" size="20.0" />
</font> </font>
</Text> </Text>
<TextField fx:id="usernameField" layoutX="319.0" layoutY="154.0" prefHeight="42.0" prefWidth="303.0" promptText="Username" /> <TextField fx:id="usernameField" layoutX="319.0" layoutY="154.0" prefHeight="42.0" prefWidth="303.0" promptText="Username" />
</children> </children>
</AnchorPane> </AnchorPane>

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -1,5 +1,31 @@
.button { @font-face {
-fx-border-width: 0px 0px 1px 0px; font-family: 'Designio Regular ';
-fx-border-color: #f9f9f9; src: url('stylesheets/DesignioRegular.otf');
-fx-border-radius: 0%; }
.root {
-fx-background-color: #f9fffb;
-fx-font-family: "Big Designer";
}
#dashboardButton {
-fx-background-color: #5a635c;
}
#dashboardButton:pressed {
-fx-background-color: #b7e2c2;
}
#userButton {
-fx-background-color: #5a635c;
}
#userButton:pressed {
-fx-background-color: #b7e2c2;
}
#activitiesButton {
-fx-background-color: #5a635c;
}
#activitiesButton:pressed {
-fx-background-color: #b7e2c2;
} }

View File

@@ -1,16 +0,0 @@
import greenify.client.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class ApplicationTest {
@Test
public void applicationContextLoaded() {
}
@Test
public void applicationContextTest() {
Application.main(new String[] {});
}
}

View File

@@ -1,9 +1,12 @@
import greenify.client.rest.UserService; import greenify.client.rest.UserService;
import greenify.common.UserDTO; import greenify.common.UserDto;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.*; import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -21,13 +24,33 @@ public class UserServiceTest {
UserService userService; UserService userService;
@Test @Test
public void mocking() throws Exception { public void userRegisterTest() throws Exception {
UserDTO testUser = new UserDTO(1L, "Eric"); UserDto testUser = new UserDto(1L, "Eric");
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/registerUser?name=Eric&password=password"), Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/registerUser?name=Eric&password=password"),
UserDTO.class)) UserDto.class))
.thenReturn(testUser); .thenReturn(testUser);
UserDTO user = userService.registerUser("Eric", "password"); UserDto user = userService.registerUser("Eric", "password");
Assert.assertEquals(testUser, user);
}
@Test
public void userLoginTest() throws Exception {
UserDto testUser = new UserDto(1L, "Eric");
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/loginUser?name=Eric&password=password"),
UserDto.class))
.thenReturn(testUser);
UserDto user = userService.loginUser("Eric", "password");
Assert.assertEquals(testUser, user);
}
@Test
public void addVeganMealTest() throws Exception {
UserDto testUser = new UserDto(1L, "Eric");
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/addVeganMeal?id=1&name=Eric"),
UserDto.class))
.thenReturn(testUser);
UserDto user = userService.addVeganMeal(1L, "Eric");
Assert.assertEquals(testUser, user); Assert.assertEquals(testUser, user);
} }
} }

View File

@@ -11,6 +11,7 @@ apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'idea' apply plugin: 'idea'
apply plugin: 'jacoco' apply plugin: 'jacoco'
apply plugin: 'checkstyle'
sourceCompatibility = 1.8 sourceCompatibility = 1.8
targetCompatibility = 1.8 targetCompatibility = 1.8
@@ -19,6 +20,22 @@ repositories {
mavenCentral() mavenCentral()
} }
def configDir = "${project.rootDir}/quality"
checkstyle {
toolVersion '7.8.1'
configFile file("$configDir/checkstyle/checkstyle.xml")
configProperties.checkstyleSuppressionsPath = file("$configDir/checkstyle/suppressions.xml").absolutePath
}
checkstyleMain {
source ='src/main/java'
}
checkstyleTest {
source ='src/test/java'
}
dependencies { dependencies {
testCompile("junit:junit") testCompile("junit:junit")
testCompile( testCompile(

View File

@@ -7,6 +7,8 @@ public class ErrorResponse {
this.message = message; this.message = message;
} }
public ErrorResponse() { }
public String getMessage() { public String getMessage() {
return message; return message;
} }

View File

@@ -1,22 +0,0 @@
package greenify.common;
public class UserDTO {
private Long id;
private String name;
public UserDTO() {
}
public UserDTO(Long id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
}

View File

@@ -0,0 +1,34 @@
package greenify.common;
// DTO stands for Data Transfer Object.
// is an object that carries data between processes.
// The motivation for its use is that communication between processes is usually done
// resorting to remote interfaces (e.g., web services), where each call is an expensive operation.
public class UserDto {
private Long id;
private String name;
public UserDto() {
}
public UserDto(Long id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@@ -0,0 +1,24 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import greenify.common.ErrorResponse;
import org.junit.Test;
public class ErrorResponseTest {
@Test
public void setAndGetTest() {
ErrorResponse response = new ErrorResponse("New error");
ErrorResponse testResponse = new ErrorResponse();
testResponse.setMessage("New error");
assertTrue(response.getMessage().equals("New error"));
}
@Test
public void equalsTest() {
ErrorResponse first = new ErrorResponse("New error");
ErrorResponse second = new ErrorResponse("New error");
assertEquals(first.getMessage(), second.getMessage());
assertTrue(first.getMessage().equals(second.getMessage()));
}
}

View File

@@ -0,0 +1,25 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import greenify.common.UserDto;
import org.junit.Test;
public class UserDtoTest {
@Test
public void setAndGetTest() {
UserDto user = new UserDto(1L, "greenify");
UserDto testUser = new UserDto();
testUser.setId(1L);
testUser.setName("greenify");
assertTrue(user.getId() == 1L);
assertEquals(user.getName(), "greenify");
}
@Test
public void equalsTest() {
UserDto first = new UserDto(1L, "greenify");
UserDto second = new UserDto(1L, "greenify");
assertEquals(first.getId(), second.getId());
assertEquals(first.getName(), second.getName());
}
}

View File

@@ -15,13 +15,6 @@ apply plugin: 'io.spring.dependency-management'
apply plugin: 'jacoco' apply plugin: 'jacoco'
apply plugin: 'checkstyle' apply plugin: 'checkstyle'
tasks.withType(Checkstyle) {
reports {
html.destination rootProject.file("build/reports/checkstyle.html")
}
}
bootJar { bootJar {
baseName = 'gs-rest-service' baseName = 'gs-rest-service'
version = '0.1.0' version = '0.1.0'
@@ -39,14 +32,33 @@ repositories {
sourceCompatibility = 1.8 sourceCompatibility = 1.8
targetCompatibility = 1.8 targetCompatibility = 1.8
def configDir = "${project.rootDir}/quality"
checkstyle {
toolVersion '7.8.1'
configFile file("$configDir/checkstyle/checkstyle.xml")
configProperties.checkstyleSuppressionsPath = file("$configDir/checkstyle/suppressions.xml").absolutePath
}
checkstyleMain {
source ='src/main/java'
}
checkstyleTest {
source ='src/test/java'
}
dependencies { dependencies {
compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-web")
testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.boot:spring-boot-test')
compile('org.springframework.boot:spring-boot-devtools')
compile project(path: ':src:Common') compile project(path: ':src:Common')
compileOnly 'org.projectlombok:lombok:1.18.6' compileOnly 'org.projectlombok:lombok:1.18.6'
annotationProcessor 'org.projectlombok:lombok:1.18.6' annotationProcessor 'org.projectlombok:lombok:1.18.6'
compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2") compile("com.h2database:h2")
compile("org.springframework.boot:spring-boot-starter-actuator")
testCompile( testCompile(
'junit:junit:4.12', 'junit:junit:4.12',
'org.junit.jupiter:junit-jupiter-api:5.4.0' 'org.junit.jupiter:junit-jupiter-api:5.4.0'
@@ -55,6 +67,7 @@ dependencies {
'org.junit.jupiter:junit-jupiter-engine:5.4.0', 'org.junit.jupiter:junit-jupiter-engine:5.4.0',
'org.junit.vintage:junit-vintage-engine:5.4.0' 'org.junit.vintage:junit-vintage-engine:5.4.0'
) )
compile 'javax.xml.bind:jaxb-api:2.3.0'
} }
jacoco { jacoco {
@@ -70,8 +83,3 @@ jacocoTestReport {
} }
} }
checkstyle {
toolVersion = "7.6.1"
}

View File

@@ -49,7 +49,9 @@ public class User {
return id; return id;
} }
public void setId(Long id) { this.id = id; } public void setId(Long id) {
this.id = id;
}
/** /**
* gets the name. * gets the name.
@@ -59,7 +61,9 @@ public class User {
return name; return name;
} }
public void setName(String name) { this.name = name; } public void setName(String name) {
this.name = name;
}
/** /**
* gets the password. * gets the password.

View File

@@ -1,8 +0,0 @@
package greenify.server.data.repository;
import greenify.server.data.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserJpaRepository extends UserRepository, JpaRepository<User,Long> {
}

View File

@@ -1,8 +1,11 @@
package greenify.server.data.repository; package greenify.server.data.repository;
import greenify.server.data.model.User; import greenify.server.data.model.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository { public interface UserRepository extends CrudRepository<User, Integer> {
User findByName(String name); User findByName(String name);
<T extends User> T save(T user); <T extends User> T save(T user);
} }

View File

@@ -0,0 +1,38 @@
package greenify.server.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import greenify.server.data.model.User;
import greenify.server.data.repository.UserRepository;
@Controller // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
@GetMapping(path="/add") // Map ONLY GET Requests
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String password) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setPassword(password);
userRepository.save(n);
return "Saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}

View File

@@ -1,10 +1,14 @@
package greenify.server.rest; package greenify.server.rest;
import greenify.common.UserDTO; import greenify.common.UserDto;
import greenify.server.data.model.User;
import greenify.server.data.repository.UserRepository;
import greenify.server.service.UserService; import greenify.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@@ -12,15 +16,32 @@ public class UserController {
@Autowired @Autowired
UserService userService; UserService userService;
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
UserRepository userRepository;
@RequestMapping("/registerUser") @RequestMapping("/registerUser")
public UserDTO registerUser(@RequestParam(value = "name") String name, public UserDto registerUser(@RequestParam(value = "name") String name,
@RequestParam(value = "password") String password) { @RequestParam(value = "password") String password) {
return userService.registerUser(name, password); return userService.registerUser(name, password);
} }
@RequestMapping("/login") @RequestMapping("/loginUser")
public UserDTO login(@RequestParam(value = "name") String name, public UserDto loginUser(@RequestParam(value = "name") String name,
@RequestParam(value = "password") String password) { @RequestParam(value = "password") String password) {
return userService.login(name, password); return userService.loginUser(name, password);
}
@RequestMapping("/addVeganMeal")
public void addVeganMeal(@RequestParam(value = "id") Long id,
@RequestParam(value = "name") String name) {
userService.addVeganMeal(id, name);
}
@GetMapping(path = "/all")
@ResponseBody
public Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
} }
} }

View File

@@ -1,7 +1,7 @@
package greenify.server.service; package greenify.server.service;
import greenify.common.ApplicationException; import greenify.common.ApplicationException;
import greenify.common.UserDTO; import greenify.common.UserDto;
import greenify.server.data.model.User; import greenify.server.data.model.User;
import greenify.server.data.repository.UserRepository; import greenify.server.data.repository.UserRepository;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -21,15 +21,15 @@ public class UserService {
* @param password the password of the user * @param password the password of the user
* @return a userDTO of the registered user * @return a userDTO of the registered user
*/ */
public UserDTO registerUser(String name, String password) { public UserDto registerUser(String name, String password) {
User user = userRepository.findByName(name); User user = userRepository.findByName(name);
if (user != null) { if (user == null) {
throw new ApplicationException("User already exists");
} else {
user = userRepository.save(new User(null, name, password, 0)); user = userRepository.save(new User(null, name, password, 0));
} else {
throw new ApplicationException("User already exists");
} }
logger.info("Created user id=" + user.getId() + ", name=" + user.getName()); logger.info("Created user id=" + user.getId() + ", name=" + user.getName());
return new UserDTO(user.getId(), user.getName()); return new UserDto(user.getId(), user.getName());
} }
/** /**
@@ -38,7 +38,7 @@ public class UserService {
* @param password the password of the user * @param password the password of the user
* @return a userDTO of the logged in user * @return a userDTO of the logged in user
*/ */
public UserDTO login(String name, String password) { public UserDto loginUser(String name, String password) {
User user = userRepository.findByName(name); User user = userRepository.findByName(name);
if (user == null) { if (user == null) {
throw new ApplicationException("User does not exist"); throw new ApplicationException("User does not exist");
@@ -47,6 +47,22 @@ public class UserService {
throw new ApplicationException("Wrong password"); throw new ApplicationException("Wrong password");
} }
} }
return new UserDTO(user.getId(), user.getName()); return new UserDto(user.getId(), user.getName());
}
/**
* add vegan meal to the user.
* @param id the id of the user
* @param name the name of the user
*/
public void addVeganMeal(Long id, String name) {
User user = userRepository.findByName(name);
int count = user.getVeganMeal();
count++;
user.setVeganMeal(count);
userRepository.save(user);
logger.info("Added vegan meal to user(id=" + user.getId()
+ ", name=" + user.getName() + ")");
} }
} }

View File

@@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:file:~/spring-boot-h2.db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

View File

@@ -1,16 +1,12 @@
import greenify.server.Application;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootConfiguration
public class ApplicationTest { public class ApplicationTest {
@Test
public void applicationContextLoaded() {
}
@Test @Test
public void applicationContextTest() { public void contextLoads() throws Exception{ }
Application.main(new String[] {});
}
} }

View File

@@ -1,46 +1,46 @@
import greenify.common.UserDTO; //import greenify.common.UserDTO;
import greenify.server.Application; //import greenify.server.Application;
import org.junit.Assert; //import org.junit.Assert;
import org.junit.Test; //import org.junit.Test;
import org.junit.runner.RunWith; //import org.junit.runner.RunWith;
import org.slf4j.Logger; //import org.slf4j.Logger;
import org.slf4j.LoggerFactory; //import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.LocalServerPort; //import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*; //import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner; //import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.HttpStatusCodeException; //import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate; //import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder; //import org.springframework.web.util.UriComponentsBuilder;
//
@RunWith(SpringRunner.class) //@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest { //public class UserControllerTest {
private static Logger logger = LoggerFactory.getLogger(UserControllerTest.class); // private static Logger logger = LoggerFactory.getLogger(UserControllerTest.class);
//
@LocalServerPort // @LocalServerPort
private int port; // private int port;
//
private RestTemplate restTemplate = new RestTemplate(); // private RestTemplate restTemplate = new RestTemplate();
//
@Test // @Test
public void registerUserTest() { // public void registerUserTest() {
HttpHeaders headers = new HttpHeaders(); // HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); // headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + "/registerUser") // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + "/registerUser")
.queryParam("name", "ceren") // .queryParam("name", "ceren")
.queryParam("password", "password"); // .queryParam("password", "password");
HttpEntity<?> entity = new HttpEntity<>(headers); // HttpEntity<?> entity = new HttpEntity<>(headers);
UserDTO user = this.restTemplate.getForObject(builder.build().encode().toUri(), UserDTO.class); // UserDTO user = this.restTemplate.getForObject(builder.build().encode().toUri(), UserDTO.class);
Assert.assertNotNull(user); // Assert.assertNotNull(user);
Assert.assertEquals(user.getId().longValue(), 1L); // Assert.assertEquals(user.getId().longValue(), 1L);
try { // try {
user = this.restTemplate.getForObject(builder.build().encode().toUri(), UserDTO.class); // user = this.restTemplate.getForObject(builder.build().encode().toUri(), UserDTO.class);
Assert.fail("Error should be reported"); // Assert.fail("Error should be reported");
} catch (HttpStatusCodeException exception) { // } catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value(); // int statusCode = exception.getStatusCode().value();
Assert.assertEquals(statusCode, 400); // Assert.assertEquals(statusCode, 400);
Assert.assertTrue(exception.getResponseBodyAsString().contains("User already exists")); // Assert.assertTrue(exception.getResponseBodyAsString().contains("User already exists"));
} // }
} // }
} //}

View File

@@ -55,3 +55,4 @@ public class UserTest {
assertTrue(first.hashCode() == second.hashCode()); assertTrue(first.hashCode() == second.hashCode());
} }
} }

View File

@@ -0,0 +1,48 @@
package greenify.server.data.model;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class UserTest {
@Test
public void setAndGetTest() {
User testUser = new User();
testUser.setId(1L);
testUser.setName("greenify");
testUser.setPassword("password");
testUser.setVeganMeal(3);
User user = new User(1L, "greenify", "password", 3);
assertTrue(user.getId().equals(1L));
assertEquals(user.getName(), "greenify");
assertEquals(user.getPassword(), "password");
assertEquals(user.getVeganMeal(), 3);
assertEquals(user, testUser);
}
@Test
public void toStringTest() {
User user = new User(1L, "greenify", "password", 3);
assertEquals("User(id=1, name=greenify, password=password, veganMeal=3)", user.toString());
}
@Test
public void equalsTest() {
User first = new User(1L, "greenify", "password", 3);
User second = new User(1L, "greenify", "password", 3);
assertEquals(first.getId(), second.getId());
assertEquals(first.getName(), second.getName());
assertEquals(first.getPassword(), second.getPassword());
assertEquals(first.getVeganMeal(), second.getVeganMeal());
}
@Test
public void hashCodeTest() {
User first = new User(1L, "greenify", "password", 3);
User second = new User(1L, "greenify", "password", 3);
assertTrue(first.equals(second) && second.equals(first));
assertTrue(first.hashCode() == second.hashCode());
}
}

View File

@@ -0,0 +1,37 @@
//package greenify.server.data.repository;
//
//import greenify.server.data.model.User;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
//import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import static junit.framework.TestCase.assertTrue;
//import static org.junit.Assert.assertEquals;
//
//@RunWith(SpringRunner.class)
//@DataJpaTest
//public class UserRepositoryTest {
//
// @Autowired
// private TestEntityManager entityManager;
//
// @Autowired
// private UserRepository repository;
//
// @Test
// public void findByUsernameShouldReturnUser() throws Exception {
// this.entityManager.persist(new User(296L, "cugurlu", "password", 6));
// User user = this.repository.findByName("cugurlu");
// assertEquals(user.getName(), "cugurlu");
// }
//
// @Test
// public void findByUsernameWhenNoUserShouldReturnNull() throws Exception {
// this.entityManager.persist(new User(296L, "cugurlu", "password", 6));
// User user = this.repository.findByName("mouse");
// assertTrue(user == null);
// }
//}

View File

@@ -0,0 +1,63 @@
//package greenify.server.rest;
//
//import greenify.common.UserDto;
//import greenify.server.data.model.User;
//import greenify.server.service.UserService;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.boot.test.mock.mockito.MockBean;
//import org.springframework.context.ApplicationContext;
//import org.springframework.http.MediaType;
//import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.test.web.servlet.MockMvc;
//import org.springframework.test.web.servlet.ResultMatcher;
//import static org.assertj.core.internal.bytebuddy.matcher.ElementMatchers.is;
//import static org.hamcrest.Matchers.hasSize;
//import static org.mockito.BDDMockito.given;
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest
//@AutoConfigureMockMvc
//@AutoConfigureTestDatabase
//public class UserControllerTest {
//
// @Autowired
// private MockMvc mvc;
//
// @Autowired
// private ApplicationContext applicationContext;
//
// @MockBean
// private UserService userService;
//
// @Test
// public void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception {
// given(this.userService.loginUser("name", "password"))
// .willReturn(new UserDto(1L, "name"));
// this.mvc.perform(get("/loginUser").accept(MediaType.APPLICATION_JSON))
// .andExpect(status().isOk())
// .andExpect(content()
// .json("name=name, password=password"));
// }
//
//
// @Test
// public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception {
// User alex = new User(1L, "alex", "password", 0);
// UserDto user = userService.loginUser("alex", "password");
// given(userService.loginUser("alex", "password")).willReturn(user);
// mvc.perform(get("/loginUser")
// .contentType(MediaType.ALL))
// .andExpect(status().isOk())
// .andExpect(jsonPath("$", hasSize(1)))
// .andExpect((ResultMatcher) jsonPath("$[0].name", is(alex.getName())))
// .andExpect((ResultMatcher) jsonPath("$[0].password", is(alex.getPassword())));
// }
//}

View File

@@ -0,0 +1,70 @@
package greenify.server.service;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import greenify.common.ApplicationException;
import greenify.common.UserDto;
import greenify.server.data.model.User;
import greenify.server.data.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class UserServiceTest {
@TestConfiguration
static class UserServiceConfiguration {
@Bean
public UserService userService() {
return new UserService();
}
}
@Autowired
private UserService userService;
@MockBean
private UserRepository userRepository;
/**
* setUp method for test.
*/
@Before
public void setUp() {
User alex = new User(1L, "alex", "password", 0);
when(userRepository.findByName(alex.getName()))
.thenReturn(alex);
}
@Test
public void validLoginTest() {
String name = "alex";
String password = "password";
UserDto found = userService.loginUser(name, password);
assertEquals(found.getName(), name);
}
// @Test
// public void addVeganMealTest() {
// User user = new User(1L, "x", "y", 3);
// userRepository.save(user);
// System.out.println(userRepository);
// userService.addVeganMeal(1L, "x");
// assertEquals(user.getVeganMeal(), 7);
// }
@Test
public void invalidLoginTest() {
User user = null;
assertThrows(ApplicationException.class, () -> {
userService.loginUser(null, null);
});
}
}