diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..6be0ca76 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Intellij files +.idea/ + +# gradle's output dir +build/ + +# the gradle temp dir +.gradle + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar +out +artifact-skeleton-plugin.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..829fe1a1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 00000000..65141135 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Artifact plugin skeleton + +This is merely a skeleton plugin that plugin developers can fork to get quickly +started with writing artifact plugins for GoCD. + +## Getting started + +* Coming soon + +## Building the code base + +To build the jar, run `./gradlew clean test assemble` + +## License + +```plain +Copyright 2017 ThoughtWorks, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +## About the license and releasing your plugin under a different license + +The skeleton code in this repository is licensed under the Apache 2.0 license. The license itself specifies the terms +under which derivative works may be distributed (the license also defines derivative works). The Apache 2.0 license is a +permissive open source license that has minimal requirements for downstream licensors/licensees to comply with. + +This does not prevent your plugin from being licensed under a different license as long as you comply with the relevant +clauses of the Apache 2.0 license (especially section 4). Typically, you clone this repository and keep the existing +copyright notices. You are free to add your own license and copyright notice to any modifications. + +This is not legal advice. Please contact your lawyers if needed. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..933d1cd1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,68 @@ +/* + * Copyright 2017 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +apply plugin: 'java' + +group = 'cd.go.artifact.docker' +version = '0.0.1' + +project.ext.pluginDesc = [ + id : 'cd.go.artifact.docker', + version : project.version, + goCdVersion: '17.12.0', + name : 'Artifact plugin for docker', + description: 'Some longer description of your plugin goes here', + vendorName : 'Acme Corp', + vendorUrl : 'https://github.com/user/repository' +] + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + compileOnly group: 'cd.go.plugin', name: 'go-plugin-api', version: project.pluginDesc.goCdVersion + compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2' + compile group: 'io.fabric8', name: 'docker-client', version: '1.3.1' + + testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'org.assertj', name: 'assertj-core', version: '3.8.0' + testCompile group: 'org.mockito', name: 'mockito-core', version: '2.13.0' + testCompile group: 'org.skyscreamer', name: 'jsonassert', version: '1.3.0' + testCompile group: 'org.jsoup', name: 'jsoup', version: '1.10.2' + testCompile group: 'cd.go.plugin', name: 'go-plugin-api', version: project.pluginDesc.goCdVersion +} + +processResources { + from("src/main/resource-templates") { + filesMatching('plugin.xml') { + expand project.pluginDesc + } + + filesMatching('plugin.properties') { + expand project.pluginDesc + } + } +} + +jar { + from(configurations.compile) { + into "lib/" + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7a3265ee Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..bf1b63c3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..cccdd3d5 --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..e95643d6 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..6c36c3ac --- /dev/null +++ b/settings.gradle @@ -0,0 +1,17 @@ +/* + * Copyright 2017 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +rootProject.name = 'docker-artifact-plugin' diff --git a/src/main/java/cd/go/artifact/docker/Constants.java b/src/main/java/cd/go/artifact/docker/Constants.java new file mode 100644 index 00000000..daf5e489 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/Constants.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +import com.thoughtworks.go.plugin.api.GoPluginIdentifier; + +import java.util.Collections; + +public interface Constants { + // The type of this extension + String EXTENSION_TYPE = "artifact"; + + // The extension point API version that this plugin understands + String API_VERSION = "1.0"; + + // the identifier of this plugin + GoPluginIdentifier PLUGIN_IDENTIFIER = new GoPluginIdentifier(EXTENSION_TYPE, Collections.singletonList(API_VERSION)); + + // requests that the plugin makes to the server + String REQUEST_SERVER_PREFIX = "go.processor"; + String REQUEST_SERVER_GET_PLUGIN_SETTINGS = REQUEST_SERVER_PREFIX + ".plugin-settings.get"; +} diff --git a/src/main/java/cd/go/artifact/docker/DockerArtifactPlugin.java b/src/main/java/cd/go/artifact/docker/DockerArtifactPlugin.java new file mode 100644 index 00000000..fa2564d2 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/DockerArtifactPlugin.java @@ -0,0 +1,93 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +import cd.go.artifact.docker.executors.*; +import cd.go.artifact.docker.utils.Util; +import com.thoughtworks.go.plugin.api.GoApplicationAccessor; +import com.thoughtworks.go.plugin.api.GoPlugin; +import com.thoughtworks.go.plugin.api.GoPluginIdentifier; +import com.thoughtworks.go.plugin.api.annotation.Extension; +import com.thoughtworks.go.plugin.api.annotation.Load; +import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; +import com.thoughtworks.go.plugin.api.info.PluginContext; +import com.thoughtworks.go.plugin.api.logging.Logger; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.Properties; + +import static cd.go.artifact.docker.Constants.PLUGIN_IDENTIFIER; + +@Extension +public class DockerArtifactPlugin implements GoPlugin { + public static final Logger LOG = Logger.getLoggerFor(cd.go.artifact.docker.DockerArtifactPlugin.class); + private GoApplicationAccessor accessor; + + @Load + public void onLoad(PluginContext ctx) { + final Properties properties = Util.getPluginProperties(); + LOG.info(String.format("Loading plugin %s[%s].", properties.getProperty("name"), properties.getProperty("pluginId"))); + } + + @Override + public void initializeGoApplicationAccessor(GoApplicationAccessor accessor) { + this.accessor = accessor; + } + + @Override + public GoPluginApiResponse handle(GoPluginApiRequest request) { + try { + switch (Request.fromString(request.requestName())) { + case REQUEST_GET_PLUGIN_ICON: + return new GetPluginIconExecutor().execute(); + case REQUEST_STORE_CONFIG_METADATA: + return new GetArtifactStoreConfigMetadataExecutor().execute(); + case REQUEST_STORE_CONFIG_VIEW: + return new GetArtifactStoreViewExecutor().execute(); + case REQUEST_STORE_CONFIG_VALIDATE: + return new ValidateArtifactStoreConfigExecutor(request).execute(); + case REQUEST_PUBLISH_ARTIFACT_METADATA: + return new GetPublishArtifactConfigMetadataExecutor().execute(); + case REQUEST_PUBLISH_ARTIFACT_VIEW: + return new GetPublishArtifactViewExecutor().execute(); + case REQUEST_PUBLISH_ARTIFACT_VALIDATE: + return new ValidatePublishArtifactConfigExecutor(request).execute(); + case REQUEST_FETCH_ARTIFACT_METADATA: + return new GetFetchArtifactMetadataExecutor().execute(); + case REQUEST_FETCH_ARTIFACT_VIEW: + return new GetFetchArtifactViewExecutor().execute(); + case REQUEST_FETCH_ARTIFACT_VALIDATE: + return new ValidateFetchArtifactConfigExecutor(request).execute(); + case REQUEST_PUBLISH_ARTIFACT: + return new PublishArtifactExecutor(request).execute(); + case REQUEST_FETCH_ARTIFACT: + return new FetchArtifactExecutor(request).execute(); + default: + throw new UnhandledRequestTypeException(request.requestName()); + } + } catch (Exception e) { + LOG.error("Error while executing request " + request.requestName(), e); + throw new RuntimeException(e); + } + } + + @Override + public GoPluginIdentifier pluginIdentifier() { + return PLUGIN_IDENTIFIER; + } +} diff --git a/src/main/java/cd/go/artifact/docker/DockerClientFactory.java b/src/main/java/cd/go/artifact/docker/DockerClientFactory.java new file mode 100644 index 00000000..da06d0a7 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/DockerClientFactory.java @@ -0,0 +1,56 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +import cd.go.artifact.docker.model.ArtifactStoreConfig; +import io.fabric8.docker.api.model.AuthConfig; +import io.fabric8.docker.client.Config; +import io.fabric8.docker.client.ConfigBuilder; +import io.fabric8.docker.client.DefaultDockerClient; +import io.fabric8.docker.client.DockerClient; + +import java.util.Collections; + +import static cd.go.artifact.docker.DockerArtifactPlugin.LOG; +import static java.text.MessageFormat.format; + +public class DockerClientFactory { + private static final DockerClientFactory DOCKER_CLIENT_FACTORY = new DockerClientFactory(); + + public synchronized DockerClient docker(ArtifactStoreConfig artifactStoreConfig) throws Exception { + return createClient(artifactStoreConfig); + } + + public static DockerClientFactory instance() { + return DOCKER_CLIENT_FACTORY; + } + + private static DefaultDockerClient createClient(ArtifactStoreConfig artifactStoreConfig) { + Config config = new ConfigBuilder() + .withAuthConfigs(Collections.singletonMap(artifactStoreConfig.getRegistryUrl(), new AuthConfig(null, null, artifactStoreConfig.getPassword(), artifactStoreConfig.getRegistryUrl(), artifactStoreConfig.getUsername()))) + .build(); + + LOG.info(format("Using docker registry server `{0}`.", artifactStoreConfig.getRegistryUrl())); + + DefaultDockerClient docker = new DefaultDockerClient(config); + docker.ping(); + if (!docker.ping()) { + throw new RuntimeException("Could not ping the docker server."); + } + return docker; + } +} \ No newline at end of file diff --git a/src/main/java/cd/go/artifact/docker/DockerEventListener.java b/src/main/java/cd/go/artifact/docker/DockerEventListener.java new file mode 100644 index 00000000..f5c330dd --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/DockerEventListener.java @@ -0,0 +1,52 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +import io.fabric8.docker.dsl.EventListener; + +import java.util.concurrent.CountDownLatch; + +public class DockerEventListener implements EventListener { + private final CountDownLatch pushDone = new CountDownLatch(1); + + @Override + public void onSuccess(String message) { + System.out.println("Success:" + message); + pushDone.countDown(); + } + + @Override + public void onError(String messsage) { + System.err.println("Failure:" + messsage); + pushDone.countDown(); + } + + @Override + public void onError(Throwable t) { + t.printStackTrace(System.err); + pushDone.countDown(); + } + + @Override + public void onEvent(String event) { + System.out.println(event); + } + + public void await() throws InterruptedException { + pushDone.await(); + } +} diff --git a/src/main/java/cd/go/artifact/docker/Request.java b/src/main/java/cd/go/artifact/docker/Request.java new file mode 100644 index 00000000..135c542a --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/Request.java @@ -0,0 +1,61 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +/** + * Enumerable that represents one of the messages that the server sends to the plugin + */ +public enum Request { + REQUEST_GET_PLUGIN_ICON(String.join(".", "cd.go.artifact", "get-icon")), + + REQUEST_STORE_CONFIG_METADATA(String.join(".", "cd.go.artifact", "store", "get-metadata")), + REQUEST_STORE_CONFIG_VIEW(String.join(".", "cd.go.artifact", "store", "get-view")), + REQUEST_STORE_CONFIG_VALIDATE(String.join(".", "cd.go.artifact", "store", "validate")), + + REQUEST_PUBLISH_ARTIFACT_METADATA(String.join(".", "cd.go.artifact", "publish", "get-metadata")), + REQUEST_PUBLISH_ARTIFACT_VIEW(String.join(".", "cd.go.artifact", "publish", "get-view")), + REQUEST_PUBLISH_ARTIFACT_VALIDATE(String.join(".", "cd.go.artifact", "publish", "validate")), + + REQUEST_FETCH_ARTIFACT_METADATA(String.join(".", "cd.go.artifact", "fetch", "get-metadata")), + REQUEST_FETCH_ARTIFACT_VIEW(String.join(".", "cd.go.artifact", "fetch", "get-view")), + REQUEST_FETCH_ARTIFACT_VALIDATE(String.join(".", "cd.go.artifact", "fetch", "validate")), + + REQUEST_PUBLISH_ARTIFACT(String.join(".", "cd.go.artifact", "publish-artifact")), + REQUEST_FETCH_ARTIFACT(String.join(".", "cd.go.artifact", "fetch-artifact")); + + private final String requestName; + + Request(String requestName) { + this.requestName = requestName; + } + + public String requestName() { + return requestName; + } + + public static Request fromString(String requestName) { + if (requestName != null) { + for (Request request : Request.values()) { + if (requestName.equalsIgnoreCase(request.requestName)) { + return request; + } + } + } + + return null; + } +} diff --git a/src/main/java/cd/go/artifact/docker/ServerRequestFailedException.java b/src/main/java/cd/go/artifact/docker/ServerRequestFailedException.java new file mode 100644 index 00000000..7bba43b2 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/ServerRequestFailedException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker; + +import com.thoughtworks.go.plugin.api.response.GoApiResponse; + +import static java.lang.String.format; + +public class ServerRequestFailedException extends Exception { + + private ServerRequestFailedException(GoApiResponse response, String request) { + super(format( + "The server sent an unexpected status code %d with the response body %s when it was sent a %s message", + response.responseCode(), response.responseBody(), request + )); + } + + public static ServerRequestFailedException getPluginSettings(GoApiResponse response) { + return new ServerRequestFailedException(response, "get plugin settings"); + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/ConfigMetadata.java b/src/main/java/cd/go/artifact/docker/annotation/ConfigMetadata.java new file mode 100644 index 00000000..7d3900df --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/ConfigMetadata.java @@ -0,0 +1,65 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import static cd.go.artifact.docker.utils.Util.isNotBlank; + +public class ConfigMetadata { + + @Expose + @SerializedName("key") + private String key; + + @Expose + @SerializedName("metadata") + private T metadata; + + public ConfigMetadata(String key, T metadata) { + this.key = key; + this.metadata = metadata; + } + + public ValidationError validate(String input) { + String validationError = doValidate(input); + if (isNotBlank(validationError)) { + return new ValidationError(key, validationError); + } + return null; + } + + protected String doValidate(String input) { + if (isRequired()) { + if (Util.isBlank(input)) { + return this.key + " must not be blank."; + } + } + return null; + } + + + public String getKey() { + return key; + } + + public boolean isRequired() { + return metadata.isRequired(); + } +} \ No newline at end of file diff --git a/src/main/java/cd/go/artifact/docker/annotation/FieldMetadata.java b/src/main/java/cd/go/artifact/docker/annotation/FieldMetadata.java new file mode 100644 index 00000000..de514d7f --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/FieldMetadata.java @@ -0,0 +1,54 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class FieldMetadata implements Metadata { + + @Expose + @SerializedName("required") + private boolean required; + + @Expose + @SerializedName("secure") + private boolean secure; + + private FieldType type; + + public FieldMetadata(boolean required, boolean secure, FieldType type) { + this.required = required; + this.secure = secure; + this.type = type; + } + + @Override + public boolean isRequired() { + return required; + } + + @Override + public boolean isSecure() { + return secure; + } + + @Override + public FieldType getType() { + return type; + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/FieldType.java b/src/main/java/cd/go/artifact/docker/annotation/FieldType.java new file mode 100644 index 00000000..a427fc3b --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/FieldType.java @@ -0,0 +1,57 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +public enum FieldType { + STRING { + @Override + public String validate(String value) { + return null; + } + }, + + POSITIVE_DECIMAL { + @Override + public String validate(String value) { + try { + if (Long.parseLong(value) < 0) { + return "must be positive decimal"; + } + } catch (Exception e) { + return "must be positive decimal"; + } + return null; + } + }, + + NUMBER { + @Override + public String validate(String value) { + try { + if (Double.parseDouble(value) < 0) { + return "must be number"; + } + } catch (Exception e) { + return "must be number"; + } + + return null; + } + }; + + public abstract String validate(String value); +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/Metadata.java b/src/main/java/cd/go/artifact/docker/annotation/Metadata.java new file mode 100644 index 00000000..4a843117 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/Metadata.java @@ -0,0 +1,25 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +public interface Metadata { + boolean isRequired(); + + boolean isSecure(); + + FieldType getType(); +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/MetadataHelper.java b/src/main/java/cd/go/artifact/docker/annotation/MetadataHelper.java new file mode 100644 index 00000000..93f0c0a1 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/MetadataHelper.java @@ -0,0 +1,42 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + + +import java.lang.reflect.Field; +import java.util.*; + +public class MetadataHelper { + + public static List getMetadata(Class clazz) { + return buildMetadata(clazz); + } + + private static List buildMetadata(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + List metadata = new ArrayList<>(); + for (Field field : fields) { + ProfileField profileField = field.getAnnotation(ProfileField.class); + if (profileField != null) { + final FieldMetadata fieldMetadata = new FieldMetadata(profileField.required(), profileField.secure(), profileField.type()); + final ConfigMetadata configMetadata = new ConfigMetadata<>(profileField.key(), fieldMetadata); + metadata.add(configMetadata); + } + } + return metadata; + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/MetadataValidator.java b/src/main/java/cd/go/artifact/docker/annotation/MetadataValidator.java new file mode 100644 index 00000000..5e209883 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/MetadataValidator.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import java.util.*; + +public class MetadataValidator { + + public ValidationResult validate(Validatable configuration) { + final ValidationResult validationResult = new ValidationResult(); + Map properties = configuration.toProperties(); + + List knownFields = new ArrayList<>(); + for (ConfigMetadata field : MetadataHelper.getMetadata(configuration.getClass())) { + knownFields.add(field.getKey()); + validationResult.addError(field.validate(properties.get(field.getKey()))); + } + + return validationResult; + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/ProfileField.java b/src/main/java/cd/go/artifact/docker/annotation/ProfileField.java new file mode 100644 index 00000000..654d0538 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/ProfileField.java @@ -0,0 +1,34 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ProfileField { + String key(); + + boolean required(); + + boolean secure(); + + FieldType type() default FieldType.STRING; +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/Validatable.java b/src/main/java/cd/go/artifact/docker/annotation/Validatable.java new file mode 100644 index 00000000..60dcdc1b --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/Validatable.java @@ -0,0 +1,34 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import com.google.gson.reflect.TypeToken; + +import java.util.Map; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public interface Validatable { + default String toJSON() { + return GSON.toJson(this); + } + + default Map toProperties() { + return GSON.fromJson(toJSON(), new TypeToken>() { + }.getType()); + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/ValidationError.java b/src/main/java/cd/go/artifact/docker/annotation/ValidationError.java new file mode 100644 index 00000000..9134dd55 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/ValidationError.java @@ -0,0 +1,60 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ValidationError { + @Expose + @SerializedName("key") + private final String key; + @Expose + @SerializedName("message") + private final String message; + + public ValidationError(String key, String message) { + this.key = key; + this.message = message; + } + + public String key() { + return key; + } + + public String message() { + return message; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ValidationError that = (ValidationError) o; + + if (key != null ? !key.equals(that.key) : that.key != null) return false; + return message != null ? message.equals(that.message) : that.message == null; + } + + @Override + public int hashCode() { + int result = key != null ? key.hashCode() : 0; + result = 31 * result + (message != null ? message.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/cd/go/artifact/docker/annotation/ValidationResult.java b/src/main/java/cd/go/artifact/docker/annotation/ValidationResult.java new file mode 100644 index 00000000..23819f14 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/annotation/ValidationResult.java @@ -0,0 +1,59 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.annotation; + +import cd.go.artifact.docker.utils.Util; + +import java.util.*; + +public class ValidationResult { + private final Set errors = new HashSet<>(); + + public ValidationResult() { + } + + public ValidationResult(Collection errors) { + this.errors.addAll(errors); + } + + public void addError(String key, String message) { + errors.add(new ValidationError(key, message)); + } + + public void addError(ValidationError validationError) { + if (validationError == null) { + return; + } + errors.add(validationError); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } + + public String toJSON() { + return Util.GSON.toJson(errors); + } + + public boolean hasKey(String key) { + return errors.stream().anyMatch(validationError -> key.equals(validationError.key())); + } + + public List errors() { + return Collections.unmodifiableList(new ArrayList<>(errors)); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/FetchArtifactExecutor.java b/src/main/java/cd/go/artifact/docker/executors/FetchArtifactExecutor.java new file mode 100644 index 00000000..65fcab9a --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/FetchArtifactExecutor.java @@ -0,0 +1,82 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.ArtifactStoreConfig; +import cd.go.artifact.docker.model.FetchArtifactConfig; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.Map; + +import static cd.go.artifact.docker.DockerArtifactPlugin.LOG; +import static cd.go.artifact.docker.utils.Util.GSON; + +public class FetchArtifactExecutor implements RequestExecutor { + private FetchArtifactRequest fetchArtifactRequest; + + public FetchArtifactExecutor(GoPluginApiRequest request) { + this.fetchArtifactRequest = FetchArtifactRequest.fromJSON(request.requestBody()); + } + + @Override + public GoPluginApiResponse execute() { + fetch(fetchArtifactRequest); + return DefaultGoPluginApiResponse.success(""); + } + + private void fetch(FetchArtifactRequest fetchArtifactRequest) { + LOG.info(String.format("Fetching artifact %s", fetchArtifactRequest.getFetchArtifactConfig())); + try { + throw new RuntimeException("Implement me!"); + } catch (Exception e) { + LOG.error("Failed to download artifact s" + e.getMessage(), e); + throw new RuntimeException(e); + } + } + + private static class FetchArtifactRequest { + @Expose + @SerializedName("store_configuration") + private ArtifactStoreConfig artifactStoreConfig; + @Expose + @SerializedName("fetch_artifact_configuration") + private FetchArtifactConfig fetchArtifactConfig; + @Expose + @SerializedName("artifact_metadata") + private Map metadata; + + public ArtifactStoreConfig getArtifactStoreConfig() { + return artifactStoreConfig; + } + + public FetchArtifactConfig getFetchArtifactConfig() { + return fetchArtifactConfig; + } + + public Map getMetadata() { + return metadata; + } + + public static FetchArtifactRequest fromJSON(String json) { + return GSON.fromJson(json, FetchArtifactRequest.class); + } + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutor.java new file mode 100644 index 00000000..bc95bbc9 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.ConfigMetadata; +import cd.go.artifact.docker.annotation.MetadataHelper; +import cd.go.artifact.docker.model.ArtifactStoreConfig; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.List; + +public class GetArtifactStoreConfigMetadataExecutor implements RequestExecutor { + private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + + public GoPluginApiResponse execute() { + final List storeConfigMetadata = MetadataHelper.getMetadata(ArtifactStoreConfig.class); + return DefaultGoPluginApiResponse.success( GSON.toJson(storeConfigMetadata)); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutor.java new file mode 100644 index 00000000..a9fbcfb2 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class GetArtifactStoreViewExecutor implements RequestExecutor { + private static final Gson GSON = new Gson(); + + @Override + public GoPluginApiResponse execute() { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("template", Util.readResource("/artifact-store.template.html")); + DefaultGoPluginApiResponse defaultGoPluginApiResponse = DefaultGoPluginApiResponse.success( GSON.toJson(jsonObject)); + return defaultGoPluginApiResponse; + } + +} diff --git a/src/main/java/cd/go/artifact/docker/executors/GetCapabilitiesExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetCapabilitiesExecutor.java new file mode 100644 index 00000000..4a098a85 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetCapabilitiesExecutor.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.Capabilities; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import static com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse.SUCCESS_RESPONSE_CODE; + +public class GetCapabilitiesExecutor { + + public GoPluginApiResponse execute() { + Capabilities capabilities = getCapabilities(); + return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, capabilities.toJSON()); + } + + Capabilities getCapabilities() { + return new Capabilities(); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutor.java new file mode 100644 index 00000000..c0db6f97 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutor.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.ConfigMetadata; +import cd.go.artifact.docker.annotation.MetadataHelper; +import cd.go.artifact.docker.model.FetchArtifactConfig; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.List; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class GetFetchArtifactMetadataExecutor implements RequestExecutor { + public GoPluginApiResponse execute() { + final List metadata = MetadataHelper.getMetadata(FetchArtifactConfig.class); + return DefaultGoPluginApiResponse.success( GSON.toJson(metadata)); + } +} + diff --git a/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutor.java new file mode 100644 index 00000000..e50d3634 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutor.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class GetFetchArtifactViewExecutor implements RequestExecutor { + private static final Gson GSON = new Gson(); + + @Override + public GoPluginApiResponse execute() { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("template", Util.readResource("/fetch-artifact.template.html")); + return DefaultGoPluginApiResponse.success(GSON.toJson(jsonObject)); + } +} + diff --git a/src/main/java/cd/go/artifact/docker/executors/GetPluginIconExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetPluginIconExecutor.java new file mode 100644 index 00000000..e6c582b2 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetPluginIconExecutor.java @@ -0,0 +1,47 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.Base64; + +public class GetPluginIconExecutor implements RequestExecutor { + private static final Gson GSON = new Gson(); + + @Override + public GoPluginApiResponse execute() { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("content_type", getContentType()); + jsonObject.addProperty("data", Base64.getEncoder().encodeToString(Util.readResourceBytes(getIcon()))); + DefaultGoPluginApiResponse defaultGoPluginApiResponse = DefaultGoPluginApiResponse.success(GSON.toJson(jsonObject)); + return defaultGoPluginApiResponse; + } + + private String getContentType() { + return "image/svg+xml"; + } + + private String getIcon() { + return "/plugin-icon.svg"; + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutor.java new file mode 100644 index 00000000..38d3fee7 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutor.java @@ -0,0 +1,35 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.ArtifactPlanConfig; +import cd.go.artifact.docker.annotation.ConfigMetadata; +import cd.go.artifact.docker.annotation.MetadataHelper; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +import java.util.List; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class GetPublishArtifactConfigMetadataExecutor implements RequestExecutor { + public GoPluginApiResponse execute() { + final List metadata = MetadataHelper.getMetadata(ArtifactPlanConfig.class); + return DefaultGoPluginApiResponse.success( GSON.toJson(metadata)); + } +} + diff --git a/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutor.java b/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutor.java new file mode 100644 index 00000000..cd67b00a --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class GetPublishArtifactViewExecutor implements RequestExecutor { + private static final Gson GSON = new Gson(); + + @Override + public GoPluginApiResponse execute() { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("template", Util.readResource("/publish-artifact.template.html")); + return DefaultGoPluginApiResponse.success( GSON.toJson(jsonObject)); + } + +} + diff --git a/src/main/java/cd/go/artifact/docker/executors/PublishArtifactExecutor.java b/src/main/java/cd/go/artifact/docker/executors/PublishArtifactExecutor.java new file mode 100644 index 00000000..696ab06e --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/PublishArtifactExecutor.java @@ -0,0 +1,99 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.DockerClientFactory; +import cd.go.artifact.docker.DockerEventListener; +import cd.go.artifact.docker.model.*; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import io.fabric8.docker.client.DockerClient; +import io.fabric8.docker.dsl.OutputHandle; + +import java.util.List; +import java.util.Map; + +import static cd.go.artifact.docker.DockerArtifactPlugin.LOG; +import static java.lang.String.format; + +public class PublishArtifactExecutor implements RequestExecutor { + private final PublishArtifactConfig publishArtifactConfig; + private final PublishArtifactResponse publishArtifactResponse; + private final DockerClientFactory clientFactory; + + public PublishArtifactExecutor(GoPluginApiRequest request) { + this(request, DockerClientFactory.instance()); + } + + PublishArtifactExecutor(GoPluginApiRequest request, DockerClientFactory clientFactory) { + this.publishArtifactConfig = PublishArtifactConfig.fromJSON(request.requestBody()); + this.clientFactory = clientFactory; + publishArtifactResponse = new PublishArtifactResponse(); + } + + @Override + public GoPluginApiResponse execute() { + try { + publish(publishArtifactConfig); + } catch (Exception e) { + publishArtifactResponse.addError(String.format("Could not upload artifact: %s", e.getMessage())); + e.printStackTrace(); + } + return DefaultGoPluginApiResponse.success(publishArtifactResponse.toJSON()); + } + + private void publish(PublishArtifactConfig publishArtifactConfigs) throws Exception { + if (publishArtifactConfigs == null || publishArtifactConfigs.getArtifactInfos().isEmpty()) { + publishArtifactResponse.addError("No artifact to publish."); + return; + } + + for (ArtifactInfo artifactInfo : publishArtifactConfigs.getArtifactInfos()) { + publishArtifactsToArtifactStore(artifactInfo); + } + } + + private void publishArtifactsToArtifactStore(ArtifactInfo artifactInfo) throws Exception { + final ArtifactStoreConfig artifactStoreConfig = artifactInfo.getArtifactStoreConfig(); + final List artifactPlans = artifactInfo.getArtifactPlans(); + + for (ArtifactPlan artifactPlan : artifactPlans) { + publishArtifact(artifactStoreConfig, artifactPlan); + } + } + + private void publishArtifact(ArtifactStoreConfig artifactStoreConfig, ArtifactPlan artifactPlan) throws Exception { + final Map buildFile = artifactPlan.getArtifactPlanConfig().getImageAndTag(publishArtifactConfig.getAgentWorkingDir()); + final DockerClient docker = clientFactory.docker(artifactStoreConfig); + + LOG.info(format("Uploading artifact using %s to artifact store with id `%s`.", artifactPlan, artifactPlan.getStoreId())); + final String imageToPush = String.format("%s:%s", buildFile.get("image"), buildFile.get("tag")); + + + final DockerEventListener dockerEventListener = new DockerEventListener(); + OutputHandle handle = docker.image().withName(buildFile.get("image")).push() + .usingListener(dockerEventListener) + .withTag(buildFile.get("tag")) + .toRegistry(); + + dockerEventListener.await(); + handle.close(); + docker.close(); + publishArtifactResponse.addMetadata("docker-image", imageToPush); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/RequestExecutor.java b/src/main/java/cd/go/artifact/docker/executors/RequestExecutor.java new file mode 100644 index 00000000..550890a2 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/RequestExecutor.java @@ -0,0 +1,24 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public interface RequestExecutor { + + GoPluginApiResponse execute() throws Exception; +} diff --git a/src/main/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutor.java b/src/main/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutor.java new file mode 100644 index 00000000..8359db26 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutor.java @@ -0,0 +1,38 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.ArtifactStoreConfig; +import cd.go.artifact.docker.annotation.MetadataValidator; +import cd.go.artifact.docker.annotation.ValidationResult; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class ValidateArtifactStoreConfigExecutor implements RequestExecutor { + private final ArtifactStoreConfig artifactStoreConfig; + + public ValidateArtifactStoreConfigExecutor(GoPluginApiRequest request) { + artifactStoreConfig = ArtifactStoreConfig.fromJSON(request.requestBody()); + } + + @Override + public GoPluginApiResponse execute() { + final ValidationResult validationResult = new MetadataValidator().validate(artifactStoreConfig); + return DefaultGoPluginApiResponse.success(validationResult.toJSON()); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutor.java b/src/main/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutor.java new file mode 100644 index 00000000..8fac8050 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutor.java @@ -0,0 +1,38 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.FetchArtifactConfig; +import cd.go.artifact.docker.annotation.MetadataValidator; +import cd.go.artifact.docker.annotation.ValidationResult; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class ValidateFetchArtifactConfigExecutor implements RequestExecutor { + private final FetchArtifactConfig fetchArtifactConfig; + + public ValidateFetchArtifactConfigExecutor(GoPluginApiRequest request) { + fetchArtifactConfig = FetchArtifactConfig.fromJSON(request.requestBody()); + } + + @Override + public GoPluginApiResponse execute() { + final ValidationResult validationResult = new MetadataValidator().validate(fetchArtifactConfig); + return DefaultGoPluginApiResponse.success(validationResult.toJSON()); + } +} diff --git a/src/main/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutor.java b/src/main/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutor.java new file mode 100644 index 00000000..6b963bc6 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutor.java @@ -0,0 +1,38 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.model.ArtifactPlanConfig; +import cd.go.artifact.docker.annotation.MetadataValidator; +import cd.go.artifact.docker.annotation.ValidationResult; +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; + +public class ValidatePublishArtifactConfigExecutor implements RequestExecutor { + private final ArtifactPlanConfig artifactPlanConfig; + + public ValidatePublishArtifactConfigExecutor(GoPluginApiRequest request) { + artifactPlanConfig = ArtifactPlanConfig.fromJSON(request.requestBody()); + } + + @Override + public GoPluginApiResponse execute() { + final ValidationResult validationResult = new MetadataValidator().validate(artifactPlanConfig); + return DefaultGoPluginApiResponse.success(validationResult.toJSON()); + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/ArtifactInfo.java b/src/main/java/cd/go/artifact/docker/model/ArtifactInfo.java new file mode 100644 index 00000000..acf87a82 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/ArtifactInfo.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import java.util.List; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class ArtifactInfo { + @Expose + @SerializedName("id") + private String id; + + @Expose + @SerializedName("configuration") + private ArtifactStoreConfig artifactStoreConfig; + + @Expose + @SerializedName("artifact_plans") + private List artifactPlans; + + public static List fromJSONList(String requestBody) { + return GSON.fromJson(requestBody, new TypeToken>() { + }.getType()); + } + + public static ArtifactInfo fromJSON(String json) { + return GSON.fromJson(json, ArtifactInfo.class); + } + + public String getId() { + return id; + } + + public ArtifactStoreConfig getArtifactStoreConfig() { + return artifactStoreConfig; + } + + public List getArtifactPlans() { + return artifactPlans; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ArtifactInfo)) return false; + + ArtifactInfo that = (ArtifactInfo) o; + + if (id != null ? !id.equals(that.id) : that.id != null) return false; + if (artifactStoreConfig != null ? !artifactStoreConfig.equals(that.artifactStoreConfig) : that.artifactStoreConfig != null) + return false; + return artifactPlans != null ? artifactPlans.equals(that.artifactPlans) : that.artifactPlans == null; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (artifactStoreConfig != null ? artifactStoreConfig.hashCode() : 0); + result = 31 * result + (artifactPlans != null ? artifactPlans.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/ArtifactPlan.java b/src/main/java/cd/go/artifact/docker/model/ArtifactPlan.java new file mode 100644 index 00000000..faa2f2e0 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/ArtifactPlan.java @@ -0,0 +1,80 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ArtifactPlan { + @Expose + @SerializedName("id") + private String id; + + @Expose + @SerializedName("storeId") + private String storeId; + + @Expose + @SerializedName("configuration") + private ArtifactPlanConfig artifactPlanConfig; + + public ArtifactPlan() { + } + + public ArtifactPlan(String id, String storeId, ArtifactPlanConfig artifactPlanConfig) { + this.id = id; + this.storeId = storeId; + this.artifactPlanConfig = artifactPlanConfig; + } + + public String getId() { + return id; + } + + public String getStoreId() { + return storeId; + } + + public ArtifactPlanConfig getArtifactPlanConfig() { + return artifactPlanConfig; + } + + @Override + public String toString() { + return String.format("ArtifactPlan[id=%s, storeId=%s, configuration=%s]", getId(), getStoreId(), artifactPlanConfig); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ArtifactPlan)) return false; + + ArtifactPlan that = (ArtifactPlan) o; + + if (id != null ? !id.equals(that.id) : that.id != null) return false; + if (storeId != null ? !storeId.equals(that.storeId) : that.storeId != null) return false; + return artifactPlanConfig != null ? artifactPlanConfig.equals(that.artifactPlanConfig) : that.artifactPlanConfig == null; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (storeId != null ? storeId.hashCode() : 0); + result = 31 * result + (artifactPlanConfig != null ? artifactPlanConfig.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/ArtifactPlanConfig.java b/src/main/java/cd/go/artifact/docker/model/ArtifactPlanConfig.java new file mode 100644 index 00000000..1160f855 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/ArtifactPlanConfig.java @@ -0,0 +1,79 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import cd.go.artifact.docker.annotation.ProfileField; +import cd.go.artifact.docker.annotation.Validatable; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Map; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class ArtifactPlanConfig implements Validatable { + @Expose + @SerializedName("BuildFile") + @ProfileField(key = "BuildFile", required = true, secure = false) + private String buildFile; + + public ArtifactPlanConfig() { + } + + public ArtifactPlanConfig(String buildFile) { + this.buildFile = buildFile; + } + + public String getBuildFile() { + return buildFile; + } + + public Map getImageAndTag(String agentWorkingDirectory) throws IOException { + final byte[] bytes = Files.readAllBytes(Paths.get(agentWorkingDirectory, getBuildFile())); + return GSON.fromJson(new String(bytes, StandardCharsets.UTF_8), new TypeToken>() { + }.getType()); + } + + @Override + public String toString() { + return toJSON(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ArtifactPlanConfig)) return false; + + ArtifactPlanConfig that = (ArtifactPlanConfig) o; + + return buildFile != null ? buildFile.equals(that.buildFile) : that.buildFile == null; + } + + @Override + public int hashCode() { + return buildFile != null ? buildFile.hashCode() : 0; + } + + public static ArtifactPlanConfig fromJSON(String json) { + return GSON.fromJson(json, ArtifactPlanConfig.class); + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/ArtifactStoreConfig.java b/src/main/java/cd/go/artifact/docker/model/ArtifactStoreConfig.java new file mode 100644 index 00000000..a37dc6df --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/ArtifactStoreConfig.java @@ -0,0 +1,87 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import cd.go.artifact.docker.annotation.ProfileField; +import cd.go.artifact.docker.annotation.Validatable; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class ArtifactStoreConfig implements Validatable { + @Expose + @SerializedName("RegistryURL") + @ProfileField(key = "RegistryURL", required = true, secure = false) + private String registryUrl; + + @Expose + @SerializedName("Username") + @ProfileField(key = "Username", required = true, secure = false) + private String username; + + @Expose + @SerializedName("Password") + @ProfileField(key = "Password", required = true, secure = true) + private String password; + + + public ArtifactStoreConfig() { + } + + public ArtifactStoreConfig(String registryUrl,String username, String password) { + this.registryUrl = registryUrl; + this.username = username; + this.password = password; + } + + public String getRegistryUrl() { + return registryUrl; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ArtifactStoreConfig)) return false; + + ArtifactStoreConfig that = (ArtifactStoreConfig) o; + + if (registryUrl != null ? !registryUrl.equals(that.registryUrl) : that.registryUrl != null) return false; + if (username != null ? !username.equals(that.username) : that.username != null) return false; + return password != null ? password.equals(that.password) : that.password == null; + } + + @Override + public int hashCode() { + int result = registryUrl != null ? registryUrl.hashCode() : 0; + result = 31 * result + (username != null ? username.hashCode() : 0); + result = 31 * result + (password != null ? password.hashCode() : 0); + return result; + } + + public static ArtifactStoreConfig fromJSON(String json) { + return GSON.fromJson(json, ArtifactStoreConfig.class); + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/Capabilities.java b/src/main/java/cd/go/artifact/docker/model/Capabilities.java new file mode 100644 index 00000000..a4140469 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/Capabilities.java @@ -0,0 +1,32 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class Capabilities { + public Capabilities() { + } + + public static Capabilities fromJSON(String json) { + return GSON.fromJson(json, Capabilities.class); + } + + public String toJSON() { + return GSON.toJson(this); + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/FetchArtifactConfig.java b/src/main/java/cd/go/artifact/docker/model/FetchArtifactConfig.java new file mode 100644 index 00000000..658fd3cd --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/FetchArtifactConfig.java @@ -0,0 +1,30 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import cd.go.artifact.docker.annotation.Validatable; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class FetchArtifactConfig implements Validatable { + public FetchArtifactConfig() { + } + + public static FetchArtifactConfig fromJSON(String json) { + return GSON.fromJson(json, FetchArtifactConfig.class); + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/PublishArtifactConfig.java b/src/main/java/cd/go/artifact/docker/model/PublishArtifactConfig.java new file mode 100644 index 00000000..19affbd0 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/PublishArtifactConfig.java @@ -0,0 +1,65 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +import static cd.go.artifact.docker.utils.Util.GSON; + +public class PublishArtifactConfig { + @Expose + @SerializedName("agent_working_directory") + private String agentWorkingDir; + + @Expose + @SerializedName("artifact_infos") + private List artifactInfos; + + public static PublishArtifactConfig fromJSON(String json) { + return GSON.fromJson(json, PublishArtifactConfig.class); + } + + public String getAgentWorkingDir() { + return agentWorkingDir; + } + + public List getArtifactInfos() { + return artifactInfos; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof PublishArtifactConfig)) return false; + + PublishArtifactConfig that = (PublishArtifactConfig) o; + + if (agentWorkingDir != null ? !agentWorkingDir.equals(that.agentWorkingDir) : that.agentWorkingDir != null) + return false; + return artifactInfos != null ? artifactInfos.equals(that.artifactInfos) : that.artifactInfos == null; + } + + @Override + public int hashCode() { + int result = agentWorkingDir != null ? agentWorkingDir.hashCode() : 0; + result = 31 * result + (artifactInfos != null ? artifactInfos.hashCode() : 0); + return result; + } +} diff --git a/src/main/java/cd/go/artifact/docker/model/PublishArtifactResponse.java b/src/main/java/cd/go/artifact/docker/model/PublishArtifactResponse.java new file mode 100644 index 00000000..2493a752 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/model/PublishArtifactResponse.java @@ -0,0 +1,67 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PublishArtifactResponse { + private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + + public PublishArtifactResponse() { + } + + public PublishArtifactResponse(Map metadata, List errors) { + this.metadata = metadata; + this.errors = errors; + } + + @Expose + @SerializedName("metadata") + private Map metadata = new HashMap<>(); + + @Expose + @SerializedName("errors") + private List errors = new ArrayList<>(); + + public Map getMetadata() { + return metadata; + } + + public List getErrors() { + return errors; + } + + public void addMetadata(String key, String value) { + this.metadata.put(key, value); + } + + public void addError(String error) { + this.errors.add(error); + } + + public String toJSON() { + return GSON.toJson(this); + } +} diff --git a/src/main/java/cd/go/artifact/docker/utils/Util.java b/src/main/java/cd/go/artifact/docker/utils/Util.java new file mode 100644 index 00000000..5b1657f7 --- /dev/null +++ b/src/main/java/cd/go/artifact/docker/utils/Util.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.utils; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class Util { + public static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + + public static String readResource(String resourceFile) { + return new String(readResourceBytes(resourceFile), StandardCharsets.UTF_8); + } + + public static byte[] readResourceBytes(String resourceFile) { + try (InputStream is = Util.class.getResourceAsStream(resourceFile)) { + return readFully(is); + } catch (IOException e) { + throw new RuntimeException("Could not find resource " + resourceFile, e); + } + } + + private static byte[] readFully(InputStream input) throws IOException { + byte[] buffer = new byte[8192]; + int bytesRead; + ByteArrayOutputStream output = new ByteArrayOutputStream(); + while ((bytesRead = input.read(buffer)) != -1) { + output.write(buffer, 0, bytesRead); + } + return output.toByteArray(); + } + + public static String pluginId() { + return getPluginProperties().getProperty("pluginId"); + } + + public static Properties getPluginProperties() { + String propertiesAsAString = readResource("/plugin.properties"); + try { + Properties properties = new Properties(); + properties.load(new StringReader(propertiesAsAString)); + return properties; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static boolean isNotBlank(final CharSequence cs) { + return !isBlank(cs); + } + + public static boolean isBlank(final CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (Character.isWhitespace(cs.charAt(i)) == false) { + return false; + } + } + return true; + } +} + diff --git a/src/main/resource-templates/plugin.properties b/src/main/resource-templates/plugin.properties new file mode 100644 index 00000000..ab0a9338 --- /dev/null +++ b/src/main/resource-templates/plugin.properties @@ -0,0 +1,18 @@ +# +# Copyright 2017 ThoughtWorks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +name=${name} +pluginId=${id} +version=${version} diff --git a/src/main/resource-templates/plugin.xml b/src/main/resource-templates/plugin.xml new file mode 100644 index 00000000..0dea6241 --- /dev/null +++ b/src/main/resource-templates/plugin.xml @@ -0,0 +1,28 @@ + + + + + ${name} + ${version} + ${goCdVersion} + ${description} + + ${vendorName} + ${vendorUrl} + + + diff --git a/src/main/resources/artifact-store.template.html b/src/main/resources/artifact-store.template.html new file mode 100644 index 00000000..718548d6 --- /dev/null +++ b/src/main/resources/artifact-store.template.html @@ -0,0 +1,17 @@ +
+ + + {{GOINPUTNAME[RegistryUrl].$error.server}} +
+ +
+ + + {{GOINPUTNAME[Username].$error.server}} +
+ +
+ + + {{GOINPUTNAME[Password].$error.server}} +
\ No newline at end of file diff --git a/src/main/resources/fetch-artifact.template.html b/src/main/resources/fetch-artifact.template.html new file mode 100644 index 00000000..281c6866 --- /dev/null +++ b/src/main/resources/fetch-artifact.template.html @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/src/main/resources/plugin-icon.svg b/src/main/resources/plugin-icon.svg new file mode 100644 index 00000000..aef17d66 --- /dev/null +++ b/src/main/resources/plugin-icon.svg @@ -0,0 +1 @@ + diff --git a/src/main/resources/plugin-settings.template.html b/src/main/resources/plugin-settings.template.html new file mode 100644 index 00000000..dc26b534 --- /dev/null +++ b/src/main/resources/plugin-settings.template.html @@ -0,0 +1,44 @@ + + + +
+ + + {{GOINPUTNAME[go_server_url].$error.server}} +
+ +
+ + + {{GOINPUTNAME[api_url].$error.server}} +
+ +
+ + + {{GOINPUTNAME[api_user].$error.server}} +
+ +
+ + + {{GOINPUTNAME[api_key].$error.server}} +
diff --git a/src/main/resources/publish-artifact.template.html b/src/main/resources/publish-artifact.template.html new file mode 100644 index 00000000..11d6fb97 --- /dev/null +++ b/src/main/resources/publish-artifact.template.html @@ -0,0 +1,5 @@ +
+ + + {{GOINPUTNAME[BuildFile].$error.server}} +
\ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/FetchArtifactExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/FetchArtifactExecutorTest.java new file mode 100644 index 00000000..1096f951 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/FetchArtifactExecutorTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class FetchArtifactExecutorTest { + @Mock + private GoPluginApiRequest request; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void shouldFetchArtifact() { + when(request.requestBody()).thenReturn("{\"store_configuration\":{}, \"fetch_artifact_configuration\":{}, \"artifact_metadata\":{}}"); + + FetchArtifactExecutor executor = new FetchArtifactExecutor(request); + + executor.execute(); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutorTest.java new file mode 100644 index 00000000..369a45c6 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreConfigMetadataExecutorTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.json.JSONException; +import org.junit.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetArtifactStoreConfigMetadataExecutorTest { + @Test + public void shouldReturnFetchArtifactMetadata() throws JSONException { + final GoPluginApiResponse response = new GetArtifactStoreConfigMetadataExecutor().execute(); + + final String expectedJSON = "[\n" + + " {\n" + + " \"key\": \"RegistryURL\",\n" + + " \"metadata\": {\n" + + " \"required\": true,\n" + + " \"secure\": false\n" + + " }\n" + + " },\n" + + " {\n" + + " \"key\": \"Username\",\n" + + " \"metadata\": {\n" + + " \"required\": true,\n" + + " \"secure\": false\n" + + " }\n" + + " },\n" + + " {\n" + + " \"key\": \"Password\",\n" + + " \"metadata\": {\n" + + " \"required\": true,\n" + + " \"secure\": true\n" + + " }\n" + + " }\n" + + "]"; + + assertThat(response.responseCode()).isEqualTo(200); + JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutorTest.java new file mode 100644 index 00000000..3687bb60 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetArtifactStoreViewExecutorTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.Validatable; +import cd.go.artifact.docker.model.ArtifactStoreConfig; +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetArtifactStoreViewExecutorTest extends ViewTest { + @Test + public void shouldRenderTheTemplateInJSON() throws Exception { + GoPluginApiResponse response = getRequestExecutor().execute(); + + Map responseHash = new Gson().fromJson(response.responseBody(), HashMap.class); + + assertThat(response.responseCode()).isEqualTo(200); + assertThat(responseHash).containsEntry("template", Util.readResource("/artifact-store.template.html")); + } + + protected Class getConfigClass() { + return ArtifactStoreConfig.class; + } + + @Override + protected RequestExecutor getRequestExecutor() { + return new GetArtifactStoreViewExecutor(); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutorTest.java new file mode 100644 index 00000000..b85c4954 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactMetadataExecutorTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.json.JSONException; +import org.junit.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetFetchArtifactMetadataExecutorTest { + @Test + public void shouldReturnFetchArtifactMetadata() throws JSONException { + final GoPluginApiResponse response = new GetFetchArtifactMetadataExecutor().execute(); + + final String expectedJSON = "[]"; + + assertThat(response.responseCode()).isEqualTo(200); + JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutorTest.java new file mode 100644 index 00000000..cd367afe --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetFetchArtifactViewExecutorTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.Validatable; +import cd.go.artifact.docker.model.FetchArtifactConfig; +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetFetchArtifactViewExecutorTest extends ViewTest { + + @Test + public void shouldRenderTheTemplateInJSON() throws Exception { + GoPluginApiResponse response = getRequestExecutor().execute(); + + Map responseHash = new Gson().fromJson(response.responseBody(), HashMap.class); + + assertThat(response.responseCode()).isEqualTo(200); + assertThat(responseHash).containsEntry("template", Util.readResource("/fetch-artifact.template.html")); + } + + @Override + protected Class getConfigClass() { + return FetchArtifactConfig.class; + } + + @Override + protected RequestExecutor getRequestExecutor() { + return new GetFetchArtifactViewExecutor(); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetPluginIconExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetPluginIconExecutorTest.java new file mode 100644 index 00000000..9ee93314 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetPluginIconExecutorTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Test; + +import java.util.Base64; +import java.util.HashMap; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetPluginIconExecutorTest { + @Test + public void rendersIconInBase64() { + GoPluginApiResponse response = new GetPluginIconExecutor().execute(); + HashMap hashMap = new Gson().fromJson(response.responseBody(), HashMap.class); + assertThat(hashMap).hasSize(2); + assertThat(hashMap.get("content_type")).isEqualTo("image/svg+xml"); + assertThat(Util.readResourceBytes("/plugin-icon.svg")).isEqualTo(Base64.getDecoder().decode(hashMap.get("data"))); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutorTest.java new file mode 100644 index 00000000..8c22396e --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactConfigMetadataExecutorTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.json.JSONException; +import org.junit.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetPublishArtifactConfigMetadataExecutorTest { + @Test + public void shouldReturnFetchArtifactMetadata() throws JSONException { + final GoPluginApiResponse response = new GetPublishArtifactConfigMetadataExecutor().execute(); + + final String expectedJSON = "[{\"key\":\"BuildFile\",\"metadata\":{\"required\":true,\"secure\":false}}]"; + + assertThat(response.responseCode()).isEqualTo(200); + JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutorTest.java new file mode 100644 index 00000000..03d98c11 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/GetPublishArtifactViewExecutorTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.Validatable; +import cd.go.artifact.docker.model.ArtifactPlanConfig; +import cd.go.artifact.docker.utils.Util; +import com.google.gson.Gson; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetPublishArtifactViewExecutorTest extends ViewTest { + @Test + public void shouldRenderTheTemplateInJSON() throws Exception { + GoPluginApiResponse response = getRequestExecutor().execute(); + + Map responseHash = new Gson().fromJson(response.responseBody(), HashMap.class); + + assertThat(response.responseCode()).isEqualTo(200); + assertThat(responseHash).containsEntry("template", Util.readResource("/publish-artifact.template.html")); + } + + protected Class getConfigClass() { + return ArtifactPlanConfig.class; + } + + @Override + protected RequestExecutor getRequestExecutor() { + return new GetPublishArtifactViewExecutor(); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/PublishArtifactExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/PublishArtifactExecutorTest.java new file mode 100644 index 00000000..04f8e0b1 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/PublishArtifactExecutorTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PublishArtifactExecutorTest { + private GoPluginApiRequest request; + + @Before + public void setUp() { + request = mock(GoPluginApiRequest.class); + } + + @Test + public void shouldPublishArtifact() { + when(request.requestBody()).thenReturn("[]"); + + final GoPluginApiResponse response = new PublishArtifactExecutor(request).execute(); + + assertThat(response.responseCode()).isEqualTo(200); + assertThat(response.responseBody()).isEqualTo("{}"); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutorExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutorExecutorTest.java new file mode 100644 index 00000000..8f2a1040 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/ValidateArtifactStoreConfigExecutorExecutorTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class ValidateArtifactStoreConfigExecutorExecutorTest { + @Mock + private GoPluginApiRequest request; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void shouldValidateMandatoryKeys() throws Exception { + when(request.requestBody()).thenReturn("{}"); + + final GoPluginApiResponse response = new ValidateArtifactStoreConfigExecutor(request).execute(); + + String expectedJSON = "[\n" + + " {\n" + + " \"key\": \"RegistryURL\",\n" + + " \"message\": \"RegistryURL must not be blank.\"\n" + + " },\n" + + " {\n" + + " \"key\": \"Password\",\n" + + " \"message\": \"Password must not be blank.\"\n" + + " },\n" + + " {\n" + + " \"key\": \"Username\",\n" + + " \"message\": \"Username must not be blank.\"\n" + + " }\n" + + "]"; + JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutorTest.java new file mode 100644 index 00000000..7aab5c8d --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/ValidateFetchArtifactConfigExecutorTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class ValidateFetchArtifactConfigExecutorTest { + @Mock + private GoPluginApiRequest request; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void shouldValidateMandatoryKeys() throws Exception { + when(request.requestBody()).thenReturn("{}"); + + final GoPluginApiResponse response = new ValidateFetchArtifactConfigExecutor(request).execute(); + + String expectedJSON = "[]"; + JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutorTest.java b/src/test/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutorTest.java new file mode 100644 index 00000000..a0d9ad21 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/ValidatePublishArtifactConfigExecutorTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; + +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class ValidatePublishArtifactConfigExecutorTest { + @Mock + private GoPluginApiRequest request; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void shouldValidateMandatoryKeys() throws Exception { + when(request.requestBody()).thenReturn("{}"); + + final GoPluginApiResponse response = new ValidatePublishArtifactConfigExecutor(request).execute(); + + String expectedJSON = "[\n" + + " {\n" + + " \"key\": \"BuildFile\",\n" + + " \"message\": \"BuildFile must not be blank.\"\n" + + " }\n" + + "]"; + JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE); + } +} \ No newline at end of file diff --git a/src/test/java/cd/go/artifact/docker/executors/ViewTest.java b/src/test/java/cd/go/artifact/docker/executors/ViewTest.java new file mode 100644 index 00000000..2de85400 --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/executors/ViewTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.executors; + +import cd.go.artifact.docker.annotation.ConfigMetadata; +import cd.go.artifact.docker.annotation.MetadataHelper; +import cd.go.artifact.docker.annotation.Validatable; +import com.google.gson.Gson; +import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.select.Elements; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static java.text.MessageFormat.format; +import static org.assertj.core.api.Assertions.assertThat; + +public abstract class ViewTest { + @Test + public void allFieldsShouldBePresentInView() throws Exception { + final Document document = getDocument(); + final List metadataList = MetadataHelper.getMetadata(getConfigClass()); + for (ConfigMetadata field : metadataList) { + final String name = field.getKey(); + final Elements inputFieldForName = document.getElementsByAttributeValue("ng-model", name); + assertThat(inputFieldForName).describedAs(format("No input/textarea defined for {0}", name)).hasSize(1); + assertThat(inputFieldForName.get(0).attr("ng-class")) + .describedAs(format("ng-class attribute is not defined on {0}", inputFieldForName)) + .isEqualTo(format("'{'''is-invalid-input'': GOINPUTNAME[{0}].$error.server'}'", name)); + + final Elements spanToShowError = document.getElementsByAttributeValue("ng-class", format("'{'''is-visible'': GOINPUTNAME[{0}].$error.server'}'", name)); + assertThat(spanToShowError).hasSize(1); + assertThat(spanToShowError.attr("ng-show")).isEqualTo(format("GOINPUTNAME[{0}].$error.server", name)); + assertThat(spanToShowError.text()).isEqualTo(format("'{{'GOINPUTNAME[{0}].$error.server'}}'", name)); + } + + final Elements inputs = document.select("textarea, input, select"); + assertThat(inputs).describedAs("should contains only inputs that defined in ElasticProfile.java").hasSize(metadataList.size()); + } + + + private Document getDocument() throws Exception { + final GoPluginApiResponse response = getRequestExecutor().execute(); + final Map responseHash = new Gson().fromJson(response.responseBody(), HashMap.class); + + assertThat(response.responseCode()).isEqualTo(200); + assertThat(responseHash).containsKey("template"); + + return Jsoup.parse(responseHash.get("template")); + } + + protected abstract Class getConfigClass(); + + protected abstract RequestExecutor getRequestExecutor(); +} diff --git a/src/test/java/cd/go/artifact/docker/model/PublishArtifactConfigTest.java b/src/test/java/cd/go/artifact/docker/model/PublishArtifactConfigTest.java new file mode 100644 index 00000000..03e9762c --- /dev/null +++ b/src/test/java/cd/go/artifact/docker/model/PublishArtifactConfigTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2018 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.artifact.docker.model; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PublishArtifactConfigTest { + + @Test + public void shouldDeserializeRequestBody() { + final String json = "{\n" + + " \"artifact_infos\": [\n" + + " {\n" + + " \"configuration\": {\n" + + " \"Foo\": \"Bar\"\n" + + " },\n" + + " \"id\": \"s3-store\",\n" + + " \"artifact_plans\": [\n" + + " {\n" + + " \"configuration\": {\n" + + " \"BuildFile\": \"build-file.json\"\n" + + " },\n" + + " \"id\": \"alpine\",\n" + + " \"storeId\": \"s3-store\"\n" + + " },\n" + + " {\n" + + " \"configuration\": {\n" + + " \"BuildFile\": \"build-file2.json\"\n" + + " },\n" + + " \"id\": \"centos\",\n" + + " \"storeId\": \"s3-store\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"agent_working_directory\": \"/temp\"\n" + + "}"; + + final PublishArtifactConfig publishArtifactConfig = PublishArtifactConfig.fromJSON(json); + + assertThat(publishArtifactConfig.getArtifactInfos()).hasSize(1); + assertThat(publishArtifactConfig.getAgentWorkingDir()).isEqualTo("/temp"); + + final ArtifactInfo artifactInfo = publishArtifactConfig.getArtifactInfos().get(0); + assertThat(artifactInfo.getId()).isEqualTo("s3-store"); + assertThat(artifactInfo.getArtifactStoreConfig()).isEqualTo(new ArtifactStoreConfig(null, null, null)); + + assertThat(artifactInfo.getArtifactPlans()).hasSize(2); + assertThat(artifactInfo.getArtifactPlans()).containsExactlyInAnyOrder( + new ArtifactPlan("alpine", "s3-store", new ArtifactPlanConfig("build-file.json")), + new ArtifactPlan("centos", "s3-store", new ArtifactPlanConfig("build-file2.json")) + ); + } +} \ No newline at end of file