ComposantsComponents

ComposantsComponents › Code personnaliséCustom Code

tJava

tJava

Code personnaliséCustom Code

Exécute une fois le code Java que vous écrivez : afficher un message, calculer une valeur, changer une variable de contexte, préparer une variable globale pour la suite du job ou décider, avec un Run if, de la branche à suivre. Runs once the Java code you write: print a message, compute a value, change a context variable, prepare a global variable for the rest of the job or decide, with a Run if, which branch to follow.

EntréeInput

Aucune : il peut commencer un sous-job. Sinon un lien Main ou Iterate. None: it can start a subjob. Otherwise one Main or Iterate link.

SortieOutput

Facultative : un lien Main ou Iterate. Optional: one Main or Iterate link.

Déclencheurs en sortieOutput triggers

On Subjob Ok On Subjob Error On Component Ok On Component Error Run if

On Subjob : seulement quand il commence son sous-job. On Subjob: only when it starts its subjob.

UtilisationUsage

Seul, dans son sous-jobAlone, in its subjob

OnSubjobOk tJava_1 tFileInputDelimited_1

Le cas le plus courant : préparer quelque chose avant la suite du job (une variable de contexte, un nom de fichier, un message). The most common case: prepare something before the rest of the job (a context variable, a file name, a message).

À chaque itérationAt each iteration

Iterate tLoop_1 tJava_1

Relié par un lien Iterate (tLoop, tFileList, tFlowToIterate…), son code s'exécute une fois par itération. Connected with an Iterate link (tLoop, tFileList, tFlowToIterate…), its code runs once per iteration.

Une fois, pas une fois par ligneOnce, not once per row

Le code est placé dans la partie de démarrage du composant. Même au milieu d'un flux, il s'exécute une seule fois, avant la première ligne. Pour traiter chaque ligne, prenez un tJavaRow ; pour un code au début, à chaque ligne et à la fin, un tJavaFlex. The code is placed in the start part of the component. Even in the middle of a flow, it runs only once, before the first row. To process each row, take a tJavaRow; for code at the start, at each row and at the end, a tJavaFlex.

  1. Déposez le tJava depuis la famille Code personnalisé de la palette. Drop the tJava from the Custom Code family of the palette.
  2. Écrivez vos instructions Java dans le champ Code de l'onglet Composant, et les import dont elles ont besoin dans Paramètres avancés › Import. Write your Java statements in the Code field of the Component tab, and the import lines they need in Advanced settings › Import.
  3. Reliez-le à la suite du job par un déclencheur (On Subjob Ok, Run if…), puis lancez le job (F6). Ce que le code écrit avec System.out.println apparaît dans la console de l'onglet Exécuter. Connect it to the rest of the job with a trigger (On Subjob Ok, Run if…), then run the job (F6). What the code writes with System.out.println appears in the console of the Run tab.

ParamètresSettings

Le nom technique, en gris, est celui du paramètre dans le fichier du job. The technical name, in grey, is the parameter name in the job file.

ParamètreSetting DéfautDefault OngletTab Description
CodeCODE String foo = "bar"; Paramètres simplesBasic settings Les instructions Java à exécuter, recopiées telles quelles dans le code du job. Elles sont à l'intérieur d'une méthode : déclarez des variables, appelez des routines, mais pas de nouvelle méthode. The Java statements to run, copied as is into the job code. They are inside a method: declare variables, call routines, but no new method.
ImportIMPORT //import java.util.List; Paramètres avancésAdvanced settings Lignes import complètes, avec leur point-virgule. Elles sont placées en tête de la classe du job : elles valent pour tout le code du job, pas seulement pour ce tJava. Complete import lines, with their semicolon. They are placed at the top of the job class: they apply to all the job code, not only to this tJava.

Ce que le code peut utiliserWhat the code can use

context.nomname
Les variables de contexte du job, en lecture et en écriture. Une valeur changée vaut pour la suite du job.The job context variables, to read and write. A changed value applies to the rest of the job.
globalMap
Les variables globales : globalMap.put("clé", valeur), globalMap.get("clé") (à convertir dans son type), et celles des composants (tLogRow_1_NB_LINE…).The global variables: globalMap.put("key", value), globalMap.get("key") (to cast to its type), and those of the components (tLogRow_1_NB_LINE…).
TalendDate, StringHandling…
Les routines système et celles du projet (Code › Routines), sans import.The system routines and those of the project (Code › Routines), without import.
jobName · jobVersion · projectName
Le nom et la version du job, le nom du projet.The job name and version, the project name.
System.out · System.err
La console d'exécution (sortie standard et sortie d'erreur du job).The Run console (standard output and error output of the job).

ExemplesExamples

Chaque sortie est celle de la console, copiée depuis une exécution du job. Dans les erreurs, plus bas, le nom du job est remplacé par MyJob et les traces d'exception et messages de compilation sont abrégés. Each output is the console one, copied from a run of the job. In the errors, below, the job name is replaced with MyJob and the exception traces and compilation messages are shortened.

Lire et changer une variable de contexteRead and change a context variable

Contexte customer (String) valant Ada. Context customer (String) set to Ada.

System.out.println("Hello " + context.customer + "!");
context.customer = context.customer.toUpperCase();
System.out.println("Now: " + context.customer);
Hello Ada!
Now: ADA

Passer une valeur au sous-job suivantPass a value to the next subjob

OnSubjobOk tJava_1 tJava_2
// tJava_1
globalMap.put("total", 42);
System.out.println("Subjob 1: total stored");

