You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dolphinscheduler.apache.org by GitBox <gi...@apache.org> on 2022/08/14 14:27:28 UTC

[GitHub] [dolphinscheduler] ruanwenjun commented on a diff in pull request #10689: [Feature-10683][Task Plugin] Add Java Task Plugin.

ruanwenjun commented on code in PR #10689:
URL: https://github.com/apache/dolphinscheduler/pull/10689#discussion_r945295271


##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaConstants.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+public class JavaConstants {
+
+    private JavaConstants() {
+        throw new IllegalStateException("Utility class");
+    }
+
+    /**
+     * The constants used to get the Java installation directory
+     **/
+    public static final String JAVA_HOME_VAR = "${JAVA_HOME}";
+
+    /**
+     * this constant represents the use of the java command to run a task
+     **/
+    public static final String RUN_TYPE_JAVA = "JAVA";
+
+    /**
+     * this constant represents the use of the java -jar command to run a task
+     **/
+    public static final String RUN_TYPE_JAR = "JAR";
+
+    /**
+     * This constant is the Classpath or module path delimiter for different operating systems
+     **/
+    public static final String PATH_SEPARATOR = System.getProperty("path.separator");

Review Comment:
   Why you don't directly use `File.pathSeparatorChar`



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaConstants.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+public class JavaConstants {
+
+    private JavaConstants() {
+        throw new IllegalStateException("Utility class");
+    }
+
+    /**
+     * The constants used to get the Java installation directory
+     **/
+    public static final String JAVA_HOME_VAR = "${JAVA_HOME}";
+
+    /**
+     * this constant represents the use of the java command to run a task
+     **/
+    public static final String RUN_TYPE_JAVA = "JAVA";
+
+    /**
+     * this constant represents the use of the java -jar command to run a task
+     **/
+    public static final String RUN_TYPE_JAR = "JAR";
+
+    /**
+     * This constant is the Classpath or module path delimiter for different operating systems
+     **/
+    public static final String PATH_SEPARATOR = System.getProperty("path.separator");
+
+    /**
+     * This constant is the file delimiter for different operating systems
+     **/
+    public static final String FILE_SEPARATOR = System.getProperty("file.separator");

Review Comment:
   Why you don't directly use `File.separator`



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaParameters.java:
##########
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+
+import java.util.List;
+
+import lombok.Data;
+
+@Data
+public class JavaParameters extends AbstractParameters {
+    /**
+     * origin java script
+     */
+    private String rawScript;
+
+    /**
+     * run in jar file
+     */
+    private ResourceInfo mainJar;
+
+    /**
+     * Marks the current task running mode
+     */
+    private String runType;
+
+    /**
+     * main method args
+     **/
+    private String mainArgs;
+
+    /**
+     * java virtual machine args
+     **/
+    private String jvmArgs;
+
+    /**
+     * module path or class path flag
+     **/
+    private boolean isModulePath;
+
+    /**
+     * resource list
+     */
+    private List<ResourceInfo> resourceList;
+
+    /**
+     * @description: Check that the parameters are valid
+     * @param: []
+     * @return: boolean
+     **/
+    @Override
+    public boolean checkParameters() {
+        return runType != null && (rawScript != null && !rawScript.isEmpty()) || mainJar != null;

Review Comment:
   ```suggestion
           return runType != null && StringUtils.isNotEmpty(rawScript) || mainJar != null;
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");

Review Comment:
   Why you don't put this in `javaParameters.checkParameters()`



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {
+        String sourceCode = buildJavaSourceContent();
+        String className = compilerRawScript(sourceCode);
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath())
+                .append(" ")
+                .append(className).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private void setMainJarName() {
+        ResourceInfo mainJar = javaParameters.getMainJar();
+        String resourceName = getResourceNameOfMainJar(mainJar);
+        mainJar.setRes(resourceName);
+        javaParameters.setMainJar(mainJar);
+    }
+
+    /**
+     * @description: Construct a shell command for the java -jar Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJarCommand() {
+        String fullName = javaParameters.getMainJar().getResourceName();
+        String mainJarName = fullName.substring(0, fullName.lastIndexOf('.'));
+        mainJarName = mainJarName.substring(mainJarName.lastIndexOf('.') + 1) + ".jar";
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath()).append(" ")
+                .append("-jar").append(" ")
+                .append(taskRequest.getExecutePath())
+                .append(mainJarName).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private String getResourceNameOfMainJar(ResourceInfo mainJar) {
+        if (null == mainJar) {
+            throw new RuntimeException("The jar for the task is required.");
+        }
+        return mainJar.getId() == 0
+                ? mainJar.getRes()
+                // when update resource maybe has error
+                : mainJar.getResourceName().replaceFirst(SINGLE_SLASH, "");
+    }
+
+    @Override
+    public void cancelApplication(boolean cancelApplication) throws Exception {
+        // cancel process
+        shellCommandExecutor.cancelApplication();
+    }
+
+    @Override
+    public AbstractParameters getParameters() {
+        return javaParameters;
+    }
+
+    /**
+     * @description: Replaces placeholders such as local variables in source files
+     * @param: [java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected static String convertJavaSourceCodePlaceholders(String rawScript) throws StringIndexOutOfBoundsException {
+        int len = "${setShareVar(${".length();
+        int scriptStart = 0;
+        while ((scriptStart = rawScript.indexOf("${setShareVar(${", scriptStart)) != -1) {
+            int start = -1;
+            int end = rawScript.indexOf('}', scriptStart + len);
+            String prop = rawScript.substring(scriptStart + len, end);
+
+            start = rawScript.indexOf(',', end);
+            end = rawScript.indexOf(')', start);
+
+            String value = rawScript.substring(start + 1, end);
+
+            start = rawScript.indexOf('}', start) + 1;
+            end = rawScript.length();
+
+            String replaceScript = String.format("print(\"${{setValue({},{})}}\".format(\"%s\",%s))", prop, value);
+
+            rawScript = rawScript.substring(0, scriptStart) + replaceScript + rawScript.substring(start, end);
+
+            scriptStart += replaceScript.length();
+        }
+        return rawScript;
+    }
+
+    /**
+     * @description: Creates a Java source file when it does not exist
+     * @param: [java.lang.String, java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected void createJavaSourceFileIfNotExists(String sourceCode, String fileName) throws IOException {
+        logger.info("tenantCode: {}, task dir:{}", taskRequest.getTenantCode(), taskRequest.getExecutePath());
+
+        if (!Files.exists(Paths.get(fileName))) {
+            logger.info("generate java source file: {}", fileName);
+
+            StringBuilder sb = new StringBuilder();
+            sb.append(sourceCode);
+            logger.info(sb.toString());
+
+            // write data to file
+            FileUtils.writeStringToFile(new File(fileName),
+                    sb.toString(),
+                    StandardCharsets.UTF_8);

Review Comment:
   ```suggestion
               logger.info("The java source code", sourceCode);
   
               // write data to file
               FileUtils.writeStringToFile(new File(fileName),
                       sb,
                       StandardCharsets.UTF_8);
   ```
   Why do you use StringBuilder here?



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/

Review Comment:
   This kind of comment is not needed.



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {
+        String sourceCode = buildJavaSourceContent();
+        String className = compilerRawScript(sourceCode);
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath())
+                .append(" ")
+                .append(className).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private void setMainJarName() {
+        ResourceInfo mainJar = javaParameters.getMainJar();
+        String resourceName = getResourceNameOfMainJar(mainJar);
+        mainJar.setRes(resourceName);
+        javaParameters.setMainJar(mainJar);
+    }
+
+    /**
+     * @description: Construct a shell command for the java -jar Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJarCommand() {
+        String fullName = javaParameters.getMainJar().getResourceName();
+        String mainJarName = fullName.substring(0, fullName.lastIndexOf('.'));
+        mainJarName = mainJarName.substring(mainJarName.lastIndexOf('.') + 1) + ".jar";
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath()).append(" ")
+                .append("-jar").append(" ")
+                .append(taskRequest.getExecutePath())
+                .append(mainJarName).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private String getResourceNameOfMainJar(ResourceInfo mainJar) {
+        if (null == mainJar) {
+            throw new RuntimeException("The jar for the task is required.");
+        }
+        return mainJar.getId() == 0
+                ? mainJar.getRes()
+                // when update resource maybe has error
+                : mainJar.getResourceName().replaceFirst(SINGLE_SLASH, "");
+    }
+
+    @Override
+    public void cancelApplication(boolean cancelApplication) throws Exception {
+        // cancel process
+        shellCommandExecutor.cancelApplication();
+    }
+
+    @Override
+    public AbstractParameters getParameters() {
+        return javaParameters;
+    }
+
+    /**
+     * @description: Replaces placeholders such as local variables in source files
+     * @param: [java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected static String convertJavaSourceCodePlaceholders(String rawScript) throws StringIndexOutOfBoundsException {
+        int len = "${setShareVar(${".length();
+        int scriptStart = 0;
+        while ((scriptStart = rawScript.indexOf("${setShareVar(${", scriptStart)) != -1) {
+            int start = -1;
+            int end = rawScript.indexOf('}', scriptStart + len);
+            String prop = rawScript.substring(scriptStart + len, end);
+
+            start = rawScript.indexOf(',', end);
+            end = rawScript.indexOf(')', start);
+
+            String value = rawScript.substring(start + 1, end);
+
+            start = rawScript.indexOf('}', start) + 1;
+            end = rawScript.length();
+
+            String replaceScript = String.format("print(\"${{setValue({},{})}}\".format(\"%s\",%s))", prop, value);
+
+            rawScript = rawScript.substring(0, scriptStart) + replaceScript + rawScript.substring(start, end);
+
+            scriptStart += replaceScript.length();
+        }
+        return rawScript;
+    }
+
+    /**
+     * @description: Creates a Java source file when it does not exist
+     * @param: [java.lang.String, java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected void createJavaSourceFileIfNotExists(String sourceCode, String fileName) throws IOException {
+        logger.info("tenantCode: {}, task dir:{}", taskRequest.getTenantCode(), taskRequest.getExecutePath());
+
+        if (!Files.exists(Paths.get(fileName))) {
+            logger.info("generate java source file: {}", fileName);
+
+            StringBuilder sb = new StringBuilder();
+            sb.append(sourceCode);
+            logger.info(sb.toString());
+
+            // write data to file
+            FileUtils.writeStringToFile(new File(fileName),
+                    sb.toString(),
+                    StandardCharsets.UTF_8);
+        } else {
+            throw new JavaSourceFileExistException("java source file exists, please report an issue on official.");
+        }
+    }
+
+    /**
+     * @description: Construct the full path name of the Java source file from the temporary execution path of the task
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaSourceCodeFileFullName(String publicClassName) {
+        return String.format(JavaConstants.JAVA_SOURCE_CODE_NAME_TEMPLATE, taskRequest.getExecutePath(), publicClassName);
+    }
+
+    /**
+     * @description: Construct a Classpath or module path based on isModulePath
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildResourcePath() {
+        StringBuilder builder = new StringBuilder();
+        if (javaParameters.isModulePath()) {
+            builder.append("--module-path");
+        } else {
+            builder.append("--class-path");
+        }
+        builder.append(" ").append(JavaConstants.CLASSPATH_CURRENT_DIR)
+                .append(JavaConstants.PATH_SEPARATOR)
+                .append(taskRequest.getExecutePath());
+        for (ResourceInfo info : javaParameters.getResourceFilesList()) {
+            builder.append(JavaConstants.PATH_SEPARATOR);
+            builder.append(taskRequest.getExecutePath())
+                    .append(info.getResourceName());
+        }
+        return builder.toString();
+    }
+
+    /**
+     * @description: Compile the Java source file
+     * @param: [java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected String compilerRawScript(String sourceCode) throws IOException, InterruptedException {
+        String publicClassName = getPublicClassName(sourceCode);
+        String fileName =  buildJavaSourceCodeFileFullName(publicClassName);
+        createJavaSourceFileIfNotExists(sourceCode, fileName);
+        String compileCommand = buildJavaCompileCommand(fileName, sourceCode);
+        Preconditions.checkNotNull(compileCommand, "command not be null.");
+        TaskResponse compileResponse = shellCommandExecutor.run(compileCommand);
+        // must drop the command file ,if do not ,the next command will not run. because be limited the ShellCommandExecutor's create file rules
+        dropShellCommandFile();

Review Comment:
   This should be a common logic for shell task?



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {

Review Comment:
   ```suggestion
       protected @Nonnull String buildJavaCommand() throws Exception {
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */

Review Comment:
   ```suggestion
   
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;

Review Comment:
   ```suggestion
           
   ```
   This catch is not needed, if you want to print the exception, it's better to print the thread stack rather than e.getMessage.



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);

Review Comment:
   ```suggestion
               logger.error("setShareVar field format error, raw java script : {}", rawJavaScript, e);
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {
+        String sourceCode = buildJavaSourceContent();
+        String className = compilerRawScript(sourceCode);
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath())
+                .append(" ")
+                .append(className).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private void setMainJarName() {
+        ResourceInfo mainJar = javaParameters.getMainJar();
+        String resourceName = getResourceNameOfMainJar(mainJar);
+        mainJar.setRes(resourceName);
+        javaParameters.setMainJar(mainJar);
+    }
+
+    /**
+     * @description: Construct a shell command for the java -jar Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/

Review Comment:
   ```suggestion
        * @description: Construct a shell command for the java -jar Run mode
        * @return: java.lang.String
        **/
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {

Review Comment:
   ```suggestion
           if (JavaConstants.RUN_TYPE_JAR.equals(javaParameters.getRunType())) {
   ```



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {
+        String sourceCode = buildJavaSourceContent();
+        String className = compilerRawScript(sourceCode);
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath())
+                .append(" ")
+                .append(className).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private void setMainJarName() {
+        ResourceInfo mainJar = javaParameters.getMainJar();
+        String resourceName = getResourceNameOfMainJar(mainJar);
+        mainJar.setRes(resourceName);
+        javaParameters.setMainJar(mainJar);
+    }
+
+    /**
+     * @description: Construct a shell command for the java -jar Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJarCommand() {
+        String fullName = javaParameters.getMainJar().getResourceName();
+        String mainJarName = fullName.substring(0, fullName.lastIndexOf('.'));
+        mainJarName = mainJarName.substring(mainJarName.lastIndexOf('.') + 1) + ".jar";
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath()).append(" ")
+                .append("-jar").append(" ")
+                .append(taskRequest.getExecutePath())
+                .append(mainJarName).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private String getResourceNameOfMainJar(ResourceInfo mainJar) {
+        if (null == mainJar) {
+            throw new RuntimeException("The jar for the task is required.");
+        }
+        return mainJar.getId() == 0
+                ? mainJar.getRes()
+                // when update resource maybe has error
+                : mainJar.getResourceName().replaceFirst(SINGLE_SLASH, "");
+    }
+
+    @Override
+    public void cancelApplication(boolean cancelApplication) throws Exception {
+        // cancel process
+        shellCommandExecutor.cancelApplication();
+    }
+
+    @Override
+    public AbstractParameters getParameters() {
+        return javaParameters;
+    }
+
+    /**
+     * @description: Replaces placeholders such as local variables in source files
+     * @param: [java.lang.String]
+     * @return: java.lang.String

Review Comment:
   AFAIK, this is not the standard javadoc?



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJavaCommand() throws Exception {
+        String sourceCode = buildJavaSourceContent();
+        String className = compilerRawScript(sourceCode);
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath())
+                .append(" ")
+                .append(className).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private void setMainJarName() {
+        ResourceInfo mainJar = javaParameters.getMainJar();
+        String resourceName = getResourceNameOfMainJar(mainJar);
+        mainJar.setRes(resourceName);
+        javaParameters.setMainJar(mainJar);
+    }
+
+    /**
+     * @description: Construct a shell command for the java -jar Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/
+    protected String buildJarCommand() {
+        String fullName = javaParameters.getMainJar().getResourceName();
+        String mainJarName = fullName.substring(0, fullName.lastIndexOf('.'));
+        mainJarName = mainJarName.substring(mainJarName.lastIndexOf('.') + 1) + ".jar";
+        StringBuilder builder = new StringBuilder();
+        builder.append(getJavaCommandPath())
+                .append("java").append(" ")
+                .append(buildResourcePath()).append(" ")
+                .append("-jar").append(" ")
+                .append(taskRequest.getExecutePath())
+                .append(mainJarName).append(" ")
+                .append(javaParameters.getMainArgs().trim()).append(" ")
+                .append(javaParameters.getJvmArgs().trim());
+        return builder.toString();
+    }
+
+    private String getResourceNameOfMainJar(ResourceInfo mainJar) {
+        if (null == mainJar) {
+            throw new RuntimeException("The jar for the task is required.");
+        }
+        return mainJar.getId() == 0
+                ? mainJar.getRes()
+                // when update resource maybe has error
+                : mainJar.getResourceName().replaceFirst(SINGLE_SLASH, "");
+    }
+
+    @Override
+    public void cancelApplication(boolean cancelApplication) throws Exception {
+        // cancel process
+        shellCommandExecutor.cancelApplication();
+    }
+
+    @Override
+    public AbstractParameters getParameters() {
+        return javaParameters;
+    }
+
+    /**
+     * @description: Replaces placeholders such as local variables in source files
+     * @param: [java.lang.String]
+     * @return: java.lang.String
+     **/
+    protected static String convertJavaSourceCodePlaceholders(String rawScript) throws StringIndexOutOfBoundsException {

Review Comment:
   Can we directly use `ParameterUtils.convertParameterPlaceholders`?



##########
dolphinscheduler-task-plugin/dolphinscheduler-task-java/src/main/java/org/apache/dolphinscheduler/plugin/task/java/JavaTask.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.dolphinscheduler.plugin.task.java;
+
+import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.SINGLE_SLASH;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.JAVA_HOME_VAR;
+import static org.apache.dolphinscheduler.plugin.task.java.JavaConstants.PUBLIC_CLASS_NAME_REGEX;
+
+
+import org.apache.dolphinscheduler.plugin.task.api.AbstractTaskExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.ShellCommandExecutor;
+import org.apache.dolphinscheduler.plugin.task.api.TaskConstants;
+import org.apache.dolphinscheduler.plugin.task.api.TaskException;
+import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
+import org.apache.dolphinscheduler.plugin.task.api.model.Property;
+import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
+import org.apache.dolphinscheduler.plugin.task.api.model.TaskResponse;
+import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
+import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
+import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
+import org.apache.dolphinscheduler.plugin.task.java.exception.JavaSourceFileExistException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.PublicClassNotFoundException;
+import org.apache.dolphinscheduler.plugin.task.java.exception.RunTypeNotFoundException;
+import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.SystemUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * java task
+ */
+public class JavaTask extends AbstractTaskExecutor {
+
+    /**
+     * Contains various parameters for this task
+     */
+    private JavaParameters javaParameters;
+
+    /**
+     * To run shell commands
+     */
+    private ShellCommandExecutor shellCommandExecutor;
+
+    /**
+     * task execution context
+     */
+    private TaskExecutionContext taskRequest;
+
+    /**
+     * class name regex pattern
+     */
+    private static final Pattern classNamePattern = Pattern.compile(PUBLIC_CLASS_NAME_REGEX);
+
+    /**
+     * @description: Construct a Java task
+     * @param: [org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext]
+     * @return: JavaTask
+     **/
+    public JavaTask(TaskExecutionContext taskRequest) {
+        super(taskRequest);
+        this.taskRequest = taskRequest;
+        this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
+                taskRequest,
+                logger);
+    }
+
+    /**
+     * @description: Initializes a Java task
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void init() {
+        logger.info("java task params {}", taskRequest.getTaskParams());
+        javaParameters = JSONUtils.parseObject(taskRequest.getTaskParams(), JavaParameters.class);
+        if (javaParameters == null || !javaParameters.checkParameters()) {
+            throw new TaskException("java task params is not valid");
+        }
+        if (javaParameters.getRunType().equals(JavaConstants.RUN_TYPE_JAR)) {
+            setMainJarName();
+        }
+    }
+
+    /**
+     * @description: Gets the Java source file that was initially processed
+     * @param: []
+     * @return: java.lang.String
+     **/
+    @Override
+    public String getPreScript() {
+        String rawJavaScript = javaParameters.getRawScript().replaceAll("\\r\\n", "\n");
+        try {
+            rawJavaScript = convertJavaSourceCodePlaceholders(rawJavaScript);
+        } catch (StringIndexOutOfBoundsException e) {
+            logger.error("setShareVar field format error, raw java script : {}", rawJavaScript);
+        }
+        return rawJavaScript;
+    }
+
+    /**
+     * @description: Execute Java tasks
+     * @param: []
+     * @return: void
+     **/
+    @Override
+    public void handle() throws Exception {
+        try {
+            // Step 1: judge if is java or jar run type.
+            // Step 2 case1: The jar run type builds the command directly, adding resource to the java -jar class when building the command
+            // Step 2 case2: The java run type, first replace the custom parameters, then compile the code, and then build the command will add resource
+            // Step 3: To run the command
+            String command = null;
+            switch (javaParameters.getRunType()) {
+                case JavaConstants.RUN_TYPE_JAVA:
+                    command = buildJavaCommand();
+                    break;
+                case JavaConstants.RUN_TYPE_JAR:
+                    command = buildJarCommand();
+                    break;
+                default:
+                    throw new RunTypeNotFoundException("run type is required, but it is null now.");
+            }
+            Preconditions.checkNotNull(command, "command not be null.");
+            TaskResponse taskResponse = shellCommandExecutor.run(command);
+            logger.info("java task run result : {}", taskResponse);
+            setExitStatusCode(taskResponse.getExitStatusCode());
+            setAppIds(taskResponse.getAppIds());
+            setProcessId(taskResponse.getProcessId());
+            setVarPool(shellCommandExecutor.getVarPool());
+        } catch (InterruptedException e) {
+            logger.error("java task interrupted ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            Thread.currentThread().interrupt();
+        } catch (RunTypeNotFoundException e) {
+            logger.error(e.getMessage());
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw e;
+        } catch (Exception e) {
+            logger.error("java task failed ", e);
+            setExitStatusCode(TaskConstants.EXIT_CODE_FAILURE);
+            throw new TaskException("run java task error", e);
+        }
+    }
+
+    /**
+     * @description: Construct a shell command for the java Run mode
+     * @param: []
+     * @return: java.lang.String
+     **/

Review Comment:
   ```suggestion
        * @description: Construct a shell command for the java Run mode
        * @return: java.lang.String
        **/
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@dolphinscheduler.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org