Получение параметров из ExecutionContext - PullRequest
0 голосов
/ 21 сентября 2018

У меня есть весеннее пакетное задание, которое выполняется с такими веб-параметрами:

https://localhost:8443/batch/async/orz003A?id=123&name=test

Я добавил эти параметры, id и test в мои ExecutionContext

У меня проблемы с доступом к ним в моем Setup Tasklet, см. Ниже.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.stereotype.Component;
import com.yrc.mcc.app.online.NTfp211;
import com.yrc.mcc.core.batch.tasklet.AbstractSetupTasklet;


@Component
public class Tfp211SetupTasklet extends AbstractSetupTasklet {

    final static Logger LOGGER = LoggerFactory.getLogger(Tfp211SetupTasklet.class);

    String gapId;

    @Override
    protected RepeatStatus performTask(ExecutionContext ec) {

        //TODO create the map, check the params for the needed params
        // throw an error if the param doesn't exist, because the param
        // is necessary to run the job. If the param does exist, set the specific param

        if (ec.isEmpty()) {
            LOGGER.info("this shit is empty");
        }
        //setg on GAPID
        gapId = ec.toString();
        ec.get(BATCH_PROGRAM_PARAMS);
        LOGGER.info(gapId);

        ec.put(AbstractSetupTasklet.BATCH_PROGRAM_NAME, NTfp211.class.getSimpleName());
        return RepeatStatus.FINISHED;
    }

}

Есть предложения?

edit:

Вот фрагмент из моего AbstractSetupTaskler

Map<String, String> params = new HashMap<>();
        if (!ec.containsKey(BATCH_PROGRAM_PARAMS)) {
            ec.put(BATCH_PROGRAM_PARAMS, params);
        }

в SetupTasklet каждой работы, который я хочу указатьпараметры, необходимые для этой работы

edit: у меня есть тасклет, который, как мне кажется, запускает мою работу

@Component
public class CallM204ProgramTasklet implements Tasklet {

    private static final Logger LOGGER = LoggerFactory.getLogger(CallM204ProgramTasklet.class);

    @Autowired
    private CommonConfig commonConfig;

    @Autowired
    private ProgramFactory programFactory;

    @Autowired
    private MidusService midusService;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        ExecutionContext ec = chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext();
        JobParameters jobParameters = chunkContext.getStepContext().getStepExecution().getJobParameters();
        jobParameters.getParameters();
        String progName = ec.getString(AbstractSetupTasklet.BATCH_PROGRAM_NAME);
        Random randomSession = new Random();
        String sessionId = "000000" + randomSession.nextInt(1000000);
        sessionId = sessionId.substring(sessionId.length() - 6);
        SessionData sessionData = new SessionDataImpl("Batch_" + sessionId, commonConfig);
        IOHarness io = new BatchIOHarnessImpl(midusService, commonConfig.getMidus().getSendToMidus());
        sessionData.setIOHarness(io);
        sessionData.setUserId("mccBatch");
        Program program = programFactory.createProgram(progName, sessionData);
        String progResult = null;
        // Create necessary globals for flat file handling.
        @SuppressWarnings("unchecked")
        Map<String, MccFtpFile> files = (Map<String, MccFtpFile>) ec.get(AbstractSetupTasklet.BATCH_FTP_FILES);
        if (files != null) {
            for (MccFtpFile mccFtpFile : files.values()) {
                program.setg(mccFtpFile.getGlobalName(), mccFtpFile.getLocalFile());
            }
        }
        @SuppressWarnings("unchecked")
        Map<String, String> params = (Map<String, String>) ec.get(AbstractSetupTasklet.BATCH_PROGRAM_PARAMS);
        //put params into globals
        if (params != null) {
            params.forEach((k, v) -> program.setg(k, v));
        }
        try {
            program.processUnthreaded(sessionData);
            progResult = io.close(sessionData);
        } catch (Exception e) {
            progResult = "Error running renovated program " + progName + ": " + e.getMessage();
            LOGGER.error(progResult, e);
            chunkContext.getStepContext().getStepExecution().setExitStatus(ExitStatus.FAILED);
        } finally {
            String currResult = ec.getString(AbstractSetupTasklet.BATCH_PROGRAM_RESULT).trim();
            // Put the program result into the execution context.
            ec.putString(AbstractSetupTasklet.BATCH_PROGRAM_RESULT, currResult + "\r" + progResult);
        }
        return RepeatStatus.FINISHED;
    }
}

1 Ответ

0 голосов
/ 21 сентября 2018

Вам необходимо настроить модуль запуска задания и передать параметры, как описано в документации здесь: https://docs.spring.io/spring-batch/4.0.x/reference/html/job.html#runningJobsFromWebContainer.

После этого вы можете получить доступ к параметрам задания в вашем тасклете из контекста чанка.Например:

class MyTasklet implements Tasklet {

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        JobParameters jobParameters = chunkContext.getStepContext().getStepExecution().getJobParameters();
        // get id and name from jobParameters
        // use id and name to do the required work
        return RepeatStatus.FINISHED;
    }
}
...