├── ui-service
├── .gitignore
├── serverless-single-page-app-plugin
│ ├── package.json
│ └── index.js
├── app
│ ├── index.html
│ └── scripts
│ │ ├── app-bundle.js.map
│ │ └── app-bundle.js
├── package.json
└── serverless.yml
├── candidate-service
├── .gitignore
├── .npmignore
├── data
│ ├── submit-event.1.json
│ ├── submit-event.json
│ └── send-assignment-event.json
├── README.md
├── package.json
├── serverless.yml
└── api
│ └── candidate.js
├── .gitignore
├── images
└── coding-round-evaluator.png
├── assignment-sender-service
├── src
│ ├── test
│ │ ├── resources
│ │ │ ├── gradle.properties
│ │ │ └── assignment.zip
│ │ └── scala
│ │ │ └── assignmentsender
│ │ │ ├── BaseTestSpec.scala
│ │ │ ├── AssignmentPreparatorSpec.scala
│ │ │ ├── AssignmentSenderSpec.scala
│ │ │ └── AssignmentSenderHandlerSpec.scala
│ └── main
│ │ ├── scala
│ │ └── assignmentsender
│ │ │ ├── Logging.scala
│ │ │ ├── package.scala
│ │ │ ├── chooser
│ │ │ └── AssignmentChooser.scala
│ │ │ ├── s3
│ │ │ └── S3Helper.scala
│ │ │ ├── email
│ │ │ └── EmailSender.scala
│ │ │ ├── preparator
│ │ │ └── AssignmentPreparator.scala
│ │ │ ├── AssignmentSenderHandler.scala
│ │ │ └── AssignmentSender.scala
│ │ └── resources
│ │ └── log4j.properties
├── project
│ ├── assembly.sbt
│ └── plugins.sbt
├── .npmignore
├── README.md
├── build.sbt
├── serverless.yml
└── .gitignore
├── assignment-build-executor-service
├── src
│ ├── test
│ │ └── resources
│ │ │ ├── myapp.zip
│ │ │ ├── myapp-build-failure.zip
│ │ │ └── not_supported_project.zip
│ └── main
│ │ ├── java
│ │ └── xebia
│ │ │ └── lcre
│ │ │ ├── exceptions
│ │ │ ├── UnknowBuildPackage.java
│ │ │ ├── UnableToRunCommand.java
│ │ │ └── UnableToCreateBuildPackage.java
│ │ │ ├── BuildExecutor.java
│ │ │ ├── utils
│ │ │ ├── FileUtils.java
│ │ │ └── ZipHelpers.java
│ │ │ ├── pkg
│ │ │ └── creators
│ │ │ │ ├── BuildPackage.java
│ │ │ │ └── BuildPackageCreator.java
│ │ │ └── BuildHandler.java
│ │ └── resources
│ │ ├── log4j.properties
│ │ └── scripts
│ │ └── java.sh
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── .npmignore
├── README.md
├── build.gradle
├── .gitignore
├── serverless.yml
├── gradlew.bat
└── gradlew
├── README.md
└── LICENSE
/ui-service/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .serverless
3 |
--------------------------------------------------------------------------------
/candidate-service/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .serverless/
3 | env.yml
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .serverless/
3 | .idea/
4 | node_modules/
5 | build/
6 | target/
7 | env.yml
8 |
--------------------------------------------------------------------------------
/candidate-service/.npmignore:
--------------------------------------------------------------------------------
1 | # package directories
2 | node_modules
3 | jspm_packages
4 |
5 | # Serverless directories
6 | .serverless
--------------------------------------------------------------------------------
/images/coding-round-evaluator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/images/coding-round-evaluator.png
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/resources/gradle.properties:
--------------------------------------------------------------------------------
1 | assignmentName=assignment-123.zip
2 | assignmentSubmissionUrl=http://example.com/submit
--------------------------------------------------------------------------------
/candidate-service/data/submit-event.1.json:
--------------------------------------------------------------------------------
1 | {
2 | "body": "{\"name\":\"Shekhar Gulati\", \"email\":\"shekhar.gulati@gmail.com\", \"experience\":9}"
3 | }
--------------------------------------------------------------------------------
/candidate-service/data/submit-event.json:
--------------------------------------------------------------------------------
1 | {
2 | "body": "{\"name\":\"Shekhar Gulati\", \"email\":\"shekhargulati84@gmail.com\", \"experience\":12}"
3 | }
--------------------------------------------------------------------------------
/assignment-sender-service/project/assembly.sbt:
--------------------------------------------------------------------------------
1 | resolvers += Resolver.sonatypeRepo("public")
2 |
3 | addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.0")
--------------------------------------------------------------------------------
/assignment-sender-service/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.0")
2 | addSbtPlugin("net.virtual-void" %% "sbt-dependency-graph" % "0.8.1")
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/resources/assignment.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/assignment-sender-service/src/test/resources/assignment.zip
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/test/resources/myapp.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/assignment-build-executor-service/src/test/resources/myapp.zip
--------------------------------------------------------------------------------
/assignment-build-executor-service/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/assignment-build-executor-service/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/test/resources/myapp-build-failure.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/assignment-build-executor-service/src/test/resources/myapp-build-failure.zip
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/test/resources/not_supported_project.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xebia-os/lambda-coding-round-evaluator/HEAD/assignment-build-executor-service/src/test/resources/not_supported_project.zip
--------------------------------------------------------------------------------
/assignment-build-executor-service/.npmignore:
--------------------------------------------------------------------------------
1 | *.class
2 | .gradle
3 | /build/
4 | /bin/
5 | /.settings/
6 | .project
7 | .classpath
8 |
9 | # Package Files
10 | *.jar
11 | *.war
12 | *.ear
13 |
14 | # Serverless directories
15 | .serverless
16 |
17 |
--------------------------------------------------------------------------------
/assignment-sender-service/.npmignore:
--------------------------------------------------------------------------------
1 | *.class
2 | *.log
3 |
4 | # sbt specific
5 | .cache
6 | .history
7 | .lib/
8 | dist/*
9 | target/
10 | lib_managed/
11 | src_managed/
12 | project/boot/
13 | project/plugins/project/
14 |
15 | # Serverless directories
16 | .serverless
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/exceptions/UnknowBuildPackage.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.exceptions;
2 |
3 | public class UnknowBuildPackage extends RuntimeException {
4 | public UnknowBuildPackage(String msg) {
5 | super(msg);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/candidate-service/README.md:
--------------------------------------------------------------------------------
1 | candidate-service
2 | ----
3 |
4 |
5 | This is Node based Serverless component. It is built using Serverless framework `aws-nodejs` template.
6 |
7 | To deploy this project, you have to do following:
8 |
9 | ```
10 | $ serverless deploy -v
11 | ```
--------------------------------------------------------------------------------
/ui-service/serverless-single-page-app-plugin/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "serverless-single-page-app-plugin",
3 | "version": "1.0.0",
4 | "description": "A plugin to simplify deploying Single Page Application using S3 and CloudFront",
5 | "author": "",
6 | "license": "MIT"
7 | }
8 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/Logging.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import org.apache.log4j.Logger
4 |
5 | trait Logging {
6 |
7 | private lazy val _logger = Logger.getLogger(getClass)
8 |
9 | protected def logger: Logger = _logger
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/scala/assignmentsender/BaseTestSpec.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 | import org.scalatest.mockito.MockitoSugar
5 |
6 | trait BaseTestSpec extends FunSpec
7 | with MockitoSugar
8 | with Matchers {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/exceptions/UnableToRunCommand.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.exceptions;
2 |
3 | public class UnableToRunCommand extends RuntimeException {
4 | public UnableToRunCommand(String message, Throwable cause) {
5 | super(message, cause);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Feb 15 13:33:08 IST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/assignment-sender-service/README.md:
--------------------------------------------------------------------------------
1 | assignment-sender-service
2 | ----
3 |
4 | This is Scala based Serverless component. It is built using Serverless framework `aws-scala-sbt` template.
5 |
6 | To deploy this project, you have to do following:
7 |
8 | ```
9 | $ sbt clean assembly
10 | $ serverless deploy -v
11 | ```
--------------------------------------------------------------------------------
/ui-service/app/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Lambda Coding Round Evaluator
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/exceptions/UnableToCreateBuildPackage.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.exceptions;
2 |
3 | public class UnableToCreateBuildPackage extends RuntimeException {
4 |
5 | public UnableToCreateBuildPackage(String message, Throwable cause) {
6 | super(message, cause);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/README.md:
--------------------------------------------------------------------------------
1 | assignment-build-executor-service
2 | -----
3 |
4 |
5 | This is Java based Serverless component. It is built using Serverless framework `aws-java-gradle` template.
6 |
7 | To deploy this project, you have to do following:
8 |
9 | ```
10 | $ ./gradlew clean build
11 | $ serverless deploy -v
12 | ```
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log = .
2 | log4j.rootLogger = INFO, LAMBDA
3 |
4 | log4j.appender.LAMBDA=com.amazonaws.services.lambda.runtime.log4j.LambdaAppender
5 | log4j.appender.LAMBDA.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.LAMBDA.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} <%X{AWSRequestId}> %-5p %c{1}:%L - %m%n
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log = .
2 | log4j.rootLogger = INFO, LAMBDA
3 |
4 | log4j.appender.LAMBDA=com.amazonaws.services.lambda.runtime.log4j.LambdaAppender
5 | log4j.appender.LAMBDA.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.LAMBDA.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} <%X{AWSRequestId}> %-5p %c:%L - %m%n
7 |
--------------------------------------------------------------------------------
/candidate-service/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "candidate-service",
3 | "version": "1.0.0",
4 | "description": "REST API backend for candidate",
5 | "author": "Shekhar Gulati",
6 | "license": "MIT",
7 | "dependencies": {
8 | "bluebird": "^3.4.7",
9 | "ramda": "^0.23.0",
10 | "uuid": "^2.0.3"
11 | },
12 | "devDependencies": {
13 | "aws-sdk": "^2.12.0"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ui-service/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "aws-single-page-app-via-cloudfront",
3 | "version": "1.0.0",
4 | "description": "Demonstrating how to deploy a Single Page Application with Serverless",
5 | "repository": "",
6 | "author": "",
7 | "license": "MIT",
8 | "devDependencies": {
9 | "serverless-single-page-app-plugin": "file:./serverless-single-page-app-plugin"
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/BuildExecutor.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre;
2 |
3 | import xebia.lcre.build.executors.LambdaBuildExecutor;
4 | import xebia.lcre.build.result.BuildResult;
5 | import xebia.lcre.build.spec.BuildSpecificationBuilder;
6 | import xebia.lcre.pkg.creators.BuildPackage;
7 |
8 | public interface BuildExecutor {
9 |
10 | static BuildExecutor newRunner(BuildSpecificationBuilder buildSpecificationBuilder) {
11 | return new LambdaBuildExecutor(buildSpecificationBuilder);
12 | }
13 |
14 | BuildResult execute(BuildPackage buildPackage);
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.utils;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Path;
6 |
7 | public abstract class FileUtils {
8 |
9 | public static File createFile(Path parent, String cmdId, String filename) throws IOException {
10 | File outputFile = parent.resolve(String.format("%s-%s", cmdId, filename)).toFile();
11 | if (!outputFile.createNewFile()) {
12 | throw new RuntimeException(String.format("Unable to create file %s", outputFile));
13 | }
14 | return outputFile;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/package.scala:
--------------------------------------------------------------------------------
1 | import java.io.File
2 | import java.net.URL
3 | import java.nio.file.Path
4 |
5 | import scala.util.Try
6 |
7 | package object assignmentsender {
8 |
9 | case class Result(messageId: String, httpStatusCode: Int)
10 |
11 | case class Assignment(assignmentUrl: String, skills: List[String], experience: Int)
12 |
13 | case class Candidate(id: String, fullname: String, email: String, experience: Int, skills: String)
14 |
15 | type CandidateId = String
16 | type AssignmentUrl = String
17 | type AssignmentLocalFile = File
18 | type AssignmentLocalPath = Path
19 |
20 | type AssignmentChooserF = Candidate => Assignment
21 | type AssignmentPreparatorF = ((Assignment, CandidateId, URL) => Try[AssignmentLocalPath])
22 | type AssignmentDownloaderF = (AssignmentUrl, CandidateId) => AssignmentLocalFile
23 | type AddGradlePropertiesToZipF = (AssignmentLocalFile, Path) => AssignmentLocalFile
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/resources/scripts/java.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | VERSION=${1:-1.8}
5 |
6 | echo "Installing OpenJDK ${VERSION}..."
7 |
8 | export JAVA_HOME=$(echo /tmp/usr/lib/jvm/java-${VERSION}.0-openjdk-${VERSION}*)
9 |
10 | if ! [ -d $JAVA_HOME ]; then
11 | set -x
12 | curl -sSL https://lambci.s3.amazonaws.com/binaries/java-${VERSION}.0-openjdk-devel.tgz | tar -xz -C /tmp
13 |
14 | # For some reason, libjvm.so needs to be physically present
15 | # Can't symlink it, have to copy, but everything else can be symlinks
16 | export JAVA_HOME=$(echo /tmp/usr/lib/jvm/java-${VERSION}.0-openjdk-${VERSION}*)
17 | cp -as /usr/lib/jvm/java-${VERSION}*/jre $JAVA_HOME/
18 | rm $JAVA_HOME/jre/lib/amd64/server/libjvm.so
19 | cp /usr/lib/jvm/java-${VERSION}*/jre/lib/amd64/server/libjvm.so $JAVA_HOME/jre/lib/amd64/server/
20 | set +x
21 | fi
22 | export PATH=$JAVA_HOME/bin:$PATH
23 | export _JAVA_OPTIONS="-Duser.home=$HOME"
24 |
25 | echo "OpenJDK setup complete"
26 | echo ""
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/pkg/creators/BuildPackage.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.pkg.creators;
2 |
3 | import java.nio.file.Path;
4 |
5 | public class BuildPackage {
6 | private final String name;
7 | private final Path codeZipPath;
8 | private final String candidateId;
9 |
10 | public BuildPackage(String name, Path codeZipPath, String candidateId) {
11 | this.name = name;
12 | this.codeZipPath = codeZipPath;
13 | this.candidateId = candidateId;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public Path getCodeZipPath() {
21 | return codeZipPath;
22 | }
23 |
24 | public String getCandidateId() {
25 | return candidateId;
26 | }
27 |
28 | @Override
29 | public String toString() {
30 | return "BuildPackage{" +
31 | "name='" + name + '\'' +
32 | ", codeZipPath=" + codeZipPath +
33 | ", candidateId='" + candidateId + '\'' +
34 | '}';
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/assignment-sender-service/build.sbt:
--------------------------------------------------------------------------------
1 | import sbt.Keys._
2 | import sbt._
3 | import sbtrelease.Version
4 |
5 | name := "assignment-sender-service"
6 |
7 | scalaVersion := "2.11.8"
8 | releaseNextVersion := { ver => Version(ver).map(_.bumpMinor.string).getOrElse("Error") }
9 | assemblyJarName in assembly := "assignment-sender-service.jar"
10 | cleanKeepFiles ++= Seq("resolution-cache", "streams").map(target.value / _)
11 | offline := true
12 | parallelExecution := false
13 |
14 | libraryDependencies ++= Seq(
15 | "com.amazonaws" % "aws-java-sdk-core" % "1.11.99",
16 | "com.amazonaws" % "aws-java-sdk-ses" % "1.11.99",
17 | "com.amazonaws" % "aws-java-sdk-s3" % "1.11.99",
18 | "com.amazonaws" % "aws-java-sdk-dynamodb" % "1.11.99",
19 | "com.amazonaws" % "aws-lambda-java-events" % "1.1.0" intransitive(),
20 | "com.amazonaws" % "aws-lambda-java-core" % "1.1.0",
21 | "org.zeroturnaround" % "zt-zip" % "1.11",
22 | "org.slf4j" % "slf4j-log4j12" % "1.7.24",
23 | "com.amazonaws" % "aws-lambda-java-log4j" % "1.0.0",
24 | "org.scalatest" %% "scalatest" % "3.0.1" % "test",
25 | "org.mockito" % "mockito-core" % "2.7.14" % "test"
26 | )
27 |
28 | scalacOptions ++= Seq(
29 | "-unchecked",
30 | "-deprecation",
31 | "-feature",
32 | "-Xfatal-warnings")
33 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/chooser/AssignmentChooser.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender.chooser
2 |
3 | import assignmentsender.{Assignment, AssignmentChooserF, Candidate}
4 |
5 | class AssignmentChooser(assignmentsS3Bucket: String)
6 | extends AssignmentChooserF {
7 |
8 | override def apply(candidate: Candidate): Assignment = {
9 | val experience = candidate.experience
10 | val skills = List(candidate.skills)
11 | if (experience > 0 && experience <= 5) {
12 | Assignment(
13 | s"https://s3.amazonaws.com/$assignmentsS3Bucket/assignment1.zip",
14 | skills,
15 | experience
16 | )
17 | } else if (experience > 5 && experience <= 8) {
18 | Assignment(
19 | s"https://s3.amazonaws.com/$assignmentsS3Bucket/assignment2.zip",
20 | skills,
21 | experience
22 | )
23 | } else {
24 | Assignment(
25 | s"https://s3.amazonaws.com/$assignmentsS3Bucket/assignment3.zip",
26 | skills,
27 | experience
28 | )
29 | }
30 | }
31 | }
32 |
33 | object AssignmentChooser {
34 | def apply(assignmentsS3Bucket: String = sys.env("LCRE_ASSIGNMENTS_BUCKET")): AssignmentChooser = new AssignmentChooser(assignmentsS3Bucket)
35 | }
36 |
37 |
38 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/s3/S3Helper.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender.s3
2 |
3 | import java.io.File
4 | import java.net.URL
5 | import java.util.Date
6 |
7 | import com.amazonaws.HttpMethod
8 | import com.amazonaws.services.s3.AmazonS3
9 | import com.amazonaws.services.s3.model.{CannedAccessControlList, GeneratePresignedUrlRequest, PutObjectRequest}
10 |
11 | import scala.util.Try
12 |
13 | trait S3Helper {
14 | val s3Client: AmazonS3
15 |
16 | def putFileInS3Bucket(bucket: String, fileToUpload: File): Try[URL] = {
17 | Try {
18 | s3Client.putObject(new PutObjectRequest(bucket, fileToUpload.getName, fileToUpload).withCannedAcl(CannedAccessControlList.PublicRead))
19 | s3Client.getUrl(bucket, fileToUpload.getName)
20 | }
21 | }
22 |
23 | def createPreSignedUrl(bucket: String, filename: String): Try[URL] = {
24 | Try {
25 | val expiration = new Date()
26 | var msec = expiration.getTime
27 | msec += 7 * 24 * 1000 * 60 * 60
28 | expiration.setTime(msec)
29 | val generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, filename)
30 | generatePresignedUrlRequest.setMethod(HttpMethod.PUT)
31 | generatePresignedUrlRequest.setExpiration(expiration)
32 | s3Client.generatePresignedUrl(generatePresignedUrlRequest)
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/utils/ZipHelpers.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.utils;
2 |
3 | import org.apache.commons.io.FileUtils;
4 | import org.zeroturnaround.zip.FileSource;
5 | import org.zeroturnaround.zip.ZipEntrySource;
6 | import org.zeroturnaround.zip.ZipUtil;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.nio.file.Path;
12 | import java.nio.file.Paths;
13 | import java.util.Arrays;
14 |
15 | public abstract class ZipHelpers {
16 |
17 | public static Path downloadZipTo(InputStream in, String filename, String dest) throws IOException {
18 | File assignmentZipFile = Paths.get(dest, filename).toFile();
19 | FileUtils.copyInputStreamToFile(in, assignmentZipFile);
20 | return assignmentZipFile.toPath();
21 | }
22 |
23 | public static Path unzipTo(Path srcZipPath, Path extractionDir) {
24 | ZipUtil.unpack(srcZipPath.toFile(), extractionDir.toFile());
25 | return extractionDir;
26 | }
27 |
28 | public static Path zip(Path zipPath, File rootDir, File... filesToZip) {
29 | File zip = zipPath.toFile();
30 | ZipUtil.pack(rootDir, zip);
31 | ZipUtil.addEntries(
32 | zip,
33 | Arrays.stream(filesToZip).map(f -> new FileSource(f.getName(), f)).toArray(ZipEntrySource[]::new)
34 | );
35 | return zipPath;
36 | }
37 | }
38 |
39 |
40 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 |
3 | repositories {
4 | mavenCentral()
5 | }
6 |
7 | sourceCompatibility = 1.8
8 | targetCompatibility = 1.8
9 |
10 | dependencies {
11 | compile (
12 | 'com.amazonaws:aws-lambda-java-core:1.1.0',
13 | 'com.amazonaws:aws-lambda-java-log4j:1.0.0',
14 | 'com.fasterxml.jackson.core:jackson-core:2.8.5',
15 | 'com.fasterxml.jackson.core:jackson-databind:2.8.5',
16 | 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
17 | )
18 | compile('com.amazonaws:aws-lambda-java-events:1.3.0'){
19 | exclude module: 'aws-java-sdk-kinesis'
20 | exclude module: 'aws-java-sdk-kms'
21 | exclude module: 'aws-java-sdk-sqs'
22 | exclude module: 'aws-java-sdk-cognitoidentity'
23 | exclude module: 'aws-java-sdk-sns'
24 | }
25 |
26 | compile "commons-io:commons-io:2.5"
27 | compile('org.zeroturnaround:zt-zip:1.11')
28 | testCompile "junit:junit:4.12"
29 | testCompile 'org.assertj:assertj-core:3.6.2'
30 | testCompile 'org.mockito:mockito-core:2.7.6'
31 | }
32 |
33 | task buildZip(type: Zip) {
34 | baseName = "assignment-build-executor-service"
35 | from compileJava
36 | from processResources
37 | into('lib') {
38 | from configurations.runtime
39 | }
40 | }
41 |
42 | build.dependsOn buildZip
43 |
44 | task wrapper(type: Wrapper) {
45 | gradleVersion = '3.3'
46 | }
47 |
--------------------------------------------------------------------------------
/assignment-sender-service/serverless.yml:
--------------------------------------------------------------------------------
1 | service: assignment-sender-service
2 |
3 | provider:
4 | name: aws
5 | runtime: java8
6 | region: us-east-1
7 | stage: dev
8 | environment:
9 | LCRE_CANDIDATE_SUBMISSIONS_S3_BUCKET: "${self:custom.s3BucketPrefix}-candidate-submissions-${self:provider.stage}"
10 | CANDIDATE_TABLE: candidate-${opt:stage, self:provider.stage}
11 | LCRE_ASSIGNMENTS_BUCKET: "${self:custom.s3BucketPrefix}-assignments-${self:provider.stage}"
12 | SOURCE_EMAIL: ${self:custom.sourceEmail}
13 | iamRoleStatements:
14 | - Effect: "Allow"
15 | Resource: "*"
16 | Action:
17 | - "dynamodb:*"
18 | - Effect: "Allow"
19 | Action:
20 | - "s3:*"
21 | Resource: "*"
22 | - Effect: Allow
23 | Action:
24 | - "ses:SendEmail"
25 | Resource: "*"
26 |
27 | custom:
28 | awsAccountNumber: ${file(./env.yml):awsAccountNumber}
29 | candidateTableStreamTimestamp: ${file(./env.yml):candidateTableStreamTimestamp}
30 | s3BucketPrefix: lcre
31 | sourceEmail: ${file(./env.yml):sourceEmail}
32 |
33 | package:
34 | artifact: target/scala-2.11/assignment-sender-service.jar
35 |
36 | functions:
37 | sendAssignment:
38 | handler: assignmentsender.AssignmentSenderHandler
39 | events:
40 | - stream: arn:aws:dynamodb:${self:provider.region}:${self:custom.awsAccountNumber}:table/${self:provider.environment.CANDIDATE_TABLE}/stream/${self:custom.candidateTableStreamTimestamp}
41 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Gradle template
3 | .gradle/
4 | /build/
5 |
6 | # Ignore Gradle GUI config
7 | gradle-app.setting
8 |
9 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
10 | !gradle/wrapper/gradle-wrapper.jar
11 |
12 | # Cache of project
13 | .gradletasknamecache
14 |
15 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
16 | # gradle/wrapper/gradle-wrapper.properties
17 | ### JetBrains template
18 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
19 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
20 |
21 | # User-specific stuff:
22 |
23 | # Sensitive or high-churn files:
24 | .idea/
25 |
26 | ## File-based project format:
27 | *.iws
28 |
29 | ## Plugin-specific files:
30 |
31 | # IntelliJ
32 | /out/
33 |
34 | # mpeltonen/sbt-idea plugin
35 | .idea_modules/
36 |
37 | # JIRA plugin
38 | atlassian-ide-plugin.xml
39 |
40 | # Crashlytics plugin (for Android Studio and IntelliJ)
41 | com_crashlytics_export_strings.xml
42 | crashlytics.properties
43 | crashlytics-build.properties
44 | fabric.properties
45 | ### Java template
46 | *.class
47 |
48 | # BlueJ files
49 | *.ctxt
50 |
51 | # Mobile Tools for Java (J2ME)
52 | .mtj.tmp/
53 |
54 | # Package Files #
55 | *.war
56 | *.ear
57 |
58 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
59 | hs_err_pid*
60 |
61 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/email/EmailSender.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender.email
2 |
3 | import java.net.URL
4 |
5 | import assignmentsender.Candidate
6 | import com.amazonaws.services.simpleemail.AmazonSimpleEmailService
7 | import com.amazonaws.services.simpleemail.model._
8 |
9 | import scala.util.Try
10 |
11 | class EmailSender(emailClient: AmazonSimpleEmailService, sourceEmail: String = sys.env("SOURCE_EMAIL")) {
12 |
13 | def sendEmail(candidate: Candidate, candidateAssignmentUrl: URL): Try[SendEmailResult] = {
14 | Try {
15 | val destination = new Destination().withToAddresses(candidate.email)
16 | val subject = new Content().withData("Coding Round with Awesome Company")
17 | val textBody = new Content().withData(
18 | s"""
19 | |Hello ${candidate.fullname},
20 |
21 | |Thanks for applying position with us. Please download assignment from $candidateAssignmentUrl.
22 | |Please read the instructions mentioned in instructions.pdf before submitting assignment.
23 |
24 | |Thanks,
25 | |Recruitment Team
26 | |""".
27 | stripMargin)
28 |
29 | val body = new Body().withText(textBody)
30 | val message = new Message().withSubject(subject).withBody(body)
31 |
32 | val request = new SendEmailRequest()
33 | .withSource(sourceEmail)
34 | .withDestination(destination)
35 | .withMessage(message)
36 |
37 | emailClient.sendEmail(request)
38 | }
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/assignment-sender-service/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### SBT template
3 | # Simple Build Tool
4 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control
5 |
6 | target/
7 | lib_managed/
8 | src_managed/
9 | project/boot/
10 | .history
11 | .cache
12 | ### JetBrains template
13 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
14 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
15 |
16 | # User-specific stuff:
17 | .idea/
18 | .idea/tasks.xml
19 |
20 | # Sensitive or high-churn files:
21 | .idea/dataSources/
22 | .idea/dataSources.ids
23 | .idea/dataSources.xml
24 | .idea/dataSources.local.xml
25 | .idea/sqlDataSources.xml
26 | .idea/dynamic.xml
27 | .idea/uiDesigner.xml
28 |
29 | # Gradle:
30 | .idea/gradle.xml
31 | .idea/libraries
32 |
33 | # Mongo Explorer plugin:
34 | .idea/mongoSettings.xml
35 |
36 | ## File-based project format:
37 | *.iws
38 |
39 | ## Plugin-specific files:
40 |
41 | # IntelliJ
42 | /out/
43 |
44 | # mpeltonen/sbt-idea plugin
45 | .idea_modules/
46 |
47 | # JIRA plugin
48 | atlassian-ide-plugin.xml
49 |
50 | # Crashlytics plugin (for Android Studio and IntelliJ)
51 | com_crashlytics_export_strings.xml
52 | crashlytics.properties
53 | crashlytics-build.properties
54 | fabric.properties
55 | ### Scala template
56 | *.class
57 | *.log
58 |
59 | # sbt specific
60 | .cache
61 | .history
62 | .lib/
63 | dist/*
64 | target/
65 | lib_managed/
66 | src_managed/
67 | project/boot/
68 | project/plugins/project/
69 |
70 | # Scala-IDE specific
71 | .scala_dependencies
72 | .worksheet
73 |
74 | # ENSIME specific
75 | .ensime_cache/
76 | .ensime
77 |
78 | env.yml
79 |
80 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/serverless.yml:
--------------------------------------------------------------------------------
1 | service: assignment-build-executor-service
2 |
3 | provider:
4 | name: aws
5 | runtime: java8
6 | stage: dev
7 | region: us-east-1
8 | environment:
9 | LCRE_CANDIDATE_SUBMISSIONS_S3_BUCKET: "${self:custom.s3BucketPrefix}-candidate-submissions-${self:provider.stage}"
10 | LCRE_CANDIDATE_BUILD_REPORTS_S3_BUCKET: "${self:custom.s3BucketPrefix}-candidate-build-reports-${self:provider.stage}"
11 | CANDIDATE_TABLE: candidate-${opt:stage, self:provider.stage}
12 | iamRoleStatements:
13 | - Effect: "Allow"
14 | Action:
15 | - "s3:*"
16 | Resource: "*"
17 | - Effect: Allow
18 | Action:
19 | - dynamodb:Query
20 | - dynamodb:Scan
21 | - dynamodb:GetItem
22 | - dynamodb:PutItem
23 | - dynamodb:UpdateItem
24 | - dynamodb:DeleteItem
25 | Resource: "*"
26 |
27 | custom:
28 | s3BucketPrefix: lcre
29 |
30 | package:
31 | artifact: build/distributions/assignment-build-executor-service.zip
32 |
33 | functions:
34 | assignment-build-executor:
35 | handler: xebia.lcre.BuildHandler
36 | memorySize: 704
37 | timeout: 300
38 | events:
39 | - s3:
40 | bucket: ${self:provider.environment.LCRE_CANDIDATE_SUBMISSIONS_S3_BUCKET}
41 | event: s3:ObjectCreated:*
42 |
43 | resources:
44 | Resources:
45 | S3BucketForBuildReports:
46 | Type: AWS::S3::Bucket
47 | Properties:
48 | BucketName: ${self:provider.environment.LCRE_CANDIDATE_BUILD_REPORTS_S3_BUCKET}
49 | CorsConfiguration:
50 | CorsRules:
51 | - AllowedMethods:
52 | - GET
53 | - PUT
54 | - POST
55 | - HEAD
56 | AllowedOrigins:
57 | - "*"
58 | AllowedHeaders:
59 | - "*"
60 |
61 |
--------------------------------------------------------------------------------
/candidate-service/data/send-assignment-event.json:
--------------------------------------------------------------------------------
1 | {
2 | "Records": [
3 | {
4 | "eventID": "6f56873432cc11327bb3d34b89fccc56",
5 | "eventName": "INSERT",
6 | "eventVersion": "1.1",
7 | "eventSource": "aws:dynamodb",
8 | "awsRegion": "us-east-1",
9 | "dynamodb": {
10 | "ApproximateCreationDateTime": 1486806180,
11 | "Keys": {
12 | "id": {
13 | "S": "9411ec60-f03e-11e6-ad71-f74b3a0b7acd"
14 | }
15 | },
16 | "NewImage": {
17 | "name": {
18 | "S": "Shekhar Gulati"
19 | },
20 | "evaluated": {
21 | "BOOL": false
22 | },
23 | "id": {
24 | "S": "9411ec60-f03e-11e6-ad71-f74b3a0b7acd"
25 | },
26 | "experience": {
27 | "N": "2"
28 | },
29 | "submittedAt": {
30 | "N": "1486806224422"
31 | },
32 | "email": {
33 | "S": "shekhargulati84@gmail.com"
34 | },
35 | "status": {
36 | "S": "Candidate Submitted"
37 | },
38 | "updatedAt": {
39 | "N": "1486806224422"
40 | }
41 | },
42 | "SequenceNumber": "83000000000019946091137",
43 | "SizeBytes": 207,
44 | "StreamViewType": "NEW_AND_OLD_IMAGES"
45 | },
46 | "eventSourceARN": "arn:aws:dynamodb:us-east-1:167443307349:table/candidate-dev/stream/2017-02-11T09:22:26.753"
47 | }
48 | ]
49 | }
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/pkg/creators/BuildPackageCreator.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre.pkg.creators;
2 |
3 | import com.amazonaws.services.s3.AmazonS3Client;
4 | import com.amazonaws.services.s3.event.S3EventNotification.S3Entity;
5 | import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord;
6 | import com.amazonaws.services.s3.model.GetObjectRequest;
7 | import com.amazonaws.services.s3.model.S3Object;
8 | import org.apache.log4j.Logger;
9 | import xebia.lcre.exceptions.UnableToCreateBuildPackage;
10 | import xebia.lcre.utils.ZipHelpers;
11 |
12 | import java.io.IOException;
13 | import java.net.URLDecoder;
14 | import java.nio.file.Path;
15 |
16 | public class BuildPackageCreator {
17 |
18 | private final AmazonS3Client client;
19 | private final Logger logger = Logger.getLogger(BuildPackageCreator.class);
20 |
21 | public BuildPackageCreator(AmazonS3Client client) {
22 | this.client = client;
23 | }
24 |
25 | public BuildPackage create(S3EventNotificationRecord record) throws UnableToCreateBuildPackage {
26 | try {
27 | S3Entity entity = record.getS3();
28 | String srcKey = URLDecoder.decode(entity.getObject().getKey().replace('+', ' '), "UTF-8");
29 | S3Object s3Object = client.getObject(new GetObjectRequest(entity.getBucket().getName(), srcKey));
30 | String zipName = s3Object.getKey();
31 | Path zipPath = ZipHelpers.downloadZipTo(s3Object.getObjectContent(), zipName, "/tmp");
32 | return new BuildPackage(zipName, zipPath, extractCandidateId(zipPath));
33 | } catch (IOException e) {
34 | logger.error("Unable to create build package", e);
35 | throw new UnableToCreateBuildPackage("Unable to create build package", e);
36 | }
37 | }
38 |
39 | private String extractCandidateId(Path zipPath) {
40 | return zipPath.getFileName().toString().replace("assignment-", "");
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/scala/assignmentsender/AssignmentPreparatorSpec.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import java.net.URL
4 | import java.nio.file.{Files, Paths}
5 |
6 | import assignmentsender.preparator.AssignmentPreparator
7 | import assignmentsender.preparator.AssignmentPreparator.{addGradlePropertiesToAssignmentZip, assignmentDownloader, createGradleProperties}
8 | import org.zeroturnaround.zip.ZipUtil
9 |
10 | import scala.collection.convert.wrapAsScala._
11 | import scala.util.Success
12 |
13 | class AssignmentPreparatorSpec extends BaseTestSpec {
14 |
15 | private val assignmentUrl = Paths.get("src", "test", "resources", "assignment.zip").toUri.toURL.toString
16 |
17 | describe("AssignmentPreparator") {
18 |
19 | it("should download assignment zip to '/tmp' directory") {
20 | val assignmentPath = assignmentDownloader(assignmentUrl, "123")
21 | assignmentPath.exists() should be(true)
22 | assignmentPath should be(Paths.get("/tmp", "assignment-123.zip").toFile)
23 | }
24 |
25 | it("should add gradle.properties to assignment zip") {
26 | assignmentDownloader(assignmentUrl, "123")
27 | val assignmentFile = Paths.get("/tmp", "assignment-123.zip").toFile
28 | addGradlePropertiesToAssignmentZip(assignmentFile, Paths.get("src", "test", "resources", "gradle.properties"))
29 | ZipUtil.containsEntry(assignmentFile, "gradle.properties") should be(true)
30 | }
31 |
32 | it("should write gradle.properties file to '/tmp' directory") {
33 | val gradleProperties = createGradleProperties("123", new URL("https://example.com/submit"))
34 | gradleProperties.toFile.exists() should be(true)
35 | Files.readAllLines(gradleProperties).mkString("<------->") should be(
36 | "assignmentName=assignment-123.zip<------->assignmentSubmissionUrl=https://example.com/submit")
37 | }
38 |
39 | it("should prepare assignment to be sent to candidate") {
40 | val assignmentPreparator = new AssignmentPreparator()
41 | val assignmentLocalPath = assignmentPreparator(Assignment(assignmentUrl, List(), 5), "123", new URL("https://example.com/submit"))
42 | assignmentLocalPath should be(Success(Paths.get("/tmp", "assignment-123.zip")))
43 | }
44 | }
45 |
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/scala/assignmentsender/AssignmentSenderSpec.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import java.net.URL
4 | import java.nio.file.Paths
5 | import java.util
6 |
7 | import assignmentsender.email.EmailSender
8 | import com.amazonaws.http.SdkHttpMetadata
9 | import com.amazonaws.services.s3.AmazonS3
10 | import com.amazonaws.services.s3.model.{PutObjectRequest, PutObjectResult}
11 | import com.amazonaws.services.simpleemail.model.SendEmailResult
12 | import org.mockito.ArgumentMatchers.any
13 | import org.mockito.{ArgumentMatchers, Mockito}
14 | import org.mockito.Mockito.when
15 |
16 | import scala.util.Success
17 | import scala.collection.convert.wrapAsJava._
18 |
19 | class AssignmentSenderSpec extends BaseTestSpec {
20 |
21 |
22 | describe("AssignmentSender") {
23 | it("should send assignment to candidate") {
24 | val candidate = Candidate("123", "Foo Bar", "foo@bar", 5, "java")
25 | val assignmentPicker: AssignmentChooserF = (_) => Assignment("http://test.com/assignment.zip", List("java"), 5)
26 | val preparator: AssignmentPreparatorF = (_, cId, _) => Success(Paths.get("/tmp", s"assignment-$cId.zip"))
27 |
28 | val mockS3Client = mock[AmazonS3]
29 | val mockEmailSender = mock[EmailSender]
30 | val sender = new AssignmentSender(mockS3Client, assignmentPicker, preparator, mockEmailSender)("test_submission_bucket", "test_assignment_bucket")
31 |
32 | val assignmentUrl = new URL("http://test.com/assignment.zip")
33 | when(mockS3Client.putObject(any[PutObjectRequest]())).thenReturn(mock[PutObjectResult])
34 | when(mockS3Client.getUrl("test_assignment_bucket", "assignment-123.zip")).thenReturn(assignmentUrl)
35 |
36 | val sendEmailResult = new SendEmailResult().withMessageId("messageId")
37 | val httpMetadata = mock[SdkHttpMetadata]
38 | when(httpMetadata.getHttpHeaders).thenReturn(Map[String, String]())
39 | when(httpMetadata.getHttpStatusCode).thenReturn(200)
40 | sendEmailResult.setSdkHttpMetadata(httpMetadata)
41 | when(mockEmailSender.sendEmail(candidate, assignmentUrl)).thenReturn(Success(sendEmailResult))
42 |
43 | val result = sender.send(candidate, Success(new URL("http://test.com/assignment.zip")))
44 |
45 | result should be(Success(Result("messageId", 200)))
46 |
47 | }
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/src/main/java/xebia/lcre/BuildHandler.java:
--------------------------------------------------------------------------------
1 | package xebia.lcre;
2 |
3 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
4 | import com.amazonaws.services.lambda.runtime.Context;
5 | import com.amazonaws.services.lambda.runtime.RequestHandler;
6 | import com.amazonaws.services.lambda.runtime.events.S3Event;
7 | import com.amazonaws.services.s3.AmazonS3Client;
8 | import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord;
9 | import org.apache.log4j.Logger;
10 | import xebia.lcre.build.failure.reason.BuildFailureReasonFinder;
11 | import xebia.lcre.build.result.BuildResult;
12 | import xebia.lcre.build.result.handlers.BuildResultHandler;
13 | import xebia.lcre.build.spec.BuildSpecificationBuilder;
14 | import xebia.lcre.pkg.creators.BuildPackage;
15 | import xebia.lcre.pkg.creators.BuildPackageCreator;
16 |
17 | public class BuildHandler implements RequestHandler {
18 |
19 | private static final Logger logger = Logger.getLogger(BuildHandler.class);
20 |
21 | private final AmazonS3Client s3Client = new AmazonS3Client();
22 | private final AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient();
23 |
24 | private final BuildPackageCreator buildPackageCreator = new BuildPackageCreator(s3Client);
25 | private final BuildExecutor buildExecutor = BuildExecutor.newRunner(new BuildSpecificationBuilder());
26 | private final BuildFailureReasonFinder buildFailureReasonFinder = BuildFailureReasonFinder.newFinder();
27 |
28 | private final BuildResultHandler resultHandler = new BuildResultHandler(
29 | s3Client,
30 | dynamoDBClient,
31 | buildFailureReasonFinder
32 | );
33 |
34 | @Override
35 | public String handleRequest(S3Event event, Context context) {
36 | try {
37 | S3EventNotificationRecord record = event.getRecords().get(0);
38 | BuildPackage buildPackage = buildPackageCreator.create(record);
39 | logger.info(String.format("Working on BuildPackage >> %s", buildPackage));
40 | BuildResult buildResult = buildExecutor.execute(buildPackage);
41 | return resultHandler.handle(buildResult);
42 | } catch (Exception e) {
43 | logger.error("Failure occurred .. ", e);
44 | return "FAILED";
45 | }
46 | }
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/preparator/AssignmentPreparator.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender.preparator
2 |
3 | import java.net.URL
4 | import java.nio.file.{Files, Paths}
5 | import java.util.UUID
6 |
7 | import assignmentsender._
8 | import assignmentsender.preparator.AssignmentPreparator.{addGradlePropertiesToAssignmentZip, assignmentDownloader, createGradleProperties}
9 | import org.zeroturnaround.zip.{FileSource, ZipUtil}
10 |
11 | import scala.util.Try
12 |
13 | class AssignmentPreparator extends AssignmentPreparatorF {
14 |
15 | override def apply(assignment: Assignment, candidateId: CandidateId, assignmentSubmissionUrl: URL): Try[AssignmentLocalPath] = {
16 | Try {
17 | val gradlePropertiesPath = createGradleProperties(candidateId, assignmentSubmissionUrl)
18 | val assignmentLocalFile = assignmentDownloader(assignment.assignmentUrl, candidateId)
19 | addGradlePropertiesToAssignmentZip(assignmentLocalFile, gradlePropertiesPath)
20 | assignmentLocalFile.toPath
21 | }
22 | }
23 |
24 | }
25 |
26 | object AssignmentPreparator {
27 | private[assignmentsender] def assignmentDownloader: AssignmentDownloaderF = (assignmentUrl, candidateId) => {
28 | import sys.process._
29 | val assignmentZipName = assignmentUrl.substring(assignmentUrl.lastIndexOf("/")).replace(".zip", "") + "-" + candidateId + ".zip"
30 | val assignment = Paths.get("/tmp", assignmentZipName).toFile
31 | (new URL(assignmentUrl) #> assignment).!!
32 | assignment
33 | }
34 |
35 | private[assignmentsender] def addGradlePropertiesToAssignmentZip: AddGradlePropertiesToZipF = (assignmentLocalFile, gradlePropertiesPath) => {
36 | val gradlePropertiesFile = Paths.get("gradle.properties").toString
37 | ZipUtil.addEntry(assignmentLocalFile, new FileSource(gradlePropertiesFile, gradlePropertiesPath.toFile))
38 | assignmentLocalFile
39 | }
40 |
41 | private[assignmentsender] def createGradleProperties(candidateId: CandidateId, assignmentSubmissionUrl: URL) = {
42 | val tmpDir = Paths.get("/tmp", UUID.randomUUID().toString)
43 | tmpDir.toFile.mkdir()
44 | val gradlePropertiesPath = tmpDir.resolve("gradle.properties")
45 | Files.write(
46 | gradlePropertiesPath,
47 | List(s"assignmentName=assignment-$candidateId.zip", s"assignmentSubmissionUrl=$assignmentSubmissionUrl").mkString("\n").getBytes()
48 | )
49 | gradlePropertiesPath
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/AssignmentSenderHandler.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import assignmentsender.chooser.AssignmentChooser
4 | import assignmentsender.email.EmailSender
5 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent
6 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord
7 | import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
8 | import com.amazonaws.services.s3.AmazonS3ClientBuilder
9 | import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder
10 |
11 | import scala.collection.convert.WrapAsScala._
12 |
13 | class AssignmentSenderHandler
14 | extends RequestHandler[DynamodbEvent, String]
15 | with Logging
16 | with DynamoDBStreamRecordToCandidate {
17 |
18 |
19 | def handleRequest(event: DynamodbEvent, context: Context): String = {
20 | val s3Client = AmazonS3ClientBuilder.defaultClient()
21 | val emailClient = AmazonSimpleEmailServiceClientBuilder.defaultClient()
22 | val assignmentSender = AssignmentSender(s3Client, AssignmentChooser(), new EmailSender(emailClient))
23 | handleRequest(event, assignmentSender)
24 | }
25 |
26 | private[assignmentsender] def handleRequest(event: DynamodbEvent, assignmentSender: AssignmentSender) = {
27 | logger.info("Received event from DynamoDB service")
28 | val insertRecords = event.getRecords.filter(r => r.getEventName == "INSERT")
29 | if (insertRecords.isEmpty) {
30 | logger.info("No assignment needs to be sent as there are no INSERT events")
31 | "NOTHING_TO_PROCESS"
32 | } else {
33 | logger.info(s"Received ${insertRecords.size} INSERT event(s).")
34 | val candidates = insertRecords.map(r => toCandidate(r))
35 | logger.info(s"Will be sending assignment to following candidate(s) ${candidates.map(_.email).mkString(",")}")
36 | assignmentSender.send(candidates.toList)
37 | "OK"
38 | }
39 | }
40 | }
41 |
42 | trait DynamoDBStreamRecordToCandidate {
43 |
44 | def toCandidate(r: DynamodbStreamRecord): Candidate = {
45 | val image = r.getDynamodb.getNewImage
46 | val experience = image.get("experience").getN.toInt
47 | val candidateId = image.get("id").getS
48 | val skills = image.get("skills").getS
49 | val fullname = image.get("fullname").getS
50 | val email = image.get("email").getS
51 | Candidate(candidateId, fullname, email, experience, skills)
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/test/scala/assignmentsender/AssignmentSenderHandlerSpec.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import com.amazonaws.services.dynamodbv2.model.{AttributeValue, StreamRecord}
4 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent
5 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord
6 | import org.mockito.Mockito.{verify, when}
7 |
8 | import scala.collection.convert.wrapAsJava._
9 |
10 | class AssignmentSenderHandlerSpec
11 | extends BaseTestSpec {
12 |
13 |
14 | describe("AssignmentSenderHandler") {
15 | it("should return OK response when INSERT event is received") {
16 | val handler = new AssignmentSenderHandler()
17 | val event = mock[DynamodbEvent]
18 | val record = mock[DynamodbStreamRecord]
19 | when(record.getEventName).thenReturn("INSERT")
20 | val experience = new AttributeValue()
21 | experience.setN("5")
22 | val attributeMap = Map(
23 | "id" -> new AttributeValue("123"),
24 | "experience" -> experience,
25 | "fullname" -> new AttributeValue("Foo Bar"),
26 | "email" -> new AttributeValue("foo@bar.com"),
27 | "skills" -> new AttributeValue("java")
28 | )
29 |
30 | val streamRecord = mock[StreamRecord]
31 | when(record.getDynamodb).thenReturn(streamRecord)
32 | when(streamRecord.getNewImage).thenReturn(attributeMap)
33 | when(event.getRecords).thenReturn(List(record))
34 |
35 | val assignmentSender = mock[AssignmentSender]
36 |
37 | val response: String = handler.handleRequest(event, assignmentSender)
38 |
39 | response should be("OK")
40 | verify(record).getEventName
41 | verify(record).getDynamodb
42 | verify(streamRecord).getNewImage
43 | verify(assignmentSender).send(List(Candidate("123", "Foo Bar", "foo@bar.com", 5, "java")))
44 | }
45 |
46 | it("should return 'NOTHING_TO_PROCESS' when no INSERT events are received") {
47 | val handler = new AssignmentSenderHandler()
48 | val event = mock[DynamodbEvent]
49 | val record = mock[DynamodbStreamRecord]
50 | when(record.getEventName).thenReturn("MODIFY")
51 | when(event.getRecords).thenReturn(List(record))
52 | val assignmentSender = mock[AssignmentSender]
53 | val response: String = handler.handleRequest(event, assignmentSender)
54 | response should be("NOTHING_TO_PROCESS")
55 | verify(record).getEventName
56 | }
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/ui-service/serverless-single-page-app-plugin/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const spawnSync = require('child_process').spawnSync;
4 |
5 | class ServerlessPlugin {
6 | constructor(serverless, options) {
7 | this.serverless = serverless;
8 | this.options = options;
9 | this.commands = {
10 | syncToS3: {
11 | usage: 'Deploys the `app` directory to your bucket',
12 | lifecycleEvents: [
13 | 'sync',
14 | ],
15 | },
16 | domainInfo: {
17 | usage: 'Fetches and prints out the deployed CloudFront domain names',
18 | lifecycleEvents: [
19 | 'domainInfo',
20 | ],
21 | },
22 | };
23 |
24 | this.hooks = {
25 | 'syncToS3:sync': this.syncDirectory.bind(this),
26 | 'domainInfo:domainInfo': this.domainInfo.bind(this),
27 | };
28 | }
29 |
30 | // syncs the `app` directory to the provided bucket
31 | syncDirectory() {
32 | const s3Bucket = this.serverless.variables.service.custom.s3Bucket;
33 | const args = [
34 | 's3',
35 | 'sync',
36 | 'app/',
37 | `s3://${s3Bucket}/`,
38 | ];
39 | const result = spawnSync('aws', args);
40 | const stdout = result.stdout.toString();
41 | const sterr = result.stderr.toString();
42 | if (stdout) {
43 | this.serverless.cli.log(stdout);
44 | }
45 | if (sterr) {
46 | this.serverless.cli.log(sterr);
47 | }
48 | if (!sterr) {
49 | this.serverless.cli.log('Successfully synced to the S3 bucket');
50 | }
51 | }
52 |
53 | // fetches the domain name from the CloudFront outputs and prints it out
54 | domainInfo() {
55 | const provider = this.serverless.getProvider('aws');
56 | const stackName = provider.naming.getStackName(this.options.stage);
57 | return provider
58 | .request(
59 | 'CloudFormation',
60 | 'describeStacks',
61 | { StackName: stackName },
62 | this.options.stage,
63 | this.options.region // eslint-disable-line comma-dangle
64 | )
65 | .then(function log(result) {
66 | const outputs = result.Stacks[0].Outputs;
67 | const output = outputs.find(entry => entry.OutputKey === 'WebAppCloudFrontDistributionOutput');
68 | if (output.OutputValue) {
69 | this.serverless.cli.log(`Web App Domain: ${output.OutputValue}`);
70 | } else {
71 | this.serverless.cli.log('Web App Domain: Not Found');
72 | }
73 | });
74 | }
75 | }
76 |
77 | module.exports = ServerlessPlugin;
78 |
--------------------------------------------------------------------------------
/candidate-service/serverless.yml:
--------------------------------------------------------------------------------
1 | service: candidate-service
2 |
3 | frameworkVersion: ">=1.1.0 <2.0.0"
4 |
5 | provider:
6 | name: aws
7 | runtime: nodejs4.3
8 | environment:
9 | CANDIDATE_TABLE: candidate-${opt:stage, self:provider.stage}
10 | CANDIDATE_EMAIL_TABLE: "candidate-email-${opt:stage, self:provider.stage}"
11 | iamRoleStatements:
12 | - Effect: Allow
13 | Action:
14 | - dynamodb:Query
15 | - dynamodb:Scan
16 | - dynamodb:GetItem
17 | - dynamodb:PutItem
18 | Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/candidate-*"
19 |
20 | functions:
21 | candidateSubmission:
22 | handler: api/candidate.submit
23 | memorySize: 128
24 | description: Submit candidate information and starts interview process.
25 | events:
26 | - http:
27 | path: candidates
28 | method: post
29 | cors: true
30 | listCandidates:
31 | handler: api/candidate.list
32 | memorySize: 128
33 | description: List all candidates
34 | events:
35 | - http:
36 | path: candidates
37 | method: get
38 | cors: true
39 | candidateDetails:
40 | handler: api/candidate.get
41 | events:
42 | - http:
43 | path: candidates/{id}
44 | method: get
45 | cors: true
46 |
47 | resources:
48 | Resources:
49 | CandidatesDynamoDbTable:
50 | Type: 'AWS::DynamoDB::Table'
51 | DeletionPolicy: Retain
52 | Properties:
53 | AttributeDefinitions:
54 | -
55 | AttributeName: "id"
56 | AttributeType: "S"
57 | KeySchema:
58 | -
59 | AttributeName: "id"
60 | KeyType: "HASH"
61 | ProvisionedThroughput:
62 | ReadCapacityUnits: 5
63 | WriteCapacityUnits: 5
64 | StreamSpecification:
65 | StreamViewType: "NEW_IMAGE"
66 | TableName: ${self:provider.environment.CANDIDATE_TABLE}
67 | CandidateEmailDynamoDbTable:
68 | Type: 'AWS::DynamoDB::Table'
69 | DeletionPolicy: Retain
70 | Properties:
71 | AttributeDefinitions:
72 | -
73 | AttributeName: "email"
74 | AttributeType: "S"
75 | KeySchema:
76 | -
77 | AttributeName: "email"
78 | KeyType: "HASH"
79 | ProvisionedThroughput:
80 | ReadCapacityUnits: 5
81 | WriteCapacityUnits: 5
82 | TableName: ${self:provider.environment.CANDIDATE_EMAIL_TABLE}
--------------------------------------------------------------------------------
/assignment-build-executor-service/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/assignment-sender-service/src/main/scala/assignmentsender/AssignmentSender.scala:
--------------------------------------------------------------------------------
1 | package assignmentsender
2 |
3 | import java.net.URL
4 |
5 | import assignmentsender.email.EmailSender
6 | import assignmentsender.preparator.AssignmentPreparator
7 | import assignmentsender.s3.S3Helper
8 | import com.amazonaws.services.s3.AmazonS3
9 |
10 | import scala.annotation.tailrec
11 | import scala.util.Try
12 |
13 | class AssignmentSender(val s3Client: AmazonS3,
14 | assignmentPicker: AssignmentChooserF,
15 | assignmentPreparator: AssignmentPreparatorF,
16 | emailSender: EmailSender)
17 | (implicit submissionS3Bucket: String = sys.env("LCRE_CANDIDATE_SUBMISSIONS_S3_BUCKET"),
18 | assignmentsS3Bucket: String = sys.env("LCRE_ASSIGNMENTS_BUCKET"))
19 | extends Logging
20 | with S3Helper {
21 |
22 |
23 | def send(candidates: List[Candidate]): List[Try[Result]] = {
24 |
25 | @tailrec
26 | def sendR(candidates: List[Candidate], results: List[Try[Result]] = List()): List[Try[Result]] = {
27 | candidates match {
28 | case candidate :: remaining =>
29 | sendR(remaining, send(candidate, createPreSignedUrl(submissionS3Bucket, s"assignment-${candidate.id}.zip")) :: results)
30 | case Nil =>
31 | results
32 | }
33 | }
34 |
35 | sendR(candidates)
36 | }
37 |
38 | private[assignmentsender] def send(candidate: Candidate,
39 | submissionUrl: Try[URL]): Try[Result] = {
40 |
41 | submissionUrl
42 | .flatMap(sUrl => assignmentPicker.andThen(assignmentPreparator.curried)(candidate)(candidate.id)(sUrl))
43 | .flatMap(assignmentLocalPath => putFileInS3Bucket(assignmentsS3Bucket, assignmentLocalPath.toFile))
44 | .flatMap(candidateAssignmentUrl => {
45 | logger.info(s"Assignment uploaded to S3 $candidateAssignmentUrl. Sending email to ${candidate.email}")
46 | emailSender.sendEmail(candidate, candidateAssignmentUrl)
47 | })
48 | .map(sendEmailResult => {
49 | logger.info(s"Received email response $sendEmailResult")
50 | Result(sendEmailResult.getMessageId, sendEmailResult.getSdkHttpMetadata.getHttpStatusCode)
51 | })
52 | }
53 |
54 |
55 | }
56 |
57 | object AssignmentSender {
58 | def apply(s3Client: AmazonS3, assignmentDecider: AssignmentChooserF, emailSender: EmailSender): AssignmentSender =
59 | new AssignmentSender(s3Client, assignmentDecider, new AssignmentPreparator(), emailSender)
60 | }
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # lambda-coding-round-evaluator
2 | The goal of this project is to implement a code evaluator that organizations can use to automate coding round interviews. This is inspired by Coursera's Scala Progfun code evaluator. The project is built following Serverless architecture. The current implementation is based on AWS Lambda and Serverless framework.
3 |
4 | Lambda functions are written in Java, Node.js, and Scala programming languages.
5 |
6 | The project uses following AWS services:
7 |
8 | 1. AWS Lambda
9 | 2. AWS DynamoDB
10 | 3. AWS Cloudformation
11 | 4. AWS SES
12 | 5. AWS S3
13 |
14 | ## What is it?
15 |
16 | `lambda-coding-round-evaluator` is used to automate coding round submission and evaluation. It helps you get rid of emails. Yay!
17 |
18 | In my current organization, one of the interview rounds is a coding round. Candidate is emailed an assignment that he/she has to submit in a week time. The assignment is then evaluated by an existing employee who then makes the decision on whether candidate passed or failed the round. I wanted to automate this process so that we can filter out bad candidates without any human intervention. **A task that can be automated should be automated**. This is how the flow will work:
19 |
20 | 1. Recruitment team submit candidate details to the system.
21 | 2. System sends an email with assignment zip to the candidate based on candidate skills and experience. The zip contains the problem as well as a Gradle or Maven project.
22 | 3. Candidate writes the code and submits the assignment using Maven or Gradle task like `gradle submitAssignment`. The task zips the source code of the candidate and submits it to the system.
23 | 4. On receiving assignment, systems builds the project and run all test cases.
24 | 1. If the build fails, then candidate status is updated to failed in the system and recruitment team is notified.
25 | 2. If build succeeds, then we find the test code coverage and if it is less than a threshold then we mark candidate status to failed and recruitment team is notified.
26 | 5. If build succeeds and code coverage is above a threshold, then we run static analysis on the code to calculate the code quality score. If code quality score is below a threshold then candidate is marked failed and notification is sent to the recruitment team. Else, candidate passes the round and a human interviewer will now evaluate candidate assignment.
27 |
28 | 
29 |
30 |
31 |
32 | ## Services
33 |
34 | This project is composed four services:
35 |
36 | 1. `candidate-service`: This service exposes REST API using API Gateway and Lambda that is used by the user interface to submit candidate details. The candidate details are stored in DynamoDB
37 | 2. `assignment-sender-service`: This service has one Lambda function that listens to DynamoDB stream and based on candidate experience and skills sends assignment to candidate via email.
38 | 3. `assignment-build-executor-service`: This service is invoked when candidate submits code using Gradle task. This builds the project and decides whether candidate passed or failed the test.
39 | 4. `ui-service`: This exposes UI using Cloudfront and S3.
40 |
41 | ## License
42 |
43 | Apache.
44 |
--------------------------------------------------------------------------------
/ui-service/serverless.yml:
--------------------------------------------------------------------------------
1 | service: ui-service
2 |
3 | frameworkVersion: ">=1.2.0 <2.0.0"
4 |
5 | plugins:
6 | - serverless-single-page-app-plugin
7 |
8 | custom:
9 | s3Bucket: lcre-website
10 |
11 | provider:
12 | name: aws
13 | runtime: nodejs4.3
14 |
15 | resources:
16 | Resources:
17 | ## Specifying the S3 Bucket
18 | WebAppS3Bucket:
19 | Type: AWS::S3::Bucket
20 | Properties:
21 | BucketName: ${self:custom.s3Bucket}
22 | AccessControl: PublicRead
23 | WebsiteConfiguration:
24 | IndexDocument: index.html
25 | ErrorDocument: index.html
26 | ## Specifying the policies to make sure all files inside the Bucket are avaialble to CloudFront
27 | WebAppS3BucketPolicy:
28 | Type: AWS::S3::BucketPolicy
29 | Properties:
30 | Bucket:
31 | Ref: WebAppS3Bucket
32 | PolicyDocument:
33 | Statement:
34 | - Sid: PublicReadGetObject
35 | Effect: Allow
36 | Principal: "*"
37 | Action:
38 | - s3:GetObject
39 | Resource: arn:aws:s3:::${self:custom.s3Bucket}/*
40 | ## Specifying the CloudFront Distribution to server your Web Application
41 | WebAppCloudFrontDistribution:
42 | Type: AWS::CloudFront::Distribution
43 | Properties:
44 | DistributionConfig:
45 | Origins:
46 | - DomainName: ${self:custom.s3Bucket}.s3.amazonaws.com
47 | ## An identifier for the origin which must be unique within the distribution
48 | Id: WebApp
49 | CustomOriginConfig:
50 | HTTPPort: 80
51 | HTTPSPort: 443
52 | OriginProtocolPolicy: https-only
53 | ## In case you want to restrict the bucket access use S3OriginConfig and remove CustomOriginConfig
54 | # S3OriginConfig:
55 | # OriginAccessIdentity: origin-access-identity/cloudfront/E127EXAMPLE51Z
56 | Enabled: 'true'
57 | ## Uncomment the following section in case you are using a custom domain
58 | # Aliases:
59 | # - mysite.example.com
60 | DefaultRootObject: index.html
61 | ## Since the Single Page App is taking care of the routing we need to make sure ever path is served with index.html
62 | ## The only exception are files that actually exist e.h. app.js, reset.css
63 | CustomErrorResponses:
64 | - ErrorCode: 404
65 | ResponseCode: 200
66 | ResponsePagePath: /index.html
67 | DefaultCacheBehavior:
68 | AllowedMethods:
69 | - DELETE
70 | - GET
71 | - HEAD
72 | - OPTIONS
73 | - PATCH
74 | - POST
75 | - PUT
76 | ## The origin id defined above
77 | TargetOriginId: WebApp
78 | ## Defining if and how the QueryString and Cookies are forwarded to the origin which in this case is S3
79 | ForwardedValues:
80 | QueryString: 'false'
81 | Cookies:
82 | Forward: none
83 | ## The protocol that users can use to access the files in the origin. To allow HTTP use `allow-all`
84 | ViewerProtocolPolicy: redirect-to-https
85 | ## The certificate to use when viewers use HTTPS to request objects.
86 | ViewerCertificate:
87 | CloudFrontDefaultCertificate: 'true'
88 | ## Uncomment the following section in case you want to enable logging for CloudFront requests
89 | # Logging:
90 | # IncludeCookies: 'false'
91 | # Bucket: mylogs.s3.amazonaws.com
92 | # Prefix: myprefix
93 |
94 | ## In order to print out the hosted domain via `serverless info` we need to define the DomainName output for CloudFormation
95 | Outputs:
96 | WebAppCloudFrontDistributionOutput:
97 | Value:
98 | 'Fn::GetAtt': [ WebAppCloudFrontDistribution, DomainName ]
99 |
--------------------------------------------------------------------------------
/candidate-service/api/candidate.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const uuid = require('uuid');
4 | const AWS = require('aws-sdk');
5 | const R = require('ramda');
6 |
7 | AWS.config.setPromisesDependency(require('bluebird'));
8 |
9 | const dynamoDb = new AWS.DynamoDB.DocumentClient();
10 |
11 | module.exports.submit = (event, context, callback) => {
12 | console.log("Receieved request submit candidate details. Event is", event);
13 | const requestBody = JSON.parse(event.body);
14 | const fullname = requestBody.fullname;
15 | const email = requestBody.email;
16 | const experience = requestBody.experience;
17 | const skills = requestBody.skills;
18 | const recruiterEmail = requestBody.recruiterEmail;
19 |
20 | if (typeof fullname !== 'string' || typeof email !== 'string' || typeof experience !== 'number' || typeof skills !== 'string' || typeof recruiterEmail !== 'string') {
21 | console.error('Validation Failed');
22 | callback(new Error('Couldn\'t submit candidate because of validation errors.'));
23 | return;
24 | }
25 |
26 | const candidate = candidateInfo(fullname, email, experience, skills, recruiterEmail);
27 | const candidateSubmissionFx = R.composeP(submitCandidateEmailP, submitCandidateP, checkCandidateExistsP);
28 |
29 | candidateSubmissionFx(candidate)
30 | .then(res => {
31 | console.log(`Successfully submitted ${fullname}(${email}) candidate to system`);
32 | callback(null, successResponseBuilder(
33 | JSON.stringify({
34 | message: `Sucessfully submitted candidate with email ${email}`,
35 | candidateId: res.id
36 | }))
37 | );
38 | })
39 | .catch(err => {
40 | console.error('Failed to submit candidate to system', err);
41 | callback(null, failureResponseBuilder(
42 | 409,
43 | JSON.stringify({
44 | message: `Unable to submit candidate with email ${email}`
45 | })
46 | ))
47 | });
48 | };
49 |
50 |
51 | module.exports.list = (event, context, callback) => {
52 | console.log("Receieved request to list all candidates. Event is", event);
53 | var params = {
54 | TableName: process.env.CANDIDATE_TABLE,
55 | ProjectionExpression: "id, fullname, email"
56 | };
57 | const onScan = (err, data) => {
58 | if (err) {
59 | console.log('Scan failed to load data. Error JSON:', JSON.stringify(err, null, 2));
60 | callback(err);
61 | } else {
62 | console.log("Scan succeeded.");
63 | return callback(null, successResponseBuilder(JSON.stringify({
64 | candidates: data.Items
65 | })
66 | ));
67 | }
68 | };
69 | dynamoDb.scan(params, onScan);
70 | };
71 |
72 | module.exports.get = (event, context, callback) => {
73 | const params = {
74 | TableName: process.env.CANDIDATE_TABLE,
75 | Key: {
76 | id: event.pathParameters.id,
77 | },
78 | };
79 | dynamoDb.get(params)
80 | .promise()
81 | .then(result => {
82 | callback(null, successResponseBuilder(JSON.stringify(result.Item)));
83 | })
84 | .catch(error => {
85 | console.error(error);
86 | callback(new Error('Couldn\'t fetch candidate.'));
87 | return;
88 | });
89 | };
90 |
91 | const checkCandidateExistsP = (candidate) => {
92 | console.log('Checking if candidate already exists...');
93 | const query = {
94 | TableName: process.env.CANDIDATE_EMAIL_TABLE,
95 | Key: {
96 | "email": candidate.email
97 | }
98 | };
99 | return dynamoDb.get(query)
100 | .promise()
101 | .then(res => {
102 | if (R.not(R.isEmpty(res))) {
103 | return Promise.reject(new Error('Candidate already exists with email ' + email));
104 | }
105 | return candidate;
106 | });
107 | }
108 |
109 | const submitCandidateP = candidate => {
110 | console.log('submitCandidateP() Submitting candidate to system');
111 | const candidateItem = {
112 | TableName: process.env.CANDIDATE_TABLE,
113 | Item: candidate,
114 | };
115 | return dynamoDb.put(candidateItem)
116 | .promise()
117 | .then(res => candidate);
118 | };
119 |
120 |
121 | const successResponseBuilder = (body) => {
122 | return {
123 | statusCode: 200,
124 | headers: {
125 | 'Content-Type': 'application/json',
126 | 'Access-Control-Allow-Origin': '*'
127 | },
128 | body: body
129 | };
130 | };
131 |
132 | const failureResponseBuilder = (statusCode, body) => {
133 | return {
134 | statusCode: statusCode,
135 | headers: {
136 | 'Content-Type': 'application/json',
137 | 'Access-Control-Allow-Origin': '*'
138 | },
139 | body: body
140 | };
141 | };
142 |
143 |
144 | const submitCandidateEmailP = candidate => {
145 | console.log('Submitting candidate email');
146 | const candidateEmailInfo = {
147 | TableName: process.env.CANDIDATE_EMAIL_TABLE,
148 | Item: {
149 | candidate_id: candidate.id,
150 | email: candidate.email
151 | },
152 | };
153 | return dynamoDb.put(candidateEmailInfo)
154 | .promise();
155 | }
156 |
157 | const candidateInfo = (fullname, email, experience, skills, recruiterEmail) => {
158 | const timestamp = new Date().getTime();
159 | return {
160 | id: uuid.v1(),
161 | fullname: fullname,
162 | email: email,
163 | experience: experience,
164 | skills: skills,
165 | recruiterEmail: recruiterEmail,
166 | evaluated: false,
167 | submittedAt: timestamp,
168 | updatedAt: timestamp,
169 | };
170 | };
171 |
172 |
--------------------------------------------------------------------------------
/assignment-build-executor-service/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn ( ) {
37 | echo "$*"
38 | }
39 |
40 | die ( ) {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save ( ) {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 Shekhar Gulati
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/ui-service/app/scripts/app-bundle.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["app.js","candidate-details.js","candidate-form.js","candidate-list.js","environment.js","main.js","messages.js","no-selection.js","utility.js","web-api.js","resources/index.js","resources/elements/loading-indicator.js"],"names":["App","inject","api","configureRouter","config","router","title","map","route","moduleId","name","CandidateDetail","ea","activate","params","routeConfig","getCandidateDetails","id","then","candidate","navModel","setTitle","originalCandidate","JSON","parse","stringify","publish","CandidateForm","fullname","email","experience","recruiterEmail","skills","appRouter","submit","candidateData","Number","console","log","submitCandidate","res","navigate","catch","err","isRequesting","CandidateList","candidates","subscribe","select","msg","found","find","x","Object","assign","created","getCandidateList","selectedId","debug","testing","configure","Promise","warnings","wForgottenReturn","aurelia","use","standardConfiguration","feature","developmentLogging","plugin","start","setRoot","CandidateUpdated","CandidateViewed","CandidateSubmitted","NoSelection","message","areEqual","obj1","obj2","keys","every","key","hasOwnProperty","axiosInstance","create","baseURL","WebAPI","get","data","response","candidateId","post","globalResources","nprogress","LoadingIndicator","defaultValue","on","loadingChanged","newValue","done"],"mappings":"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","file":"app-bundle.js","sourcesContent":["import {WebAPI} from './web-api';\n\nexport class App {\n \n static inject() { return [WebAPI]; }\n\n constructor(api) {\n this.api = api;\n }\n\n configureRouter(config, router){\n config.title = 'Candidate Repository';\n \n config.map([\n { route: '', moduleId: 'no-selection', title: 'home'},\n { route: 'candidates/new', moduleId: 'candidate-form', name:'candidateSubmission' },\n { route: 'candidates/:id', moduleId: 'candidate-details', name:'candidates' }\n ]);\n\n this.router = router;\n }\n}","import {EventAggregator} from 'aurelia-event-aggregator';\nimport {WebAPI} from './web-api';\nimport {CandidateUpdated,CandidateViewed} from './messages';\nimport {areEqual} from './utility';\n\nexport class CandidateDetail {\n static inject() { return [WebAPI, EventAggregator]; }\n\n constructor(api, ea){\n this.api = api;\n this.ea = ea;\n }\n\n activate(params, routeConfig) {\n this.routeConfig = routeConfig;\n\n return this.api.getCandidateDetails(params.id).then(candidate => {\n this.candidate = candidate;\n this.routeConfig.navModel.setTitle(candidate.name);\n this.originalCandidate = JSON.parse(JSON.stringify(candidate));\n this.ea.publish(new CandidateViewed(this.candidate));\n });\n }\n \n}","import { EventAggregator } from 'aurelia-event-aggregator';\nimport { WebAPI } from './web-api';\nimport { CandidateSubmitted } from './messages';\nimport { areEqual } from './utility';\nimport { Router } from 'aurelia-router';\n\nexport class CandidateForm {\n static inject() { return [WebAPI, EventAggregator, Router]; }\n\n constructor(api, ea, router) {\n this.api = api;\n this.ea = ea;\n this.appRouter = router;\n }\n\n candidate = {\n fullname: null,\n email: null,\n experience: null,\n recruiterEmail: null,\n skills: null\n };\n\n\n get canSave() {\n return this.candidate.fullname\n && this.candidate.email\n && this.candidate.experience\n && this.candidate.recruiterEmail\n && this.candidate.skills\n && !this.api.isRequesting;\n }\n\n submit() {\n const candidateData = {\n fullname: this.candidate.fullname,\n email: this.candidate.email,\n experience: Number(this.candidate.experience),\n recruiterEmail: this.candidate.recruiterEmail,\n skills : this.candidate.skills\n }\n console.log('candidate', candidateData);\n this.api.submitCandidate(candidateData)\n .then(res => {\n console.log('Receieved response from API', JSON.stringify(res));\n this.appRouter.navigate('');\n }).catch(err => {\n console.log('errror', err);\n })\n ;\n }\n}","import {EventAggregator} from 'aurelia-event-aggregator';\nimport {WebAPI} from './web-api';\nimport {CandidateUpdated, CandidateViewed} from './messages';\n\nexport class CandidateList {\n static inject = [WebAPI, EventAggregator];\n\n constructor(api, ea){\n console.log('inside CandidateList');\n this.api = api;\n this.candidates = [];\n\n ea.subscribe(CandidateViewed, msg => this.select(msg.candidate));\n ea.subscribe(CandidateUpdated, msg => {\n let id = msg.candidate.id;\n let found = this.candidates.find(x => x.id === id);\n Object.assign(found, msg.candidate);\n });\n }\n\n created(){\n console.log('fetching CandidateList');\n this.api.getCandidateList().then(candidates => {\n this.candidates = candidates\n });\n }\n\n select(candidate){\n this.selectedId = candidate.id;\n return true;\n }\n}","export default {\n debug: true,\n testing: true\n};\n","import environment from './environment';\n\n//Configure Bluebird Promises.\nPromise.config({\n warnings: {\n wForgottenReturn: false\n }\n});\n\nexport function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .feature('resources');\n\n if (environment.debug) {\n aurelia.use.developmentLogging();\n }\n\n if (environment.testing) {\n aurelia.use.plugin('aurelia-testing');\n }\n\n aurelia.start().then(() => aurelia.setRoot());\n}\n","export class CandidateUpdated {\n constructor(candidate){\n this.candidate = candidate;\n }\n}\n\nexport class CandidateViewed {\n constructor(candidate){\n this.candidate = candidate;\n }\n}\n\nexport class CandidateSubmitted {\n constructor(candidate){\n this.candidate = candidate;\n }\n}","export class NoSelection {\n constructor() {\n this.message = \"Please Select a Contact.\";\n }\n}","export function areEqual(obj1, obj2) {\n\treturn Object.keys(obj1).every((key) => obj2.hasOwnProperty(key) && (obj1[key] === obj2[key]));\n};","\nimport axios from 'axios';\n\n\nconst axiosInstance = axios.create({\n baseURL: 'https://ofoxq5c8f7.execute-api.us-east-1.amazonaws.com/dev/candidates'\n});\n\n\nexport class WebAPI {\n isRequesting = false;\n\n getCandidateList() {\n this.isRequesting = true;\n return axiosInstance.get('').then(response => {\n this.isRequesting = false;\n const data = response.data;\n return data.candidates;\n }).catch(err => {\n console.log(\"Received failure from API\", err);\n this.isRequesting = false;\n throw err;\n });\n }\n\n getCandidateDetails(candidateId) {\n this.isRequesting = true;\n return axiosInstance.get(`/${candidateId}`).then(response => {\n this.isRequesting = false;\n return response.data;\n }).catch(err => {\n console.log(\"Received failure from API\", err);\n this.isRequesting = false;\n throw err;\n });\n }\n\n submitCandidate(candidate) {\n this.isRequesting = true;\n return axiosInstance.post('', candidate)\n .then(res => {\n this.isRequesting = false;\n return res;\n }).catch(err => {\n console.log(\"Received failure from API\", err);\n this.isRequesting = false;\n throw err;\n });;\n }\n}\n","export function configure(config) {\n config.globalResources(['./elements/loading-indicator']);\n}","import * as nprogress from 'nprogress';\nimport {bindable, noView, decorators} from 'aurelia-framework';\n\nexport let LoadingIndicator = decorators(\n noView(['nprogress/nprogress.css']),\n bindable({name: 'loading', defaultValue: false})\n).on(class {\n loadingChanged(newValue){\n if (newValue) {\n nprogress.start();\n } else {\n nprogress.done();\n }\n }\n});"],"sourceRoot":"../src"}
--------------------------------------------------------------------------------
/ui-service/app/scripts/app-bundle.js:
--------------------------------------------------------------------------------
1 | define('app',['exports', './web-api'], function (exports, _webApi) {
2 | 'use strict';
3 |
4 | Object.defineProperty(exports, "__esModule", {
5 | value: true
6 | });
7 | exports.App = undefined;
8 |
9 | function _classCallCheck(instance, Constructor) {
10 | if (!(instance instanceof Constructor)) {
11 | throw new TypeError("Cannot call a class as a function");
12 | }
13 | }
14 |
15 | var App = exports.App = function () {
16 | App.inject = function inject() {
17 | return [_webApi.WebAPI];
18 | };
19 |
20 | function App(api) {
21 | _classCallCheck(this, App);
22 |
23 | this.api = api;
24 | }
25 |
26 | App.prototype.configureRouter = function configureRouter(config, router) {
27 | config.title = 'Candidate Repository';
28 |
29 | config.map([{ route: '', moduleId: 'no-selection', title: 'home' }, { route: 'candidates/new', moduleId: 'candidate-form', name: 'candidateSubmission' }, { route: 'candidates/:id', moduleId: 'candidate-details', name: 'candidates' }]);
30 |
31 | this.router = router;
32 | };
33 |
34 | return App;
35 | }();
36 | });
37 | define('candidate-details',['exports', 'aurelia-event-aggregator', './web-api', './messages', './utility'], function (exports, _aureliaEventAggregator, _webApi, _messages, _utility) {
38 | 'use strict';
39 |
40 | Object.defineProperty(exports, "__esModule", {
41 | value: true
42 | });
43 | exports.CandidateDetail = undefined;
44 |
45 | function _classCallCheck(instance, Constructor) {
46 | if (!(instance instanceof Constructor)) {
47 | throw new TypeError("Cannot call a class as a function");
48 | }
49 | }
50 |
51 | var CandidateDetail = exports.CandidateDetail = function () {
52 | CandidateDetail.inject = function inject() {
53 | return [_webApi.WebAPI, _aureliaEventAggregator.EventAggregator];
54 | };
55 |
56 | function CandidateDetail(api, ea) {
57 | _classCallCheck(this, CandidateDetail);
58 |
59 | this.api = api;
60 | this.ea = ea;
61 | }
62 |
63 | CandidateDetail.prototype.activate = function activate(params, routeConfig) {
64 | var _this = this;
65 |
66 | this.routeConfig = routeConfig;
67 |
68 | return this.api.getCandidateDetails(params.id).then(function (candidate) {
69 | _this.candidate = candidate;
70 | _this.routeConfig.navModel.setTitle(candidate.name);
71 | _this.originalCandidate = JSON.parse(JSON.stringify(candidate));
72 | _this.ea.publish(new _messages.CandidateViewed(_this.candidate));
73 | });
74 | };
75 |
76 | return CandidateDetail;
77 | }();
78 | });
79 | define('candidate-form',['exports', 'aurelia-event-aggregator', './web-api', './messages', './utility', 'aurelia-router'], function (exports, _aureliaEventAggregator, _webApi, _messages, _utility, _aureliaRouter) {
80 | 'use strict';
81 |
82 | Object.defineProperty(exports, "__esModule", {
83 | value: true
84 | });
85 | exports.CandidateForm = undefined;
86 |
87 | function _classCallCheck(instance, Constructor) {
88 | if (!(instance instanceof Constructor)) {
89 | throw new TypeError("Cannot call a class as a function");
90 | }
91 | }
92 |
93 | var _createClass = function () {
94 | function defineProperties(target, props) {
95 | for (var i = 0; i < props.length; i++) {
96 | var descriptor = props[i];
97 | descriptor.enumerable = descriptor.enumerable || false;
98 | descriptor.configurable = true;
99 | if ("value" in descriptor) descriptor.writable = true;
100 | Object.defineProperty(target, descriptor.key, descriptor);
101 | }
102 | }
103 |
104 | return function (Constructor, protoProps, staticProps) {
105 | if (protoProps) defineProperties(Constructor.prototype, protoProps);
106 | if (staticProps) defineProperties(Constructor, staticProps);
107 | return Constructor;
108 | };
109 | }();
110 |
111 | var CandidateForm = exports.CandidateForm = function () {
112 | CandidateForm.inject = function inject() {
113 | return [_webApi.WebAPI, _aureliaEventAggregator.EventAggregator, _aureliaRouter.Router];
114 | };
115 |
116 | function CandidateForm(api, ea, router) {
117 | _classCallCheck(this, CandidateForm);
118 |
119 | this.candidate = {
120 | fullname: null,
121 | email: null,
122 | experience: null,
123 | recruiterEmail: null,
124 | skills: null
125 | };
126 |
127 | this.api = api;
128 | this.ea = ea;
129 | this.appRouter = router;
130 | }
131 |
132 | CandidateForm.prototype.submit = function submit() {
133 | var _this = this;
134 |
135 | var candidateData = {
136 | fullname: this.candidate.fullname,
137 | email: this.candidate.email,
138 | experience: Number(this.candidate.experience),
139 | recruiterEmail: this.candidate.recruiterEmail,
140 | skills: this.candidate.skills
141 | };
142 | console.log('candidate', candidateData);
143 | this.api.submitCandidate(candidateData).then(function (res) {
144 | console.log('Receieved response from API', JSON.stringify(res));
145 | _this.appRouter.navigate('');
146 | }).catch(function (err) {
147 | console.log('errror', err);
148 | });
149 | };
150 |
151 | _createClass(CandidateForm, [{
152 | key: 'canSave',
153 | get: function get() {
154 | return this.candidate.fullname && this.candidate.email && this.candidate.experience && this.candidate.recruiterEmail && this.candidate.skills && !this.api.isRequesting;
155 | }
156 | }]);
157 |
158 | return CandidateForm;
159 | }();
160 | });
161 | define('candidate-list',['exports', 'aurelia-event-aggregator', './web-api', './messages'], function (exports, _aureliaEventAggregator, _webApi, _messages) {
162 | 'use strict';
163 |
164 | Object.defineProperty(exports, "__esModule", {
165 | value: true
166 | });
167 | exports.CandidateList = undefined;
168 |
169 | function _classCallCheck(instance, Constructor) {
170 | if (!(instance instanceof Constructor)) {
171 | throw new TypeError("Cannot call a class as a function");
172 | }
173 | }
174 |
175 | var _class, _temp;
176 |
177 | var CandidateList = exports.CandidateList = (_temp = _class = function () {
178 | function CandidateList(api, ea) {
179 | var _this = this;
180 |
181 | _classCallCheck(this, CandidateList);
182 |
183 | console.log('inside CandidateList');
184 | this.api = api;
185 | this.candidates = [];
186 |
187 | ea.subscribe(_messages.CandidateViewed, function (msg) {
188 | return _this.select(msg.candidate);
189 | });
190 | ea.subscribe(_messages.CandidateUpdated, function (msg) {
191 | var id = msg.candidate.id;
192 | var found = _this.candidates.find(function (x) {
193 | return x.id === id;
194 | });
195 | Object.assign(found, msg.candidate);
196 | });
197 | }
198 |
199 | CandidateList.prototype.created = function created() {
200 | var _this2 = this;
201 |
202 | console.log('fetching CandidateList');
203 | this.api.getCandidateList().then(function (candidates) {
204 | _this2.candidates = candidates;
205 | });
206 | };
207 |
208 | CandidateList.prototype.select = function select(candidate) {
209 | this.selectedId = candidate.id;
210 | return true;
211 | };
212 |
213 | return CandidateList;
214 | }(), _class.inject = [_webApi.WebAPI, _aureliaEventAggregator.EventAggregator], _temp);
215 | });
216 | define('environment',["exports"], function (exports) {
217 | "use strict";
218 |
219 | Object.defineProperty(exports, "__esModule", {
220 | value: true
221 | });
222 | exports.default = {
223 | debug: true,
224 | testing: true
225 | };
226 | });
227 | define('main',['exports', './environment'], function (exports, _environment) {
228 | 'use strict';
229 |
230 | Object.defineProperty(exports, "__esModule", {
231 | value: true
232 | });
233 | exports.configure = configure;
234 |
235 | var _environment2 = _interopRequireDefault(_environment);
236 |
237 | function _interopRequireDefault(obj) {
238 | return obj && obj.__esModule ? obj : {
239 | default: obj
240 | };
241 | }
242 |
243 | Promise.config({
244 | warnings: {
245 | wForgottenReturn: false
246 | }
247 | });
248 |
249 | function configure(aurelia) {
250 | aurelia.use.standardConfiguration().feature('resources');
251 |
252 | if (_environment2.default.debug) {
253 | aurelia.use.developmentLogging();
254 | }
255 |
256 | if (_environment2.default.testing) {
257 | aurelia.use.plugin('aurelia-testing');
258 | }
259 |
260 | aurelia.start().then(function () {
261 | return aurelia.setRoot();
262 | });
263 | }
264 | });
265 | define('messages',["exports"], function (exports) {
266 | "use strict";
267 |
268 | Object.defineProperty(exports, "__esModule", {
269 | value: true
270 | });
271 |
272 | function _classCallCheck(instance, Constructor) {
273 | if (!(instance instanceof Constructor)) {
274 | throw new TypeError("Cannot call a class as a function");
275 | }
276 | }
277 |
278 | var CandidateUpdated = exports.CandidateUpdated = function CandidateUpdated(candidate) {
279 | _classCallCheck(this, CandidateUpdated);
280 |
281 | this.candidate = candidate;
282 | };
283 |
284 | var CandidateViewed = exports.CandidateViewed = function CandidateViewed(candidate) {
285 | _classCallCheck(this, CandidateViewed);
286 |
287 | this.candidate = candidate;
288 | };
289 |
290 | var CandidateSubmitted = exports.CandidateSubmitted = function CandidateSubmitted(candidate) {
291 | _classCallCheck(this, CandidateSubmitted);
292 |
293 | this.candidate = candidate;
294 | };
295 | });
296 | define('no-selection',["exports"], function (exports) {
297 | "use strict";
298 |
299 | Object.defineProperty(exports, "__esModule", {
300 | value: true
301 | });
302 |
303 | function _classCallCheck(instance, Constructor) {
304 | if (!(instance instanceof Constructor)) {
305 | throw new TypeError("Cannot call a class as a function");
306 | }
307 | }
308 |
309 | var NoSelection = exports.NoSelection = function NoSelection() {
310 | _classCallCheck(this, NoSelection);
311 |
312 | this.message = "Please Select a Contact.";
313 | };
314 | });
315 | define('utility',["exports"], function (exports) {
316 | "use strict";
317 |
318 | Object.defineProperty(exports, "__esModule", {
319 | value: true
320 | });
321 | exports.areEqual = areEqual;
322 | function areEqual(obj1, obj2) {
323 | return Object.keys(obj1).every(function (key) {
324 | return obj2.hasOwnProperty(key) && obj1[key] === obj2[key];
325 | });
326 | };
327 | });
328 | define('web-api',['exports', 'axios'], function (exports, _axios) {
329 | 'use strict';
330 |
331 | Object.defineProperty(exports, "__esModule", {
332 | value: true
333 | });
334 | exports.WebAPI = undefined;
335 |
336 | var _axios2 = _interopRequireDefault(_axios);
337 |
338 | function _interopRequireDefault(obj) {
339 | return obj && obj.__esModule ? obj : {
340 | default: obj
341 | };
342 | }
343 |
344 | function _classCallCheck(instance, Constructor) {
345 | if (!(instance instanceof Constructor)) {
346 | throw new TypeError("Cannot call a class as a function");
347 | }
348 | }
349 |
350 | var axiosInstance = _axios2.default.create({
351 | baseURL: 'https://9own2oqyrh.execute-api.us-east-1.amazonaws.com/dev/candidates'
352 | });
353 |
354 | var WebAPI = exports.WebAPI = function () {
355 | function WebAPI() {
356 | _classCallCheck(this, WebAPI);
357 |
358 | this.isRequesting = false;
359 | }
360 |
361 | WebAPI.prototype.getCandidateList = function getCandidateList() {
362 | var _this = this;
363 |
364 | this.isRequesting = true;
365 | return axiosInstance.get('').then(function (response) {
366 | _this.isRequesting = false;
367 | var data = response.data;
368 | return data.candidates;
369 | }).catch(function (err) {
370 | console.log("Received failure from API", err);
371 | _this.isRequesting = false;
372 | throw err;
373 | });
374 | };
375 |
376 | WebAPI.prototype.getCandidateDetails = function getCandidateDetails(candidateId) {
377 | var _this2 = this;
378 |
379 | this.isRequesting = true;
380 | return axiosInstance.get('/' + candidateId).then(function (response) {
381 | _this2.isRequesting = false;
382 | return response.data;
383 | }).catch(function (err) {
384 | console.log("Received failure from API", err);
385 | _this2.isRequesting = false;
386 | throw err;
387 | });
388 | };
389 |
390 | WebAPI.prototype.submitCandidate = function submitCandidate(candidate) {
391 | var _this3 = this;
392 |
393 | this.isRequesting = true;
394 | return axiosInstance.post('', candidate).then(function (res) {
395 | _this3.isRequesting = false;
396 | return res;
397 | }).catch(function (err) {
398 | console.log("Received failure from API", err);
399 | _this3.isRequesting = false;
400 | throw err;
401 | });;
402 | };
403 |
404 | return WebAPI;
405 | }();
406 | });
407 | define('resources/index',['exports'], function (exports) {
408 | 'use strict';
409 |
410 | Object.defineProperty(exports, "__esModule", {
411 | value: true
412 | });
413 | exports.configure = configure;
414 | function configure(config) {
415 | config.globalResources(['./elements/loading-indicator']);
416 | }
417 | });
418 | define('resources/elements/loading-indicator',['exports', 'nprogress', 'aurelia-framework'], function (exports, _nprogress, _aureliaFramework) {
419 | 'use strict';
420 |
421 | Object.defineProperty(exports, "__esModule", {
422 | value: true
423 | });
424 | exports.LoadingIndicator = undefined;
425 |
426 | var nprogress = _interopRequireWildcard(_nprogress);
427 |
428 | function _interopRequireWildcard(obj) {
429 | if (obj && obj.__esModule) {
430 | return obj;
431 | } else {
432 | var newObj = {};
433 |
434 | if (obj != null) {
435 | for (var key in obj) {
436 | if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
437 | }
438 | }
439 |
440 | newObj.default = obj;
441 | return newObj;
442 | }
443 | }
444 |
445 | function _classCallCheck(instance, Constructor) {
446 | if (!(instance instanceof Constructor)) {
447 | throw new TypeError("Cannot call a class as a function");
448 | }
449 | }
450 |
451 | var LoadingIndicator = exports.LoadingIndicator = (0, _aureliaFramework.decorators)((0, _aureliaFramework.noView)(['nprogress/nprogress.css']), (0, _aureliaFramework.bindable)({ name: 'loading', defaultValue: false })).on(function () {
452 | function _class() {
453 | _classCallCheck(this, _class);
454 | }
455 |
456 | _class.prototype.loadingChanged = function loadingChanged(newValue) {
457 | if (newValue) {
458 | nprogress.start();
459 | } else {
460 | nprogress.done();
461 | }
462 | };
463 |
464 | return _class;
465 | }());
466 | });
467 | define('text!app.html', ['module'], function(module) { module.exports = ""; });
468 | define('text!styles.css', ['module'], function(module) { module.exports = "body { padding-top: 70px; }\n\nsection {\n margin: 0 20px;\n}\n\na:focus {\n outline: none;\n}\n\n.navbar-nav li.loader {\n margin: 12px 24px 0 6px;\n}\n\n.no-selection {\n margin: 20px;\n}\n\n.contact-list {\n overflow-y: auto;\n border: 1px solid #ddd;\n padding: 10px;\n}\n\n.panel {\n margin: 20px;\n}\n\n.button-bar {\n right: 0;\n left: 0;\n bottom: 0;\n border-top: 1px solid #ddd;\n background: white;\n}\n\n.button-bar > button {\n float: right;\n margin: 20px;\n}\n\nli.list-group-item {\n list-style: none;\n}\n\nli.list-group-item > a {\n text-decoration: none;\n}\n\nli.list-group-item.active > a {\n color: white;\n}\n"; });
469 | define('text!candidate-details.html', ['module'], function(module) { module.exports = ""; });
470 | define('text!candidate-form.html', ['module'], function(module) { module.exports = ""; });
471 | define('text!candidate-list.html', ['module'], function(module) { module.exports = ""; });
472 | define('text!no-selection.html', ['module'], function(module) { module.exports = "${message}
"; });
473 | //# sourceMappingURL=app-bundle.js.map
--------------------------------------------------------------------------------