title: Spring Batch: Executing job depending on result in itemReader
body: <p>I'm developing a spring batch application. I've set a job with 1 step that uses an ItemReader, an ItemProcessor and an ItemWriter. My ItemReader does a HTTP request obtaining json from an API. The processor transform its content and finally the writer persist it to a text file.</p>
  
  <p>I'm executing this job from a java scheduler, where I set the jobParameters that itemReader uses to do the HTTP Request (npag). Since the consulted API paginate the results, I want to execute this job an indeterminate amount of times, till the result of the http request is that there's no more data.</p>
  
  <p><em>Example:</em></p>
  
  <p>If reader does the http request (<a href="http://whatever/resource?npag=1" rel="nofollow">http://whatever/resource?npag=1</a>) obtaining:</p>
  
  <pre><code>[{"item1":"content1"}....{"item500":"content500"}]
  </code></pre>
  
  <p>Since API paginates in groups of 500 items, I need to execute the job another time because probably we have more data. To do this I change the npag parameter in de resource (<a href="http://whatever/resource?npag=2" rel="nofollow">http://whatever/resource?npag=2</a>).</p>
  
  <p>If I obtain as a result:</p>
  
  <pre><code>[]
  </code></pre>
  
  <p>There's no more data, so I want to stop executing the job.</p>
  
  <p><strong>My approach:</strong>
  I was trying to set a jobParameter in ItemReader that lets me know in the Scheduler if I can stop or not doing requests. But in ItemReader I only know how to read jobparameters (with annotation @StepCope), but not how to set it.</p>
  
  <p>Summary: I need to know the value of a variable setted in the ItemReader from outside the job (from the scheduler that execute this job)</p>
  
  <p>Any idea? Thanks,</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>As @HansjoergWingeier suggest, doing all the requests inside the itemReader could resolve the problem:</p>
  
  <pre><code>private String npag = 1;
  
  @Override
  public String read() throws Exception {
  
      Map&lt;String, String&gt; vars = new HashMap&lt;&gt;();
  
      while (npag &gt; 0) {
          vars.put("numPag", String.valueOf(npag));
  
          String result = restTemplate.getForObject(urlAPI, String.class, vars);
          if ("[]".equals(result)) {
              return null;
          } else {
              npag++;
              return result;
          }
      }
      return null;
  }
  </code></pre>