kunwp1 commented on code in PR #9339:
URL: https://github.com/apache/texera/pull/9339#discussion_r4516814219


##########
frontend/package.json:
##########
@@ -35,6 +35,7 @@
     "@auth0/angular-jwt": "5.1.0",
     "@codingame/monaco-vscode-java-default-extension": "37.6.1",
     "@codingame/monaco-vscode-python-default-extension": "37.6.1",
+    "@lezer/java": "1.1.5",

Review Comment:
   The ubuntu frontend job fails its license check because `@lezer/[email protected]` 
isn't in `frontend/LICENSE-binary`. It goes under MIT next to the other 
`@lezer` entries.



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/udf/java/JavaUdfUiParameterInjector.scala:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.texera.amber.operator.udf.java
+
+import com.sun.source.tree._
+import com.sun.source.util.{JavacTask, Trees}
+import org.apache.texera.amber.core.tuple.AttributeType
+import org.apache.texera.amber.operator.udf.{UiUDFParameter, 
UiUdfParameterContract}
+
+import java.net.URI
+import java.nio.charset.StandardCharsets
+import java.time.{LocalDateTime, ZoneOffset}
+import java.time.format.{DateTimeFormatter, DateTimeFormatterBuilder, 
ResolverStyle}
+import java.time.temporal.ChronoField
+import java.util.{Base64, Locale}
+import javax.lang.model.element.Modifier
+import javax.tools._
+import scala.jdk.CollectionConverters._
+import scala.util.{Try, Using}
+
+/** Uses javac's source tree to initialize annotated fields without executing 
user code. */
+object JavaUdfUiParameterInjector {
+  private val annotationName = 
"org.apache.texera.amber.operator.udf.java.UiParameter"
+  private val nativeTypes = UiUdfParameterContract.javaTypes.flatMap {
+    case (kind, names) => names.map(_ -> kind)
+  }
+  private val timestampFormat = new DateTimeFormatterBuilder()
+    .append(DateTimeFormatter.ISO_LOCAL_DATE)
+    .optionalStart()
+    .appendLiteral('T')
+    .appendPattern("HH")
+    .optionalStart()
+    .appendPattern(":mm")
+    .optionalStart()
+    .appendPattern(":ss")
+    .optionalStart()
+    .appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
+    .optionalEnd()
+    .optionalEnd()
+    .optionalEnd()
+    .optionalEnd()
+    .optionalStart()
+    .appendOffset("+HH:MM", "Z")
+    .optionalEnd()
+    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
+    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
+    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
+    .toFormatter(Locale.ROOT)
+    .withResolverStyle(ResolverStyle.STRICT)
+
+  private def refuse(message: String): Nothing = throw new 
RuntimeException(s"UiParameter $message")
+  private def stringExpression(text: String): String = {
+    val encoded = 
Base64.getEncoder.encodeToString(text.getBytes(StandardCharsets.UTF_8))
+    s"""new String(java.util.Base64.getDecoder().decode("$encoded"), 
java.nio.charset.StandardCharsets.UTF_8)"""
+  }
+  private def number(raw: String): Double =
+    raw.toLowerCase(Locale.ROOT) match {
+      case "nan" | "+nan" | "-nan"                   => Double.NaN
+      case "inf" | "+inf" | "infinity" | "+infinity" => Double.PositiveInfinity
+      case "-inf" | "-infinity"                      => Double.NegativeInfinity
+      case value if 
value.matches("[+-]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?") =>
+        value.toDouble
+      case _ => refuse("requires a decimal numeric value.")
+    }
+  private def initializer(p: UiUDFParameter): String = {
+    val raw = p.value.trim
+    Try {
+      p.attribute.getType match {
+        case AttributeType.STRING  => stringExpression(p.value)
+        case AttributeType.INTEGER => raw.toInt.toString
+        case AttributeType.LONG    => s"${raw.toLong}L"
+        case AttributeType.DOUBLE =>
+          
s"java.lang.Double.longBitsToDouble(${java.lang.Double.doubleToLongBits(number(raw))}L)"
+        case AttributeType.BOOLEAN =>
+          (raw.toLowerCase(Locale.ROOT) match {
+            case "true"  => true
+            case "false" => false
+            case _       => number(raw) != 0d
+          }).toString
+        case AttributeType.TIMESTAMP =>
+          val normalized = raw.replace(' ', 
'T').replaceFirst("([+-][0-9]{2})([0-9]{2})$", "$1:$2")
+          val parsed = timestampFormat.parse(normalized)
+          val offset =
+            if (parsed.isSupported(ChronoField.OFFSET_SECONDS)) 
ZoneOffset.from(parsed)
+            else ZoneOffset.UTC
+          val instant = LocalDateTime.from(parsed).toInstant(offset)
+          
s"java.sql.Timestamp.from(java.time.Instant.parse(${stringExpression(instant.toString)}))"
+        case _ => refuse("type is not supported.")
+      }
+    }.recover {
+      case e: Exception =>
+        throw new RuntimeException(
+          s"UiParameter '${p.attribute.getName}' requires a valid 
${p.attribute.getType.getName} value.",
+          e
+        )
+    }.get
+  }
+
+  def inject(code: String, uiParameters: List[UiUDFParameter]): String = {
+    val parameters = Option(uiParameters).getOrElse(Nil)
+    UiUdfParameterContract.validate(parameters)
+    val source = Option(code).getOrElse("")
+    if (parameters.isEmpty && !source.contains("UiParameter")) return source
+    val compiler = ToolProvider.getSystemJavaCompiler
+    if (compiler == null)
+      refuse("declarations require a JDK with javac on the workflow compiling 
service.")

Review Comment:
   This runs wherever the workflow is compiled, including the 
workflow-compiling-service. That image runs on `eclipse-temurin:17-jre` 
(`bin/dockerfiles/workflow-compiling-service.dockerfile`), where 
`getSystemJavaCompiler()` returns null; I confirmed that by running without the 
`jdk.compiler` module. The new default template comment contains `UiParameter`, 
so the skip above doesn't apply, and every new Java UDF shows this error in a 
deployed stack, even with no parameters. Returning the source unchanged when 
javac is missing and no values are saved fixes that case. 
   
   Workflows with saved Java parameters would still hit this refusal on every 
compile there, because only computing-unit-master ships a JDK. One option is a 
JDK image for the compiling service. The other is to skip injection whenever 
javac is missing: a host without javac can't run Java UDFs anyway, since 
`JavaRuntimeCompilation` needs it too, and execution re-runs this injection on 
the computing unit.



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/udf/java/JavaUDFOpDesc.scala:
##########
@@ -109,7 +121,7 @@ class JavaUDFOpDesc extends LogicalOp {
           workflowId,
           executionId,
           operatorIdentifier,
-          OpExecWithCode(code, "java")
+          OpExecWithCode(injectUiParameters(code), "java")

Review Comment:
   Both branches now repeat the injected `OpExecWithCode` and 
`executionBinding(code)`. Computing them once before the `if`, as `RUDFOpDesc` 
does, keeps the two builders from drifting apart.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to