diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d0445f --- /dev/null +++ b/.gitignore @@ -0,0 +1,55 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/java,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle +.idea +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### Gradle ### +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# End of https://www.toptal.com/developers/gitignore/api/java,gradle \ No newline at end of file diff --git a/README b/README.MD similarity index 84% rename from README rename to README.MD index fbf530b..57b7ffc 100644 --- a/README +++ b/README.MD @@ -1,19 +1,19 @@ -# README # +# SFTP Extension -### What is this repository for? ### +## What is this repository for? The SFTP Extension allows you to configure Thingworx entities to connect to a remote SFTP (SSH File Transfer Protocol) server for the purposes of managing the file system, like copying, moving or deleting files, as well as file transfer functionalities, like uploading or downloading files. The extension uses SSH for its underlying transport, so it provides secure authentication and transport. Both password, and key based authentication are supported. - -### How do I get set up? ### +## How do I get set up? * To build the importable zip extension run the gradle task **packageExtension**. * Install the extension archive "zip/sftpExtension.zip" using the Extension import tool from ThingWorx. * Create Things that inherit the SftpRepositoryTemplate ThingTemplate. * On the created Things, configure them according to the documentation -### Developing ### +## Developing You can use the gradle tasks *eclipse* or *idea* to generate projects that you can use in your favourite IDE -This Extension is provided as-is and without warranty or support. It is not part of the PTC product suite. This project is licensed under the terms of the MIT license +Please open an issue or contact placatus@iqnox.com for support. +This Extension is provided as-is and without warranty or support. It is not part of the PTC product suite. This project is licensed under the terms of the MIT license. diff --git a/build.gradle b/build.gradle index cfbf9c5..f93887f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,42 +1,52 @@ -group 'com.thingworx.extensions' -version '1.0-SNAPSHOT' -apply plugin: 'idea' -apply plugin: 'eclipse' -apply plugin: 'java' +import groovyx.net.http.HTTPBuilder +import org.apache.http.entity.mime.MultipartEntityBuilder +import static groovyx.net.http.Method.POST + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'org.apache.httpcomponents:httpmime:4.5.2' + classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1' + } +} -defaultTasks 'clean', 'build-extension' +plugins { + id 'java' + id 'wrapper' +} + +group 'com.iqnox' +version '1.0-SNAPSHOT' +defaultTasks 'clean', 'packageExtension' project.sourceCompatibility = 1.8 project.targetCompatibility = 1.8 // set the properties accordingly project.ext { + incrementVersionNumber = true extensionJar = "thingworx-sftp-extension.jar" // name of the jar baseDir = projectDir common = 'common' - uiDir = "${baseDir}/ui" // if there are any widgets - localJarDir = "${baseDir}/lib/local" // if you have any jars add them here - srcDir = "${baseDir}/src/main" // where are the sources located + uiDir = "${baseDir}/ui" // if there are any widgets + localJarDir = "${baseDir}/lib/local" // if you have any jars add them here + srcDir = "${baseDir}/src/main" // where are the sources located buildDir = "${baseDir}/build" // where is the build saved configDir = "${baseDir}/configfiles" // folder location of the metadata.xml file + entitiesDir = "${baseDir}/configfiles/Entities" // folder location of the metadata.xml file zipDir = "${baseDir}/zip" // where to store the generated zip - thingworxSdkDir = "${baseDir}/lib/common" // where the thingworx sdk is located - packageVendor = "ThingWorx Customer Service" + thingworxSdkDir = "${baseDir}/lib/twxSdk" // where the thingworx sdk is located + packageVendor = "IQNOX" packageName = "SftpExtension" packageTitle = "SftpExtension" packageVersion = version + thingworxServerRoot = "http://Administrator:Administrator12345@localhost:8016" } repositories { mavenCentral() - jcenter() - maven { - url "${artifactory_contextUrl}/${artifactory_resolve_repokey}" - credentials { - username = "${artifactory_user}" - password = "${artifactory_password}" - } - } flatDir { dirs project.ext.thingworxSdkDir @@ -60,43 +70,32 @@ clean.doFirst { configurations { packageDependencies - compile { + implementation { extendsFrom packageDependencies } - thingworxsdk } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.11' - // add all the dependencies for the extension using the packageDependencies configuration. Here only one is added - packageDependencies 'com.jcraft:jsch:0.1.53' + testImplementation group: 'junit', name: 'junit', version: '4.11' - // the zip version - thingworxsdk group: 'com.thingworx', name: 'Thingworx-Extension-SDK', version: '6.5.2-b463', ext: 'zip' - compile fileTree(dir: project.ext.thingworxSdkDir, include: ['*.jar']) + // import the statically defined jar files, and the jars in the thingworx sdk + implementation fileTree(dir: project.ext.thingworxSdkDir, include: ['*.jar']) packageDependencies fileTree(dir: project.ext.localJarDir, include: ['*.jar']) -} -task extractTwxSdk(type: Copy) { - from { - configurations.thingworxsdk.collect { zipTree(it) } - } - into project.ext.thingworxSdkDir -} + // add all the dependencies for the extension using the packageDependencies configuration. + // use the implementation for jars that always exist at runtime + packageDependencies 'com.jcraft:jsch:0.1.55' -gradle.projectsEvaluated { - compileJava.dependsOn(extractTwxSdk) } jar { - archiveName = project.ext.extensionJar + archiveFileName = project.ext.extensionJar manifest { - attributes(["Built-By" : project.ext.packageVendor, - "Build-Date": new Date().format("yyyy-MM-dd HH:mm:ss")]) - attributes(["Package-Title" : project.ext.packageTitle, - "Package-Version": project.ext.packageVersion, - "Package-Vendor" : project.ext.packageVendor], project.ext.packageName - ) + attributes "Built-By" : project.ext.packageVendor + attributes "Build-Date": new Date().format("yyyy-MM-dd HH:mm:ss") + attributes "Package-Title" : project.ext.packageTitle + attributes "Package-Version": project.ext.packageVersion + attributes "Package-Vendor" : project.ext.packageVendor } } @@ -109,6 +108,9 @@ def addDependenciesInMetadata() { [type: "JAR", file: project.ext.extensionJar] ) for (File f : configurations.packageDependencies) { + if (shouldExcludeFile(f.getName())) { + continue; + } xml.ExtensionPackages.ExtensionPackage.JarResources[0]?.appendNode( "FileResource", [type: "JAR", file: f.getName()] @@ -119,14 +121,49 @@ def addDependenciesInMetadata() { pw.close() } +private boolean shouldExcludeFile(String fileName) { + fileName.startsWith("commons-codec") || + fileName.startsWith("commons-io") || + fileName.startsWith("commons-lang") || + fileName.startsWith("commons-logging") || + fileName.startsWith("commons-compress") || + fileName.startsWith("commons-collections4") || + fileName.startsWith("bcprov") || + fileName.startsWith("netty") || + fileName.startsWith("gson") || + fileName.startsWith("okhttp") || + fileName.startsWith("okio") || + fileName.startsWith("retrofit") || + fileName.startsWith("jackson") || + fileName.startsWith("jaxen") || + fileName.startsWith("jdom") || + fileName.startsWith("joda") || + fileName.startsWith("log4j") || + fileName.startsWith("logback") || + fileName.startsWith("httpclient") || + fileName.startsWith("httpcore") || + fileName.startsWith("slf4j") || + fileName.startsWith("thingworx") || + fileName.startsWith("oauth2-oidc-sdk") || + fileName.startsWith("guava") || + fileName.startsWith("nimbus-jose-jwt") || + fileName.startsWith("json-smart") || + fileName.startsWith("error_prone_annotations") || + fileName.startsWith("checker-qual") +} + task prepPackage(dependsOn: jar) { + if (project.ext.incrementVersionNumber) + increaseVersionNumber() doLast { delete project.ext.zipDir delete "${buildDir}/zip/" // add here all the jars from the packageDependencies configuration copy { - from configurations.packageDependencies + from configurations.packageDependencies { + exclude {FileTreeElement details -> shouldExcludeFile(details.file.name)} + } into "${buildDir}/zip/lib/common/" } // add the configuration @@ -143,13 +180,66 @@ task prepPackage(dependsOn: jar) { // add the ui files copy { from uiDir - into "${buildDir}/zip/ui/common/" + into "${buildDir}/zip/ui/" } } } -task packageExtension(type: Zip, dependsOn: prepPackage, overwrite: true) { - archiveName = "${project.name}.zip" - destinationDir = new File(project.ext.zipDir) + +tasks.register('packageExtension', Zip) { + dependsOn(prepPackage) + archiveFileName = "${project.name}.zip" + destinationDirectory = new File(project.ext.zipDir) from "${buildDir}/zip/" -} \ No newline at end of file +} + + +def increaseVersionNumber() { + def file = "${configDir}/metadata.xml" + def parser = new groovy.util.XmlParser(false, true); + def xml = parser.parse(file) + + def currentVersion = xml.ExtensionPackages.ExtensionPackage.@packageVersion[0]; + + def versionComponents = currentVersion.split('\\.'); + + def minorVersion = ++Integer.parseInt(versionComponents[versionComponents.length - 1]); + + versionComponents[versionComponents.length - 1] = String.valueOf(minorVersion); + + xml.ExtensionPackages.ExtensionPackage.@packageVersion = String.join('.', versionComponents); + // xml.ExtensionPackages.ExtensionPackage.get(0).attributes().put('packageVersion', String.join(',', versionComponents)); + + println 'Updated to version ' + String.join('.', versionComponents) + println xml.ExtensionPackages.ExtensionPackage.@packageVersion[0]; + + PrintWriter pw = new PrintWriter(new File(file)) + pw.write(groovy.xml.XmlUtil.serialize(xml)) + pw.close() +} + +task upload(dependsOn: packageExtension) { + doLast { + def http = new HTTPBuilder("${project.ext.thingworxServerRoot}/Thingworx/") + + def extZip = file("${project.ext.zipDir}/${project.name}.zip") + + http.request(POST) { req -> + uri.path = 'ExtensionPackageUploader' + uri.query = ['purpose': 'import'] + headers."X-XSRF-TOKEN" = "TWX-XSRF-TOKEN-VALUE" + requestContentType = 'multipart/form-data' + MultipartEntityBuilder entity = MultipartEntityBuilder.create().setLaxMode() + entity.addBinaryBody('file', extZip) + req.setEntity(entity.build()) + response.success = { resp -> + println("Upload successful!") + } + response.failure = { resp -> + println(resp.statusLine) + throw new StopExecutionException("Thingworx upload failed! See server response above") + } + } + } +} + diff --git a/configfiles/metadata.xml b/configfiles/metadata.xml index 3c84ccb..760a244 100644 --- a/configfiles/metadata.xml +++ b/configfiles/metadata.xml @@ -1,24 +1,29 @@ - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index 4c86e8d..0000000 --- a/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -artifactory_contextUrl=http://twxcisvr.thingworx.com:8082/artifactory -artifactory_resolve_repokey=twxlibs-release-local -artifactory_user=prtnreng -artifactory_password=flUrd3Ul diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 0000000..943f0cb 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 100755 index 0000000..bdc9a83 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100644 index 91a7e26..0000000 --- a/gradlew +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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 -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# 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\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - -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" ] ; 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"` - - # 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 - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 8a0b282..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@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 - -@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= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@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 Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -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/src/main/java/com/thingworx/extensions/sftpExtension/SftpRepositoryThing.java b/src/main/java/com/thingworx/extensions/sftpExtension/SftpRepositoryThing.java index fc656d7..b5d73d5 100644 --- a/src/main/java/com/thingworx/extensions/sftpExtension/SftpRepositoryThing.java +++ b/src/main/java/com/thingworx/extensions/sftpExtension/SftpRepositoryThing.java @@ -2,11 +2,11 @@ import ch.qos.logback.classic.Logger; -import com.thingworx.common.utils.StringUtilities; import com.thingworx.data.util.InfoTableInstanceFactory; import com.thingworx.entities.utils.ThingUtilities; import com.thingworx.logging.LogUtilities; import com.thingworx.metadata.annotations.*; +import com.thingworx.system.ContextType; import com.thingworx.things.Thing; import com.thingworx.things.repository.FileRepositoryThing; import com.thingworx.types.InfoTable; @@ -103,10 +103,11 @@ )} ) public class SftpRepositoryThing extends Thing { - private static Logger LOGGER = LogUtilities.getInstance().getApplicationLogger(SftpRepositoryThing.class); - + private static final Logger LOGGER = LogUtilities.getInstance().getApplicationLogger(SftpRepositoryThing.class); + private static final String CONNECTION_SETTINGS_TABLE = "ConnectionInfo"; + private static final String KEY_BASED_SETTINGS_TABLE = "Keybasedauth"; private ManagedSftpFileRepository repository; - private SftpConfiguration config = new SftpConfiguration(); + private final SftpConfiguration config = new SftpConfiguration(); public static InfoTable convertToInfotable(Collection files) throws Exception { InfoTable messagesInfoTable = InfoTableInstanceFactory.createInfoTableFromDataShape("FileSystemFile"); @@ -124,15 +125,16 @@ public static InfoTable convertToInfotable(Collection files) thr } @Override - protected void initializeThing() throws Exception { + protected void initializeThing(ContextType contextType) throws Exception { + super.initializeThing(contextType); // get values from the configuration table - config.setHost((String) this.getConfigurationData().getValue("ConnectionInfo", "host")); - config.setPort((Integer) this.getConfigurationData().getValue("ConnectionInfo", "port")); - config.setPassphrase((String) this.getConfigurationData().getValue("Keybasedauth", "passphrase")); - config.setPassword((String) this.getConfigurationData().getValue("ConnectionInfo", "password")); - String privateKeyFile = (String) this.getConfigurationData().getValue("Keybasedauth", "privateKey"); - String fileRepo = (String) this.getConfigurationData().getValue("Keybasedauth", "repository"); - if (StringUtilities.isNonEmpty(fileRepo)) { + config.setHost(this.getStringConfigurationSetting(CONNECTION_SETTINGS_TABLE, "host")); + config.setPort((Integer) this.getConfigurationSetting(CONNECTION_SETTINGS_TABLE, "port")); + config.setPassphrase(this.getStringConfigurationSetting(KEY_BASED_SETTINGS_TABLE, "passphrase")); + config.setPassword(this.getStringConfigurationSetting(CONNECTION_SETTINGS_TABLE, "password")); + String privateKeyFile = this.getStringConfigurationSetting(KEY_BASED_SETTINGS_TABLE, "privateKey"); + String fileRepo = this.getStringConfigurationSetting(KEY_BASED_SETTINGS_TABLE, "repository"); + if (fileRepo!=null && !fileRepo.isEmpty()) { try { Thing repoThing = ThingUtilities.findThing(fileRepo); config.setPrivateKey(((FileRepositoryThing) repoThing).LoadText(privateKeyFile)); @@ -140,9 +142,9 @@ protected void initializeThing() throws Exception { LOGGER.warn("Cannot load the private key file", ex); } } - config.setUsername((String) this.getConfigurationData().getValue("ConnectionInfo", "username")); - config.setConnectionTimeout((Integer) this.getConfigurationData().getValue("ConnectionInfo", "connectionTimeout")); - config.setKeepAliveTimeout((Integer) this.getConfigurationData().getValue("ConnectionInfo", "keepAliveTimeout")); + config.setUsername(this.getStringConfigurationSetting(CONNECTION_SETTINGS_TABLE, "username")); + config.setConnectionTimeout((Integer) this.getConfigurationSetting(CONNECTION_SETTINGS_TABLE, "connectionTimeout")); + config.setKeepAliveTimeout((Integer) this.getConfigurationSetting(CONNECTION_SETTINGS_TABLE, "keepAliveTimeout")); repository = new ManagedSftpFileRepository(config); } diff --git a/src/main/java/com/thingworx/extensions/sftpExtension/jsch/SftpFileRepositoryImpl.java b/src/main/java/com/thingworx/extensions/sftpExtension/jsch/SftpFileRepositoryImpl.java index f416013..e782cc9 100644 --- a/src/main/java/com/thingworx/extensions/sftpExtension/jsch/SftpFileRepositoryImpl.java +++ b/src/main/java/com/thingworx/extensions/sftpExtension/jsch/SftpFileRepositoryImpl.java @@ -2,7 +2,6 @@ import ch.qos.logback.classic.Logger; import com.jcraft.jsch.*; -import com.thingworx.common.utils.StringUtilities; import com.thingworx.extensions.sftpExtension.*; import com.thingworx.extensions.sftpExtension.SftpException; import com.thingworx.logging.LogUtilities; @@ -20,7 +19,7 @@ * A implementation of the SftpRepository based on the Jsch library */ public class SftpFileRepositoryImpl implements SftpRepository { - private static Logger LOGGER = LogUtilities.getInstance().getApplicationLogger(SftpRepositoryThing.class); + private static final Logger LOGGER = LogUtilities.getInstance().getApplicationLogger(SftpRepositoryThing.class); private final Session session; private final ChannelSftp channel; @@ -30,7 +29,7 @@ public SftpFileRepositoryImpl(SftpConfiguration config) throws SftpException { try { JSch jSch = new JSch(); // attempt to load the private key - if (StringUtilities.isNonEmpty(config.getPrivateKey())) { + if (config.getPrivateKey() != null && !"".equals(config.getPassphrase())) { // get the passphrase as a byte array byte[] passphraseBytes = config.getPassphrase() != null ? config.getPassphrase().getBytes() : null; // the private key as a byte array