스프링 배치 shell - seupeuling baechi shell

Hudson 의 Execution Shell에 java command 쓰다가 하루 시간이 다 가므로.. 스크립트를 만들어서 쓰면 많이 편리하다. serivce project 이름, xml 파일 이름, define한 job 이름, 저장할 table의 prefix, 기타 덧붙일 스트링이 있으면 사용하기 편할 수 있다.

실제 사용 예)

/home/www/script/batch_start.pl -p batch_bot –j bot_collector

스크립트

#!/usr/bin/perl

use strict;
use Getopt::Std;

my %OPTS;
getopt('pxjtma', \%OPTS);

my $WWW_HOME = "$ENV{'WWW_HOME'}";

main();

sub main {

        if(scalar(%OPTS) < 2) {
        print STDERR "Usage : batch_start.pl  -p [project-name] -x [xmlfile] -j [jobname] -t [table_prefix]\n";
        print STDERR "ex) batch_start.pl -p batch_template -x batch_template_job.xml -j job1\n\n";
        print STDERR "Usage : batch_start.pl  -p [project-name] -j [jobname] -t [table_prefix] -a [append string]\n";
        print STDERR "ex) batch_start.pl -p batch_template -j job1 -a \"jobparam1=p1\"\n";

        exit 1;
    }

    my $project_name =  $OPTS{"p"};
    my $xml_name =      $OPTS{"x"};
    my $job_name =      $OPTS{"j"};
    my $prefix_name =   $OPTS{"t"};
    my $module_name =   $OPTS{"m"};
    my $appendstr =     $OPTS{"a"};

    # define 해야 할 곳~

    my $project_path =  "…";
    my $jar_name = `ls $project_path| grep $project_name`;

        if ($module_name) {
            $jar_name = $module_name.".jar";
        }

        if($xml_name) {
                $xml_name = "$xml_name";
        } else {
                $xml_name = "$job_name";
        }

        chomp($jar_name);

        my @libList = `ls $project_path/lib`;
        my $classpath_prefix = "$project_path/lib";

        print "## project_name = $project_name"."\n";
        print "## xml_file = $xml_name"."\n";
        print "## job_name = $job_name"."\n";
        print "## jar_name = $jar_name"."\n";
        print "## prefix_name = $prefix_name"."\n";
        print "## appendstr = $appendstr"."\n";

        my $classpath = "./";

        foreach my $lib_jar (@libList) {
                chomp($lib_jar);
                $classpath .= ":$classpath_prefix/$lib_jar";
        }

        chomp($appendstr);

        print "java -jar $project_path/$jar_name $xml_name $job_name $prefix_name $appendstr -classpath$..\n";
        !system("java -jar $project_path/$jar_name $xml_name $job_name $prefix_name $appendstr -classpath$classpath") or die "failure";
}

__END__

pom.xml에 추가할 코드- jar 파일을 바로 실행하게 한다.  


    org.apache.maven.plugins
    maven-jar-plugin
    
     
      true
      
       com.google.batch.ParameterJobLuancher
       true
       lib/
      
     
    

...

Spring Batch의 CommandLineJobRunner 처럼 클래스를 하나 만듬

(http://www.docjar.com/html/api/org/springframework/batch/core/launch/support/CommandLineJobRunner.java.html)

Hello guys, in this post we will explore how to find the solution to Use shell Command in Spring Batch SystemCommandTasklet Code examples in programming.

public ExitStatus processFile(String fileName, String workingDir) throws InterruptedException, IOException {
        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        logger.info("OS windows {} :", isWindows);
        String command = String.format("tail -1 %s > input_footer.txt && head -n -1 %s > input_body.txt", fileName, fileName);
        logger.info("command {} and working dir{} :", command, workingDir);
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(bashPath, "-c", command);
        builder.directory(new File(workingDir));
        Process process = builder.start();
        StreamGobbler streamGobbler =
                new StreamGobbler(process.getInputStream(), System.out::println);
        Executors.newSingleThreadExecutor().submit(streamGobbler);
        int exitCode = process.waitFor();
        ExitStatus status = exitCode == 0 ? ExitStatus.COMPLETED : ExitStatus.FAILED;
        return status;
    }
 public MethodInvokingTaskletAdapter preProcessFileAdapter(@Value("#{jobExecutionContext['customerFile']}") String file, PreProcessFile preProcessFile)
    {
        String workingDir = FilenameUtils.getFullPath(file);
        String fileName = FilenameUtils.getName(file);
        MethodInvokingTaskletAdapter methodInvokingTaskletAdapter=new MethodInvokingTaskletAdapter();
        methodInvokingTaskletAdapter.setTargetObject(preProcessFile);
        methodInvokingTaskletAdapter.setTargetMethod("processFile");
        methodInvokingTaskletAdapter.setArguments(new String[]{fileName,workingDir});
 return methodInvokingTaskletAdapter;
    }

Many examples helped us understand how to fix the Use shell Command in Spring Batch SystemCommandTasklet Code examples error.

How do I run a Spring Batch job from the command line?

Running Jobs from the Command Line

  • Load the appropriate ApplicationContext.
  • Parse command line arguments into JobParameters.
  • Locate the appropriate job based on arguments.
  • Use the JobLauncher provided in the application context to launch the job.

How do I run a batch file in spring?

The steps are as follows:

  • Step 1: On your browser, navigate to the Spring Intializr.
  • Step 2: Set the name of your project as per your choice.
  • Step 3: You can add spring web, h2 database, lombok, spring batch, and spring data jpa as the project dependencies .
  • Step 4: A project zip file will be generated.

What is Chunksize in Spring Batch?

Spring Batch collects items one at a time from the item reader into a chunk, where the chunk size is configurable. Spring Batch then sends the chunk to the item writer and goes back to using the item reader to create another chunk, and so on until the input is exhausted. This is what we call chunk processing.

How do I fail a Tasklet in Spring Batch?

To fail the tasklet, just throw an exception from it.24-Sept-2018

What is %% A in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. () Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.29-Jul-2022

How do I run a batch file line by line?

Executing Batch Files

  • Step 1 − Open the command prompt (cmd.exe).
  • Step 2 − Go to the location where the . bat or . cmd file is stored.
  • Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file.

What is %% g'in batch file?

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.

What is %% R in batch command?

/r - iterate through the folder and all subfolders, i.e. recursively. %%I - placeholder for a path/filename. The above command simply lists all files in the current folder and all subfolders. Follow this answer to receive notifications.22-Aug-2014

How do I run a batch file automatically?

How to schedule a Batch File to run automatically in Windows 11/10

  • Create a Batch file.
  • Open Task Scheduler.
  • Create a Basic Task.
  • Open Task Scheduler Library.
  • Make Task runs with the highest privileges.

What is StepContribution in Spring Batch?

public class StepContribution extends Object implements Serializable. Represents a contribution to a StepExecution , buffering changes until they can be applied at a chunk boundary.