// tJava_2
Integer total = (Integer) globalMap.get("total");
System.out.println("Subjob 2: total = " + total);
Subjob 1: total stored
Subjob 2: total = 42

Avec un importWith an import

Paramètres avancés › Import : import java.time.LocalDate; Advanced settings › Import: import java.time.LocalDate;

System.out.println(LocalDate.of(2026, 11, 10).getDayOfWeek());
TUESDAY

À chaque itération d'un tLoopAt each iteration of a tLoop

Iterate tLoop_1 tJava_1

tLoop de 1 à 3. Sa variable CURRENT_VALUE donne le numéro de l'itération. tLoop from 1 to 3. Its CURRENT_VALUE variable gives the iteration number.

System.out.println("Iteration " + ((Integer) globalMap.get("tLoop_1_CURRENT_VALUE")));
Iteration 1
Iteration 2
Iteration 3

Choisir la branche avec Run ifChoose the branch with Run if

If If tJava_1 tJava_2 tJava_3
// tJava_1
globalMap.put("fileCount", 0);

// Run if → tJava_2 (prints "No file to process")
((Integer) globalMap.get("fileCount")) == 0
// Run if → tJava_3 (prints "Processing files")
((Integer) globalMap.get("fileCount")) > 0
No file to process

Au milieu d'un flux : une seule foisIn the middle of a flow: only once

row1 (Main) tFixedFlowInput_1 tJava_1
System.out.println("tJava_1 code");
tJava_1 code

Trois lignes passent, le message n'est écrit qu'une fois. Three rows go through, the message is written only once.

ErreursErrors

Le code du tJava est compilé avec le reste du job : une erreur Java empêche le job de démarrer. Une exception à l'exécution arrête le composant. The tJava code is compiled with the rest of the job: a Java error prevents the job from starting. An exception at run time stops the component.

Exception sans lien d'erreurException without an error link

OnSubjobOk tJava_1 tJava_2
if (true) {
    throw new RuntimeException("Stop here");
}
Exception in component tJava_1 (MyJob)
java.lang.RuntimeException: Stop here
	at demo.myjob_0_1.MyJob.tJava_1Process(MyJob.java:395)
	…

Le job s'arrête avec le code de sortie 1 : le sous-job suivant ne s'exécute pas. The job stops with exit code 1: the next subjob does not run.

Exception traitée par On Component ErrorException handled by On Component Error

OnComponentError tJava_1 tJava_2
// tJava_2
System.out.println("Error caught: " + globalMap.get("tJava_1_ERROR_MESSAGE"));
Exception in component tJava_1 (MyJob)
java.lang.RuntimeException: Stop here
	…
Error caught: Stop here

L'exception est toujours écrite, mais le job continue par le lien d'erreur et se termine avec le code 0. tJava_1_ERROR_MESSAGE donne son message. The exception is still written, but the job goes on through the error link and ends with code 0. tJava_1_ERROR_MESSAGE gives its message.

Erreurs de compilation fréquentesFrequent compilation errors

Variable d'un autre sous-jobVariable from another subjob

// tJava_1
int count = 3;
// tJava_2, relié par On Subjob Ok / connected with On Subjob Ok
System.out.println(count);
error: cannot find symbol
System.out.println(count);
                   ^
  symbol:   variable count

Chaque sous-job est une méthode Java : une variable déclarée dans un tJava n'existe que dans son sous-job. Passez la valeur par globalMap ou par une variable de contexte. Each subjob is a Java method: a variable declared in a tJava only exists in its subjob. Pass the value through globalMap or a context variable.

throw ou return seulBare throw or return

throw new RuntimeException("Stop here");
error: unreachable statement
	currentComponent="tJava_1";
	^

Le code du job continue après celui du tJava : Java refuse une instruction qui ne peut plus être atteinte. Placez le throw dans un if, comme dans les exemples ci-dessus. The job code goes on after the tJava code: Java refuses a statement that can no longer be reached. Put the throw inside an if, as in the examples above.

ConseilsTips

Le bon composantThe right component

  • tJavaRow : un code pour chaque ligne d'un flux.tJavaRow: code for each row of a flow.
  • tJavaFlex : un code au début, à chaque ligne et à la fin.tJavaFlex: code at the start, at each row and at the end.
  • tSetGlobalVar : des variables globales sans écrire de code.tSetGlobalVar: global variables without writing code.

Code réutilisé : une routineReused code: a routine

Une méthode ne se déclare pas dans un tJava. Un code utile à plusieurs composants ou plusieurs jobs se met dans une routine du projet (Code › Routines), appelée ensuite depuis le tJava : MaRoutine.calcul(…). A method cannot be declared in a tJava. Code useful to several components or several jobs goes into a project routine (Code › Routines), then called from the tJava: MyRoutine.compute(…).

Types de globalMapglobalMap types

globalMap.get renvoie un Object : convertissez-le dans le type rangé, (Integer) globalMap.get("total"). Un nom de clé mal écrit renvoie null, sans erreur. globalMap.get returns an Object: cast it to the stored type, (Integer) globalMap.get("total"). A misspelled key name returns null, without an error.

Arrêter le job proprementStop the job cleanly

Pour arrêter le job sur une condition, levez une exception dans un if, ou faites suivre le tJava d'un tDie par un Run if : le message passe alors au tLogCatcher. To stop the job on a condition, throw an exception inside an if, or follow the tJava with a tDie through a Run if: the message then goes to the tLogCatcher.

Voir aussiSee also

Les autres composants de la famille Code personnalisé : The other components of the Custom Code family: