embulk-input-salesforce_bulk 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a2821fcc5df5becf61f94ffc728e98d2948eb7d1
4
+ data.tar.gz: 202a4322acaf781ef7ffb453afa024615c325a8b
5
+ SHA512:
6
+ metadata.gz: e805860e45473aa27f0917365580579cadddc763d4ad7dd59fa7ee95779888f0cd4c935de9ce016e8bf1963f715640b819d6aff3de766c0ba9fdd7f925a1b627
7
+ data.tar.gz: d33ca8863e05fbe41227949238c0d6c8c756fe9c8625777909f0f0529b37e5cb1449e5f14b53b43601630e0b878834c6fa371138e29d5238d449df4dc1221091
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ *~
2
+ /pkg/
3
+ /tmp/
4
+ *.gemspec
5
+ .gradle/
6
+ /classpath/
7
+ build/
8
+ .idea
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+
2
+ MIT License
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining
5
+ a copy of this software and associated documentation files (the
6
+ "Software"), to deal in the Software without restriction, including
7
+ without limitation the rights to use, copy, modify, merge, publish,
8
+ distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so, subject to
10
+ the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # Salesforce Bulk input plugin for Embulk
2
+
3
+ Salesforce Bulk API の一括クエリ結果を取得します。
4
+
5
+ ## Overview
6
+
7
+ * **Plugin type**: input
8
+ * **Resume supported**: no
9
+ * **Cleanup supported**: no
10
+ * **Guess supported**: no
11
+
12
+ ## Configuration
13
+
14
+ - **userName**: Salesforce user name.(string, required)
15
+ - **password**: Salesforce password.(string, required)
16
+ - **authEndpointUrl**: Salesforce login endpoint URL.(string, required)
17
+ - **objectType**: object type of JobInfo.(string, required)
18
+ - **pollingIntervalMillisecond**: polling interval millisecond.(string, default is 30000)
19
+ - **querySelectFrom**: part of query. SELECT and FROM.(string, required)
20
+ - **queryWhere**: part of query. WHERE.(string, default is "")
21
+ - **queryOrder**: part of query. ORDER BY.(string, default is "")
22
+ - **columns**: schema config.(SchemaConfig, required)
23
+ - **startRowMarkerName**: 開始レコードを特定するための目印とするカラム名を指定する.(String, default is null)
24
+ - **start_row_marker**: 抽出条件に、『カラム「startRowMarkerName」がこの値よりも大きい』を追加する.(string, default is null)
25
+ - **queryAll**: if true, uses the queryAll operation so that deleted records are returned.(boolean, default is false)
26
+
27
+ ## Example
28
+
29
+ ### query で指定したものをすべて抽出
30
+
31
+ ```yaml
32
+ in:
33
+ type: salesforce_bulk
34
+ userName: USER_NAME
35
+ password: PASSWORD
36
+ authEndpointUrl: https://login.salesforce.com/services/Soap/u/39.0
37
+ objectType: Account
38
+ pollingIntervalMillisecond: 5000
39
+ querySelectFrom: SELECT Id,Name,LastModifiedDate FROM Account
40
+ queryWhere: Name like 'Test%'
41
+ queryOrder: Name desc
42
+ columns:
43
+ - {type: string, name: Id}
44
+ - {type: string, name: Name}
45
+ - {type: timestamp, name: LastModifiedDate, format: '%FT%T.%L%Z'}
46
+ ```
47
+
48
+ ### 前回取得時点から変更があったオブジェクトのみ取得
49
+
50
+ startRowMarkerName に LastModifiedDate を指定したうえで、
51
+ -o オプションを指定して embulk を実行する。
52
+
53
+ #### config.yaml
54
+
55
+ ```yaml
56
+ in:
57
+ type: salesforce_bulk
58
+ userName: USER_NAME
59
+ password: PASSWORD
60
+ authEndpointUrl: https://login.salesforce.com/services/Soap/u/39.0
61
+ objectType: Account
62
+ pollingIntervalMillisecond: 5000
63
+ querySelectFrom: SELECT Id,Name,LastModifiedDate FROM Account
64
+ queryOrder: Name desc
65
+ columns:
66
+ - {type: string, name: Id}
67
+ - {type: string, name: Name}
68
+ - {type: timestamp, name: LastModifiedDate, format: '%FT%T.%L%Z'}
69
+ startRowMarkerName: LastModifiedDate
70
+ ```
71
+
72
+ #### 実行コマンド
73
+
74
+ ```sh
75
+ embulk run config.yaml -o config.yaml
76
+ ```
77
+
78
+ ## TODO
79
+
80
+ - エラーログ出力を真面目にやる
81
+ - guess 対応
82
+ - 効率化
83
+
84
+ ## Build
85
+
86
+ ```
87
+ $ ./gradlew gem
88
+ ```
data/build.gradle ADDED
@@ -0,0 +1,86 @@
1
+ plugins {
2
+ id "com.jfrog.bintray" version "1.1"
3
+ id "com.github.jruby-gradle.base" version "1.5.0"
4
+ id "java"
5
+ id "eclipse"
6
+ }
7
+ import com.github.jrubygradle.JRubyExec
8
+ repositories {
9
+ mavenCentral()
10
+ jcenter()
11
+ }
12
+ configurations {
13
+ provided
14
+ }
15
+
16
+ version = "0.2.0"
17
+ [compileJava, compileTestJava]*.options*.encoding = "UTF-8"
18
+
19
+ dependencies {
20
+ compile 'com.force.api:force-wsc:39.+'
21
+ compile 'com.force.api:force-partner-api:39.+'
22
+ compile "org.embulk:embulk-core:0.8.14"
23
+ provided "org.embulk:embulk-core:0.8.14"
24
+ testCompile "junit:junit:4.+"
25
+ testCompile "org.hamcrest:hamcrest-all:1.+"
26
+ }
27
+
28
+ sourceSets {
29
+ test {
30
+ resources {
31
+ srcDir "src/test/resource"
32
+ }
33
+ }
34
+ }
35
+
36
+ task classpath(type: Copy, dependsOn: ["jar"]) {
37
+ doFirst { file("classpath").deleteDir() }
38
+ from (configurations.runtime - configurations.provided + files(jar.archivePath))
39
+ into "classpath"
40
+ }
41
+ clean { delete "classpath" }
42
+
43
+ task gem(type: JRubyExec, dependsOn: ["gemspec", "classpath"]) {
44
+ jrubyArgs "-S"
45
+ script "gem"
46
+ scriptArgs "build", "${project.name}.gemspec"
47
+ doLast { ant.move(file: "${project.name}-${project.version}.gem", todir: "pkg") }
48
+ }
49
+
50
+ task gemPush(type: JRubyExec, dependsOn: ["gem"]) {
51
+ jrubyArgs "-S"
52
+ script "gem"
53
+ scriptArgs "push", "pkg/${project.name}-${project.version}.gem"
54
+ }
55
+
56
+ task "package"(dependsOn: ["gemspec", "classpath"]) << {
57
+ println "> Build succeeded."
58
+ println "> You can run embulk with '-L ${file(".").absolutePath}' argument."
59
+ }
60
+
61
+ task gemspec {
62
+ ext.gemspecFile = file("${project.name}.gemspec")
63
+ inputs.file "build.gradle"
64
+ outputs.file gemspecFile
65
+ doLast { gemspecFile.write($/
66
+ Gem::Specification.new do |spec|
67
+ spec.name = "${project.name}"
68
+ spec.version = "${project.version}"
69
+ spec.authors = ["mikoto2000"]
70
+ spec.summary = %[Salesforce Bulk input plugin for Embulk]
71
+ spec.description = %[Loads records from Salesforce Bulk.]
72
+ spec.email = ["mikoto2000@gmail.com"]
73
+ spec.licenses = ["MIT"]
74
+ spec.homepage = "https://github.com/mikoto2000/embulk-input-salesforce_bulk"
75
+
76
+ spec.files = `git ls-files`.split("\n") + Dir["classpath/*.jar"]
77
+ spec.test_files = spec.files.grep(%r"^(test|spec)/")
78
+ spec.require_paths = ["lib"]
79
+
80
+ spec.add_development_dependency 'bundler', ['~> 1.0']
81
+ spec.add_development_dependency 'rake', ['>= 10.0']
82
+ end
83
+ /$)
84
+ }
85
+ }
86
+ clean { delete "${project.name}.gemspec" }
Binary file
@@ -0,0 +1,6 @@
1
+ #Tue Aug 11 00:26:20 PDT 2015
2
+ distributionBase=GRADLE_USER_HOME
3
+ distributionPath=wrapper/dists
4
+ zipStoreBase=GRADLE_USER_HOME
5
+ zipStorePath=wrapper/dists
6
+ distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip
data/gradlew ADDED
@@ -0,0 +1,164 @@
1
+ #!/usr/bin/env bash
2
+
3
+ ##############################################################################
4
+ ##
5
+ ## Gradle start up script for UN*X
6
+ ##
7
+ ##############################################################################
8
+
9
+ # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10
+ DEFAULT_JVM_OPTS=""
11
+
12
+ APP_NAME="Gradle"
13
+ APP_BASE_NAME=`basename "$0"`
14
+
15
+ # Use the maximum available, or set MAX_FD != -1 to use that value.
16
+ MAX_FD="maximum"
17
+
18
+ warn ( ) {
19
+ echo "$*"
20
+ }
21
+
22
+ die ( ) {
23
+ echo
24
+ echo "$*"
25
+ echo
26
+ exit 1
27
+ }
28
+
29
+ # OS specific support (must be 'true' or 'false').
30
+ cygwin=false
31
+ msys=false
32
+ darwin=false
33
+ case "`uname`" in
34
+ CYGWIN* )
35
+ cygwin=true
36
+ ;;
37
+ Darwin* )
38
+ darwin=true
39
+ ;;
40
+ MINGW* )
41
+ msys=true
42
+ ;;
43
+ esac
44
+
45
+ # For Cygwin, ensure paths are in UNIX format before anything is touched.
46
+ if $cygwin ; then
47
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48
+ fi
49
+
50
+ # Attempt to set APP_HOME
51
+ # Resolve links: $0 may be a link
52
+ PRG="$0"
53
+ # Need this for relative symlinks.
54
+ while [ -h "$PRG" ] ; do
55
+ ls=`ls -ld "$PRG"`
56
+ link=`expr "$ls" : '.*-> \(.*\)$'`
57
+ if expr "$link" : '/.*' > /dev/null; then
58
+ PRG="$link"
59
+ else
60
+ PRG=`dirname "$PRG"`"/$link"
61
+ fi
62
+ done
63
+ SAVED="`pwd`"
64
+ cd "`dirname \"$PRG\"`/" >&-
65
+ APP_HOME="`pwd -P`"
66
+ cd "$SAVED" >&-
67
+
68
+ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69
+
70
+ # Determine the Java command to use to start the JVM.
71
+ if [ -n "$JAVA_HOME" ] ; then
72
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73
+ # IBM's JDK on AIX uses strange locations for the executables
74
+ JAVACMD="$JAVA_HOME/jre/sh/java"
75
+ else
76
+ JAVACMD="$JAVA_HOME/bin/java"
77
+ fi
78
+ if [ ! -x "$JAVACMD" ] ; then
79
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80
+
81
+ Please set the JAVA_HOME variable in your environment to match the
82
+ location of your Java installation."
83
+ fi
84
+ else
85
+ JAVACMD="java"
86
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87
+
88
+ Please set the JAVA_HOME variable in your environment to match the
89
+ location of your Java installation."
90
+ fi
91
+
92
+ # Increase the maximum file descriptors if we can.
93
+ if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94
+ MAX_FD_LIMIT=`ulimit -H -n`
95
+ if [ $? -eq 0 ] ; then
96
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97
+ MAX_FD="$MAX_FD_LIMIT"
98
+ fi
99
+ ulimit -n $MAX_FD
100
+ if [ $? -ne 0 ] ; then
101
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
102
+ fi
103
+ else
104
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105
+ fi
106
+ fi
107
+
108
+ # For Darwin, add options to specify how the application appears in the dock
109
+ if $darwin; then
110
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111
+ fi
112
+
113
+ # For Cygwin, switch paths to Windows format before running java
114
+ if $cygwin ; then
115
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117
+
118
+ # We build the pattern for arguments to be converted via cygpath
119
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120
+ SEP=""
121
+ for dir in $ROOTDIRSRAW ; do
122
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
123
+ SEP="|"
124
+ done
125
+ OURCYGPATTERN="(^($ROOTDIRS))"
126
+ # Add a user-defined pattern to the cygpath arguments
127
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129
+ fi
130
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
131
+ i=0
132
+ for arg in "$@" ; do
133
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135
+
136
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138
+ else
139
+ eval `echo args$i`="\"$arg\""
140
+ fi
141
+ i=$((i+1))
142
+ done
143
+ case $i in
144
+ (0) set -- ;;
145
+ (1) set -- "$args0" ;;
146
+ (2) set -- "$args0" "$args1" ;;
147
+ (3) set -- "$args0" "$args1" "$args2" ;;
148
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154
+ esac
155
+ fi
156
+
157
+ # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158
+ function splitJvmOpts() {
159
+ JVM_OPTS=("$@")
160
+ }
161
+ eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162
+ JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163
+
164
+ exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
data/gradlew.bat ADDED
@@ -0,0 +1,90 @@
1
+ @if "%DEBUG%" == "" @echo off
2
+ @rem ##########################################################################
3
+ @rem
4
+ @rem Gradle startup script for Windows
5
+ @rem
6
+ @rem ##########################################################################
7
+
8
+ @rem Set local scope for the variables with windows NT shell
9
+ if "%OS%"=="Windows_NT" setlocal
10
+
11
+ @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12
+ set DEFAULT_JVM_OPTS=
13
+
14
+ set DIRNAME=%~dp0
15
+ if "%DIRNAME%" == "" set DIRNAME=.
16
+ set APP_BASE_NAME=%~n0
17
+ set APP_HOME=%DIRNAME%
18
+
19
+ @rem Find java.exe
20
+ if defined JAVA_HOME goto findJavaFromJavaHome
21
+
22
+ set JAVA_EXE=java.exe
23
+ %JAVA_EXE% -version >NUL 2>&1
24
+ if "%ERRORLEVEL%" == "0" goto init
25
+
26
+ echo.
27
+ echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28
+ echo.
29
+ echo Please set the JAVA_HOME variable in your environment to match the
30
+ echo location of your Java installation.
31
+
32
+ goto fail
33
+
34
+ :findJavaFromJavaHome
35
+ set JAVA_HOME=%JAVA_HOME:"=%
36
+ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37
+
38
+ if exist "%JAVA_EXE%" goto init
39
+
40
+ echo.
41
+ echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42
+ echo.
43
+ echo Please set the JAVA_HOME variable in your environment to match the
44
+ echo location of your Java installation.
45
+
46
+ goto fail
47
+
48
+ :init
49
+ @rem Get command-line arguments, handling Windowz variants
50
+
51
+ if not "%OS%" == "Windows_NT" goto win9xME_args
52
+ if "%@eval[2+2]" == "4" goto 4NT_args
53
+
54
+ :win9xME_args
55
+ @rem Slurp the command line arguments.
56
+ set CMD_LINE_ARGS=
57
+ set _SKIP=2
58
+
59
+ :win9xME_args_slurp
60
+ if "x%~1" == "x" goto execute
61
+
62
+ set CMD_LINE_ARGS=%*
63
+ goto execute
64
+
65
+ :4NT_args
66
+ @rem Get arguments from the 4NT Shell from JP Software
67
+ set CMD_LINE_ARGS=%$
68
+
69
+ :execute
70
+ @rem Setup the command line
71
+
72
+ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73
+
74
+ @rem Execute Gradle
75
+ "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76
+
77
+ :end
78
+ @rem End local scope for the variables with windows NT shell
79
+ if "%ERRORLEVEL%"=="0" goto mainEnd
80
+
81
+ :fail
82
+ rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83
+ rem the _cmd.exe /c_ return code!
84
+ if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85
+ exit /b 1
86
+
87
+ :mainEnd
88
+ if "%OS%"=="Windows_NT" endlocal
89
+
90
+ :omega
@@ -0,0 +1,3 @@
1
+ Embulk::JavaPlugin.register_input(
2
+ "salesforce_bulk", "org.embulk.input.salesforce_bulk.SalesforceBulkInputPlugin",
3
+ File.expand_path('../../../../classpath', __FILE__))
@@ -0,0 +1,339 @@
1
+ package org.embulk.input.salesforce_bulk;
2
+
3
+ import com.google.common.base.Optional;
4
+ import com.sforce.async.AsyncApiException;
5
+ import com.sforce.ws.ConnectionException;
6
+
7
+ import java.io.IOException;
8
+ import java.time.ZonedDateTime;
9
+ import java.time.format.DateTimeFormatter;
10
+ import java.time.temporal.TemporalField;
11
+ import java.util.Comparator;
12
+ import java.util.Date;
13
+ import java.util.List;
14
+ import java.util.Map;
15
+
16
+ import org.embulk.config.TaskReport;
17
+ import org.embulk.config.Config;
18
+ import org.embulk.config.ConfigDefault;
19
+ import org.embulk.config.ConfigDiff;
20
+ import org.embulk.config.ConfigInject;
21
+ import org.embulk.config.ConfigSource;
22
+ import org.embulk.config.Task;
23
+ import org.embulk.config.TaskSource;
24
+ import org.embulk.spi.BufferAllocator;
25
+ import org.embulk.spi.Column;
26
+ import org.embulk.spi.ColumnConfig;
27
+ import org.embulk.spi.ColumnVisitor;
28
+ import org.embulk.spi.Exec;
29
+ import org.embulk.spi.InputPlugin;
30
+ import org.embulk.spi.PageBuilder;
31
+ import org.embulk.spi.PageOutput;
32
+ import org.embulk.spi.Schema;
33
+ import org.embulk.spi.SchemaConfig;
34
+ import org.embulk.spi.time.Timestamp;
35
+ import org.embulk.spi.time.TimestampParseException;
36
+ import org.embulk.spi.time.TimestampParser;
37
+ import org.embulk.spi.util.Timestamps;
38
+ import org.slf4j.Logger;
39
+
40
+ import org.slf4j.Logger;
41
+
42
+ public class SalesforceBulkInputPlugin
43
+ implements InputPlugin
44
+ {
45
+ public interface PluginTask
46
+ extends Task, TimestampParser.Task
47
+ {
48
+ // 認証用エンドポイントURL
49
+ @Config("authEndpointUrl")
50
+ @ConfigDefault("\"https://login.salesforce.com/services/Soap/u/39.0\"")
51
+ public String getAuthEndpointUrl();
52
+
53
+ // ユーザー名
54
+ @Config("userName")
55
+ public String getUserName();
56
+
57
+ // パスワード
58
+ @Config("password")
59
+ public String getPassword();
60
+
61
+ // オブジェクトタイプ
62
+ @Config("objectType")
63
+ public String getObjectType();
64
+
65
+ // SOQL クエリ文字列 SELECT, FROM
66
+ @Config("querySelectFrom")
67
+ public String getQuerySelectFrom();
68
+
69
+ // SOQL クエリ文字列 WHERE
70
+ @Config("queryWhere")
71
+ @ConfigDefault("null")
72
+ public Optional<String> getQueryWhere();
73
+
74
+ // SOQL クエリ文字列 ORDER BY
75
+ @Config("queryOrder")
76
+ @ConfigDefault("null")
77
+ public Optional<String> getQueryOrder();
78
+
79
+ // 圧縮設定
80
+ @Config("isCompression")
81
+ @ConfigDefault("true")
82
+ public Boolean getCompression();
83
+
84
+ // ポーリング間隔(ミリ秒)
85
+ @Config("pollingIntervalMillisecond")
86
+ @ConfigDefault("30000")
87
+ public int getPollingIntervalMillisecond();
88
+
89
+ // スキーマ情報
90
+ @Config("columns")
91
+ public SchemaConfig getColumns();
92
+
93
+ // next config のための最終レコード判定用カラム名
94
+ @Config("startRowMarkerName")
95
+ @ConfigDefault("null")
96
+ public Optional<String> getStartRowMarkerName();
97
+
98
+ // next config のための最終レコード値
99
+ @Config("start_row_marker")
100
+ @ConfigDefault("null")
101
+ public Optional<String> getStartRowMarker();
102
+
103
+ // 謎。バッファアロケーターの実装を定義?
104
+ @ConfigInject
105
+ public BufferAllocator getBufferAllocator();
106
+
107
+ @Config("queryAll")
108
+ @ConfigDefault("false")
109
+ public Boolean getQueryAll();
110
+ }
111
+
112
+ private Logger log = Exec.getLogger(SalesforceBulkInputPlugin.class);
113
+
114
+ @Override
115
+ public ConfigDiff transaction(ConfigSource config,
116
+ InputPlugin.Control control)
117
+ {
118
+ PluginTask task = config.loadConfig(PluginTask.class);
119
+
120
+ Schema schema = task.getColumns().toSchema();
121
+ int taskCount = 1; // number of run() method calls
122
+
123
+ ConfigDiff returnConfigDiff = resume(task.dump(), schema, taskCount, control);
124
+ return returnConfigDiff;
125
+ }
126
+
127
+ @Override
128
+ public ConfigDiff resume(TaskSource taskSource,
129
+ Schema schema, int taskCount,
130
+ InputPlugin.Control control)
131
+ {
132
+ List<TaskReport> taskReportList =
133
+ control.run(taskSource, schema, taskCount);
134
+
135
+ // start_row_marker を ConfigDiff にセット
136
+ ConfigDiff configDiff = Exec.newConfigDiff();
137
+ for (TaskReport taskReport : taskReportList) {
138
+ final String label = "start_row_marker";
139
+ final String startRowMarker = taskReport.get(String.class, label, null);
140
+ if (startRowMarker != null) {
141
+ configDiff.set(label, startRowMarker);
142
+ }
143
+ }
144
+ return configDiff;
145
+ }
146
+
147
+ @Override
148
+ public void cleanup(TaskSource taskSource,
149
+ Schema schema, int taskCount,
150
+ List<TaskReport> successTaskReports)
151
+ {
152
+ }
153
+
154
+ @Override
155
+ public TaskReport run(TaskSource taskSource,
156
+ Schema schema, int taskIndex,
157
+ PageOutput output)
158
+ {
159
+ PluginTask task = taskSource.loadTask(PluginTask.class);
160
+
161
+ BufferAllocator allocator = task.getBufferAllocator();
162
+ PageBuilder pageBuilder = new PageBuilder(allocator, schema, output);
163
+
164
+ // start_row_marker 取得のための前準備
165
+ String start_row_marker = null;
166
+ TaskReport taskReport = Exec.newTaskReport();
167
+
168
+ log.info("Try login to '{}'.", task.getAuthEndpointUrl());
169
+ try (SalesforceBulkWrapper sfbw = new SalesforceBulkWrapper(
170
+ task.getUserName(),
171
+ task.getPassword(),
172
+ task.getAuthEndpointUrl(),
173
+ task.getCompression(),
174
+ task.getPollingIntervalMillisecond(),
175
+ task.getQueryAll())) {
176
+
177
+ log.info("Login success.");
178
+
179
+ // クエリの作成
180
+ String querySelectFrom = task.getQuerySelectFrom();
181
+ String queryWhere = task.getQueryWhere().or("");
182
+ String queryOrder = task.getQueryOrder().or("");
183
+ String column = task.getStartRowMarkerName().orNull();
184
+ String value = task.getStartRowMarker().orNull();
185
+
186
+ String query;
187
+ query = querySelectFrom;
188
+
189
+ if (!queryWhere.isEmpty()) {
190
+ queryWhere = " WHERE " + queryWhere;
191
+ }
192
+
193
+ if (column != null && value != null) {
194
+ if (queryWhere.isEmpty()) {
195
+ queryWhere += " WHERE ";
196
+ } else {
197
+ queryWhere += " AND ";
198
+ }
199
+
200
+ queryWhere += column + " > " + value;
201
+ }
202
+
203
+ query += queryWhere;
204
+
205
+ if (!queryOrder.isEmpty()) {
206
+ query += " ORDER BY " + queryOrder;
207
+ }
208
+
209
+ log.info("Send request : '{}'", query);
210
+
211
+ List<Map<String, String>> queryResults = sfbw.syncQuery(
212
+ task.getObjectType(), query);
213
+
214
+ for (Map<String, String> row : queryResults) {
215
+ // Visitor 作成
216
+ ColumnVisitor visitor = new ColumnVisitorImpl(row, task, pageBuilder);
217
+
218
+ // スキーマ解析
219
+ schema.visitColumns(visitor);
220
+
221
+ // 編集したレコードを追加
222
+ pageBuilder.addRecord();
223
+ }
224
+ pageBuilder.finish();
225
+
226
+ // 取得した値の最大値を start_row_marker に設定
227
+ if (column != null) {
228
+ start_row_marker = queryResults.stream()
229
+ .map(item -> item.get(column))
230
+ .max(Comparator.naturalOrder()).orElse(null);
231
+
232
+ if (start_row_marker == null) {
233
+ taskReport.set("start_row_marker", value);
234
+ } else {
235
+ taskReport.set("start_row_marker", start_row_marker);
236
+ }
237
+ }
238
+ } catch (ConnectionException|AsyncApiException|InterruptedException|IOException e) {
239
+ log.error("{}", e.getClass(), e);
240
+ }
241
+
242
+ return taskReport;
243
+ }
244
+
245
+ @Override
246
+ public ConfigDiff guess(ConfigSource config)
247
+ {
248
+ return Exec.newConfigDiff();
249
+ }
250
+
251
+ class ColumnVisitorImpl implements ColumnVisitor {
252
+ private final Map<String, String> row;
253
+ private final TimestampParser[] timestampParsers;
254
+ private final PageBuilder pageBuilder;
255
+
256
+ ColumnVisitorImpl(Map<String, String> row, PluginTask task, PageBuilder pageBuilder) {
257
+ this.row = row;
258
+ this.pageBuilder = pageBuilder;
259
+
260
+ this.timestampParsers = Timestamps.newTimestampColumnParsers(
261
+ task, task.getColumns());
262
+ }
263
+
264
+ @Override
265
+ public void booleanColumn(Column column) {
266
+ String value = row.get(column.getName());
267
+ if (value == null) {
268
+ pageBuilder.setNull(column);
269
+ } else {
270
+ pageBuilder.setBoolean(column, Boolean.parseBoolean(value));
271
+ }
272
+ }
273
+
274
+ @Override
275
+ public void longColumn(Column column) {
276
+ String value = row.get(column.getName());
277
+ if (value == null) {
278
+ pageBuilder.setNull(column);
279
+ } else {
280
+ try {
281
+ pageBuilder.setLong(column, Long.parseLong(value));
282
+ } catch (NumberFormatException e) {
283
+ log.error("NumberFormatError: Row: {}", row);
284
+ log.error("{}", e);
285
+ pageBuilder.setNull(column);
286
+ }
287
+ }
288
+ }
289
+
290
+ @Override
291
+ public void doubleColumn(Column column) {
292
+ String value = row.get(column.getName());
293
+ if (value == null) {
294
+ pageBuilder.setNull(column);
295
+ } else {
296
+ try {
297
+ pageBuilder.setDouble(column, Double.parseDouble(value));
298
+ } catch (NumberFormatException e) {
299
+ log.error("NumberFormatError: Row: {}", row);
300
+ log.error("{}", e);
301
+ pageBuilder.setNull(column);
302
+ }
303
+ }
304
+ }
305
+
306
+ @Override
307
+ public void stringColumn(Column column) {
308
+ String value = row.get(column.getName());
309
+ if (value == null) {
310
+ pageBuilder.setNull(column);
311
+ } else {
312
+ pageBuilder.setString(column, value);
313
+ }
314
+ }
315
+
316
+ @Override
317
+ public void jsonColumn(Column column) {
318
+ throw new UnsupportedOperationException("This plugin doesn't support json type. Please try to upgrade version of the plugin using 'embulk gem update' command. If the latest version still doesn't support json type, please contact plugin developers, or change configuration of input plugin not to use json type.");
319
+ }
320
+
321
+ @Override
322
+ public void timestampColumn(Column column) {
323
+ String value = row.get(column.getName());
324
+ if (value == null) {
325
+ pageBuilder.setNull(column);
326
+ } else {
327
+ try {
328
+ Timestamp timestamp = timestampParsers[column.getIndex()]
329
+ .parse(value);
330
+ pageBuilder.setTimestamp(column, timestamp);
331
+ } catch (TimestampParseException e) {
332
+ log.error("TimestampParseError: Row: {}", row);
333
+ log.error("{}", e);
334
+ pageBuilder.setNull(column);
335
+ }
336
+ }
337
+ }
338
+ }
339
+ }
@@ -0,0 +1,223 @@
1
+ package org.embulk.input.salesforce_bulk;
2
+
3
+ import java.io.ByteArrayInputStream;
4
+ import java.io.IOException;
5
+ import java.io.InputStream;
6
+
7
+ import java.util.ArrayList;
8
+ import java.util.HashMap;
9
+ import java.util.List;
10
+ import java.util.Map;
11
+
12
+ import com.sforce.async.AsyncApiException;
13
+ import com.sforce.async.AsyncExceptionCode;
14
+ import com.sforce.async.BatchInfo;
15
+ import com.sforce.async.BatchStateEnum;
16
+ import com.sforce.async.BulkConnection;
17
+ import com.sforce.async.ContentType;
18
+ import com.sforce.async.CSVReader;
19
+ import com.sforce.async.JobInfo;
20
+ import com.sforce.async.JobStateEnum;
21
+ import com.sforce.async.OperationEnum;
22
+ import com.sforce.async.QueryResultList;
23
+
24
+ import com.sforce.soap.partner.PartnerConnection;
25
+
26
+ import com.sforce.ws.ConnectionException;
27
+ import com.sforce.ws.ConnectorConfig;
28
+
29
+ /**
30
+ * SalesforceBulkWrapper.
31
+ *
32
+ * -- example:
33
+ * <pre>
34
+ * {@code
35
+ * SalesforceBulkWrapper sfbw = new SalesforceBulkWrapper(
36
+ * USER_NAME,
37
+ * PASSWORD,
38
+ * AUTH_ENDPOINT_URL,
39
+ * IS_COMPRESSION,
40
+ * POLLING_INTERVAL_MILLISECOND);
41
+ * List<Map<String, String>> results = sfbw.syncQuery(
42
+ * "Account", "SELECT Id, Name FROM Account ORDER BY Id");
43
+ * sfbw.close();
44
+ * }
45
+ * </pre>
46
+ */
47
+ public class SalesforceBulkWrapper implements AutoCloseable {
48
+
49
+ // コネクション
50
+ private PartnerConnection partnerConnection;
51
+ private BulkConnection bulkConnection;
52
+
53
+ // Bulk 接続設定
54
+ private boolean isCompression;
55
+ private int pollingIntervalMillisecond;
56
+ private boolean queryAll;
57
+
58
+ private static final String API_VERSION = "39.0";
59
+ private static final String AUTH_ENDPOINT_URL_DEFAULT =
60
+ "https://login.salesforce.com/services/Soap/u/" + API_VERSION;
61
+
62
+ private static final boolean IS_COMPRESSION_DEFAULT = true;
63
+ private static final int POLLING_INTERVAL_MILLISECOND_DEFAULT = 30000;
64
+ private static final boolean QUERY_ALL_DEFAULT = false;
65
+
66
+ /**
67
+ * Constructor
68
+ */
69
+ public SalesforceBulkWrapper(String userName, String password)
70
+ throws AsyncApiException, ConnectionException {
71
+ this(userName,
72
+ password,
73
+ AUTH_ENDPOINT_URL_DEFAULT,
74
+ IS_COMPRESSION_DEFAULT,
75
+ POLLING_INTERVAL_MILLISECOND_DEFAULT,
76
+ QUERY_ALL_DEFAULT);
77
+ }
78
+
79
+ /**
80
+ * Constructor
81
+ */
82
+ public SalesforceBulkWrapper(
83
+ String userName,
84
+ String password,
85
+ String authEndpointUrl,
86
+ boolean isCompression,
87
+ int pollingIntervalMillisecond,
88
+ boolean queryAll)
89
+ throws AsyncApiException, ConnectionException {
90
+
91
+ partnerConnection = createPartnerConnection(
92
+ authEndpointUrl,
93
+ userName,
94
+ password);
95
+ bulkConnection = createBulkConnection(partnerConnection.getConfig());
96
+
97
+ this.pollingIntervalMillisecond = pollingIntervalMillisecond;
98
+ this.queryAll = queryAll;
99
+ }
100
+
101
+ public List<Map<String, String>> syncQuery(String objectType, String query)
102
+ throws InterruptedException, AsyncApiException, IOException {
103
+
104
+ // ジョブ作成
105
+ JobInfo jobInfo = new JobInfo();
106
+ jobInfo.setObject(objectType);
107
+ if (queryAll) {
108
+ jobInfo.setOperation(OperationEnum.queryAll);
109
+ } else {
110
+ jobInfo.setOperation(OperationEnum.query);
111
+ }
112
+ jobInfo.setContentType(ContentType.CSV);
113
+ jobInfo = bulkConnection.createJob(jobInfo);
114
+
115
+ // バッチ作成
116
+ InputStream is = new ByteArrayInputStream(query.getBytes());
117
+ BatchInfo batchInfo = bulkConnection.createBatchFromStream(jobInfo, is);
118
+
119
+ // ジョブクローズ
120
+ JobInfo closeJob = new JobInfo();
121
+ closeJob.setId(jobInfo.getId());
122
+ closeJob.setState(JobStateEnum.Closed);
123
+ bulkConnection.updateJob(closeJob);
124
+
125
+ // 実行状況取得
126
+ batchInfo = waitBatch(batchInfo);
127
+ BatchStateEnum state = batchInfo.getState();
128
+
129
+ // 実行結果取得
130
+ if (state == BatchStateEnum.Completed) {
131
+ QueryResultList queryResultList =
132
+ bulkConnection.getQueryResultList(
133
+ batchInfo.getJobId(),
134
+ batchInfo.getId());
135
+ return getQueryResultMapList(batchInfo, queryResultList);
136
+ } else {
137
+ throw new AsyncApiException(batchInfo.getStateMessage(), AsyncExceptionCode.InvalidBatch);
138
+ }
139
+ }
140
+
141
+ private List<Map<String, String>> getQueryResultMapList(BatchInfo batchInfo,
142
+ QueryResultList queryResultList)
143
+ throws AsyncApiException, IOException {
144
+
145
+ List<Map<String, String>> queryResults = new ArrayList<>();
146
+
147
+ for (String queryResultId : queryResultList.getResult()) {
148
+ CSVReader rdr =
149
+ new CSVReader(bulkConnection.getQueryResultStream(
150
+ batchInfo.getJobId(),
151
+ batchInfo.getId(),
152
+ queryResultId));
153
+
154
+ // バッチ作成時の CSV 制限は今回関係ないのですべて Integer.MAX_VALUE に設定。
155
+ rdr.setMaxRowsInFile(Integer.MAX_VALUE);
156
+ rdr.setMaxCharsInFile(Integer.MAX_VALUE);
157
+
158
+ List<String> resultHeader = rdr.nextRecord();
159
+ int resultCols = resultHeader.size();
160
+
161
+ List<String> row;
162
+ while ((row = rdr.nextRecord()) != null) {
163
+ HashMap<String, String> rowMap = new HashMap<>(resultCols);
164
+ for (int i = 0; i < resultCols; i++) {
165
+ rowMap.put(resultHeader.get(i), row.get(i));
166
+ }
167
+ queryResults.add(rowMap);
168
+ }
169
+ }
170
+ return queryResults;
171
+ }
172
+
173
+ public void close() throws ConnectionException {
174
+ partnerConnection.logout();
175
+ }
176
+
177
+ private PartnerConnection createPartnerConnection(
178
+ String endpointUrl,
179
+ String userName,
180
+ String password)
181
+ throws ConnectionException {
182
+
183
+ ConnectorConfig partnerConfig = new ConnectorConfig();
184
+ partnerConfig.setUsername(userName);
185
+ partnerConfig.setPassword(password);
186
+ partnerConfig.setAuthEndpoint(endpointUrl);
187
+
188
+ return new PartnerConnection(partnerConfig);
189
+ }
190
+
191
+ private BulkConnection createBulkConnection(ConnectorConfig partnerConfig)
192
+ throws AsyncApiException {
193
+
194
+ ConnectorConfig config = new ConnectorConfig();
195
+ config.setSessionId(partnerConfig.getSessionId());
196
+
197
+ String soapEndpoint = partnerConfig.getServiceEndpoint();
198
+ String restEndpoint = soapEndpoint.substring(
199
+ 0, soapEndpoint.indexOf("Soap/")) + "async/" + API_VERSION;
200
+ config.setRestEndpoint(restEndpoint);
201
+ config.setCompression(isCompression);
202
+
203
+ config.setTraceMessage(false);
204
+
205
+ return new BulkConnection(config);
206
+ }
207
+
208
+ private BatchInfo waitBatch(BatchInfo batchInfo)
209
+ throws InterruptedException, AsyncApiException {
210
+ while(true) {
211
+ Thread.sleep(pollingIntervalMillisecond);
212
+ batchInfo = bulkConnection.getBatchInfo(
213
+ batchInfo.getJobId(),
214
+ batchInfo.getId());
215
+ BatchStateEnum state = batchInfo.getState();
216
+ if (state == BatchStateEnum.Completed ||
217
+ state == BatchStateEnum.Failed ||
218
+ state == BatchStateEnum.NotProcessed) {
219
+ return batchInfo;
220
+ }
221
+ }
222
+ }
223
+ }
@@ -0,0 +1,5 @@
1
+ package org.embulk.input.salesforce_bulk;
2
+
3
+ public class TestSalesforceBulkInputPlugin
4
+ {
5
+ }
@@ -0,0 +1,39 @@
1
+ package org.embulk.input.salesforce_bulk;
2
+
3
+ import java.util.List;
4
+ import java.util.Map;
5
+ import java.util.Properties;
6
+ import java.io.InputStream;
7
+
8
+ import com.sforce.async.QueryResultList;
9
+
10
+ import static org.junit.Assert.*;
11
+ import org.junit.Test;
12
+
13
+ /**
14
+ * TestSalesforceBulkWrapper
15
+ */
16
+ public class TestSalesforceBulkWrapper {
17
+ @Test
18
+ public void testsyncQuery() throws Exception {
19
+ // ユーザー情報をプロパティファイルから取得
20
+ Properties p = new Properties();
21
+ InputStream is = TestSalesforceBulkWrapper.class.
22
+ getResourceAsStream("/user_info.properties");
23
+ p.load(is);
24
+
25
+ String userName = p.getProperty("username", "");
26
+ String password = p.getProperty("password", "");
27
+
28
+ if (userName.equals("") || password.equals("")) {
29
+ System.exit(1);
30
+ }
31
+
32
+ SalesforceBulkWrapper sfbw = new SalesforceBulkWrapper(
33
+ userName, password);
34
+ List<Map<String, String>> queryResults = sfbw.syncQuery(
35
+ "Account", "SELECT Id, Name FROM Account ORDER BY Id");
36
+ sfbw.close();
37
+ System.out.println(queryResults);
38
+ }
39
+ }
@@ -0,0 +1,2 @@
1
+ username=USER_NAME
2
+ password=PASSWORD+TOKEN
metadata ADDED
@@ -0,0 +1,97 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: embulk-input-salesforce_bulk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - mikoto2000
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-11-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.0'
19
+ name: bundler
20
+ prerelease: false
21
+ type: :development
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.0'
27
+ - !ruby/object:Gem::Dependency
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '10.0'
33
+ name: rake
34
+ prerelease: false
35
+ type: :development
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: Loads records from Salesforce Bulk.
42
+ email:
43
+ - mikoto2000@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".gitignore"
49
+ - LICENSE.txt
50
+ - README.md
51
+ - build.gradle
52
+ - classpath/ST4-4.0.7.jar
53
+ - classpath/antlr-2.7.7.jar
54
+ - classpath/antlr-runtime-3.5.jar
55
+ - classpath/commons-beanutils-1.7.0.jar
56
+ - classpath/commons-logging-1.0.3.jar
57
+ - classpath/embulk-input-salesforce_bulk-0.2.0.jar
58
+ - classpath/force-partner-api-39.0.0.jar
59
+ - classpath/force-wsc-39.0.5.jar
60
+ - classpath/jackson-core-asl-1.9.13.jar
61
+ - classpath/jackson-mapper-asl-1.9.13.jar
62
+ - classpath/stringtemplate-3.2.1.jar
63
+ - gradle/wrapper/gradle-wrapper.jar
64
+ - gradle/wrapper/gradle-wrapper.properties
65
+ - gradlew
66
+ - gradlew.bat
67
+ - lib/embulk/input/salesforce_bulk.rb
68
+ - src/main/java/org/embulk/input/salesforce_bulk/SalesforceBulkInputPlugin.java
69
+ - src/main/java/org/embulk/input/salesforce_bulk/SalesforceBulkWrapper.java
70
+ - src/test/java/org/embulk/input/salesforce_bulk/TestSalesforceBulkInputPlugin.java
71
+ - src/test/java/org/embulk/input/salesforce_bulk/TestSalesforceBulkWrapper.java
72
+ - src/test/resource/user_info.properties
73
+ homepage: https://github.com/mikoto2000/embulk-input-salesforce_bulk
74
+ licenses:
75
+ - MIT
76
+ metadata: {}
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubyforge_project:
93
+ rubygems_version: 2.6.8
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Salesforce Bulk input plugin for Embulk
97
+ test_files: []