Announcement Announcement Module
Collapse
No announcement yet.
How to use SBA as Restful service? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to use SBA as Restful service?

    I have downloaded the SBA(spring batch admin) sample of 1.0.0.M3, and run it correctly.Now i just to use it as Restful service,so the other projects can invoke it by using the class RestTemplat.

    I am so sorry that my english is bad...

    /my/jobs GET
    /my/jobs/{jobName} GET
    /my/jobs/{jobName} POST
    The GETS works good,but i can't invoke the postForObject correctly...
    the server side will invoke the method launch,but can't accept the parameter launchReques's value.I just want to give the jobParameters and invoke the method launch by using the class RestTemplat on the client side.Do i have to use the form on the html?I'm new to Spring MVC,sorry.




    package org.springframework.batch.admin.web;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import java.util.TimeZone;

    import org.springframework.batch.admin.service.JobService ;
    import org.springframework.batch.core.JobExecution;
    import org.springframework.batch.core.JobInstance;
    import org.springframework.batch.core.JobParameters;
    import org.springframework.batch.core.JobParametersInvali dException;
    import org.springframework.batch.core.converter.DefaultJo bParametersConverter;
    import org.springframework.batch.core.converter.JobParame tersConverter;
    import org.springframework.batch.core.launch.NoSuchJobExc eption;
    import org.springframework.batch.core.repository.JobExecu tionAlreadyRunningException;
    import org.springframework.batch.core.repository.JobInsta nceAlreadyCompleteException;
    import org.springframework.batch.core.repository.JobResta rtException;
    import org.springframework.batch.support.PropertiesConver ter;
    import org.springframework.beans.factory.annotation.Autow ired;
    import org.springframework.beans.factory.annotation.Quali fier;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.validation.Errors;
    import org.springframework.web.bind.annotation.ModelAttri bute;
    import org.springframework.web.bind.annotation.PathVariab le;
    import org.springframework.web.bind.annotation.RequestBod y;
    import org.springframework.web.bind.annotation.RequestMap ping;
    import org.springframework.web.bind.annotation.RequestMet hod;
    import org.springframework.web.bind.annotation.RequestPar am;

    /**
    * Controller for launching jobs.
    *
    *
    *
    */
    @Controller
    public class MyJobController {

    private final JobService jobService;

    private JobParametersConverter converter = new DefaultJobParametersConverter();

    private TimeZone timeZone = TimeZone.getDefault();

    /**
    * @param timeZone the timeZone to set
    */
    @Autowired(required=false)
    @Qualifier("userTimeZone")
    public void setTimeZone(TimeZone timeZone) {
    this.timeZone = timeZone;
    }

    @Autowired
    public MyJobController(JobService jobService) {
    super();
    this.jobService = jobService;
    }

    @RequestMapping(value = "/my/jobs/{jobName}", method = RequestMethod.POST)
    public String launch(ModelMap model, @PathVariable String jobName,
    @ModelAttribute("launchRequest") LaunchRequest launchRequest, Errors errors,
    @RequestParam(defaultValue = "job") String origin) {

    launchRequest.setJobName(jobName);
    String params = launchRequest.jobParameters;
    System.out.println("=============="+params+"====== =============");
    Properties properties = PropertiesConverter.stringToProperties(params);
    JobParameters jobParameters = converter.getJobParameters(properties);

    try {
    JobExecution jobExecution = jobService.launch(jobName, jobParameters);
    model.addAttribute(new JobExecutionInfo(jobExecution, timeZone));
    }
    catch (NoSuchJobException e) {
    errors.reject("no.such.job", new Object[] { jobName }, "No such job: " + jobName);
    }
    catch (JobExecutionAlreadyRunningException e) {
    errors.reject("job.already.running", "A job with this name and parameters is already running.");
    }
    catch (JobRestartException e) {
    errors.reject("job.could.not.restart", "The job was not able to restart.");
    }
    catch (JobInstanceAlreadyCompleteException e) {
    errors
    .reject("job.already.complete",
    "A job with this name and parameters already completed successfully.");
    }
    catch (JobParametersInvalidException e) {
    errors.reject("job.parameters.invalid", "The job parameters are invalid according to the configuration.");
    }

    if ("execution".equals(origin)) {
    // return "jobs/execution";
    return "json";
    }
    else {
    return details(model, jobName, new Date(), errors, 0, 20);
    }

    // Not a redirect because normally it is requested by an Ajax call so
    // there's less of a pressing need for one (the browser history won't
    // contain the request).

    }





    @RequestMapping(value = "/my/jobs/{jobName}", method = RequestMethod.GET)
    public String details(ModelMap model, @PathVariable String jobName, @ModelAttribute("date") Date date,
    Errors errors, @RequestParam(defaultValue = "0") int startJobInstance,
    @RequestParam(defaultValue = "20") int pageSize) {

    model.addAttribute("launchable", jobService.isLaunchable(jobName));

    try {
    int total = jobService.countJobInstances(jobName);

    Collection<JobInstance> result = jobService.listJobInstances(jobName, startJobInstance, total);
    Collection<JobInstanceInfo> jobInstances = new ArrayList<JobInstanceInfo>();
    for (JobInstance jobInstance : result) {
    jobInstances.add(new JobInstanceInfo(jobInstance, jobService.getJobExecutionsForJobInstance(jobName,
    jobInstance.getId())));
    }

    model.addAttribute("jobInstances", jobInstances);
    model.addAttribute("jobParameters", getLastJobParameters(jobInstances));

    TableUtils.addPagination(model, total, startJobInstance, pageSize, "JobInstance");
    int count = jobService.countJobExecutionsForJob(jobName);
    model.addAttribute("job", new JobInfo(jobName, count));

    }
    catch (NoSuchJobException e) {
    errors.reject("no.such.job", new Object[] { jobName }, "There is no such job (" + jobName + ")");
    }
    // return "jobs/job";
    return "json";

    }

    /**
    * @param lastInstances the latest job instances
    * @return a String representation for rendering the job parameters from the last instance
    */
    private String getLastJobParameters(Collection<JobInstanceInfo> lastInstances) {

    JobInstance lastInstance = null;
    if (!lastInstances.isEmpty()) {
    lastInstance = lastInstances.iterator().next().getJobInstance();
    }

    JobParameters oldParameters = new JobParameters();
    if (lastInstance != null) {
    oldParameters = lastInstance.getJobParameters();
    }

    return PropertiesConverter.propertiesToString(converter.g etProperties(oldParameters));
    }

    @RequestMapping(value = "/my/jobs", method = RequestMethod.GET)
    public String jobs(ModelMap model, @RequestParam(defaultValue = "0") int startJob,
    @RequestParam(defaultValue = "20") int pageSize) {
    int total = jobService.countJobs();
    Collection<String> names = jobService.listJobs(startJob,total);
    List<JobInfo> jobs = new ArrayList<JobInfo>();
    for (String name : names) {
    int count = 0;
    try {
    count = jobService.countJobExecutionsForJob(name);
    }
    catch (NoSuchJobException e) {
    // shouldn't happen
    }
    boolean launchable = jobService.isLaunchable(name);
    boolean incrementable = jobService.isIncrementable(name);
    jobs.add(new JobInfo(name, count, null, launchable, incrementable));
    }
    model.addAttribute("jobs", jobs);
    return "json";
    }

    }


    spring-batch-admin-sample/src/main/resources/META-INF/spring/batch/jobs/module-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean parent="placeholderProperties" />

    <bean name="/steps/step1" class="org.springframework.remoting.httpinvoker.Ht tpInvokerServiceExporter">
    <property name="serviceInterface" value="org.springframework.batch.core.Step" />
    <property name="service" ref="step1" />
    </bean>

    <bean id="step1" class="org.springframework.batch.admin.service.Ste pLocatorStepFactoryBean">
    <property name="stepLocator">
    <bean class="org.springframework.batch.admin.service.Job LocatorStepLocator">
    <property name="jobLocator" ref="jobRegistry"/>
    </bean>
    </property>
    <property name="stepName" value="job1/j1.s1"/>
    </bean>
    <bean class="org.springframework.batch.admin.web.MyJobCo ntroller"/>
    <bean id="json" class="org.springframework.web.servlet.view.json.M appingJacksonJsonView"/>

    </beans>

  • #2
    client code:


    /**
    *
    */
    package org.springframework.batch.admin.sample;

    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;

    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;

    import org.apache.commons.collections.map.MultiValueMap;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.junit.runner.RunWith;
    import org.springframework.batch.admin.web.LaunchRequest;
    import org.springframework.batch.core.Job;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.client.ClientHttpRequestF actory;
    import org.springframework.http.converter.HttpMessageConv erter;
    import org.springframework.test.context.ContextConfigurat ion;
    import org.springframework.test.context.junit4.SpringJUni t4ClassRunner;
    import org.springframework.web.bind.annotation.ModelAttri bute;
    import org.springframework.web.client.RestTemplate;

    import com.sun.org.apache.bcel.internal.generic.NEW;
    import com.sun.xml.internal.bind.v2.schemagen.xmlschema.L ist;

    /**
    * @author Administrator
    *v
    */

    public class TestClient {
    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String url="http://localhost:8888/spring-batch-admin-sample/batch/my/jobs";
    RestTemplate restTemplate=new RestTemplate();
    String result=null;
    result= restTemplate.getForObject(url, String.class);
    System.out.println(result);
    System.out.println("============================== ========" +
    "================================================= ======");
    url="http://localhost:8888/spring-batch-admin-sample/batch/my/jobs/{jobName}";
    restTemplate=new RestTemplate();
    String jobParameters="run.count(long)=3,fail=false";
    LaunchRequest launchRequest=new LaunchRequest();
    launchRequest.setJobParameters(jobParameters);
    result=restTemplate.postForObject(url, launchRequest, String.class, "job1");
    System.out.println(result); System.out.println("============================== ========" +
    "================================================= ======");

    }

    }

    I try the rest other method of RestTemplate (such as exchange, postForEntity),but the same sad end.

    Comment


    • #3
      I think you ned to look at @RequestBody and @ResponseBody. Might be an idea to ask in the web forum, since that is the feature set you need (not really Batch specific).

      (Please use [code][/code] tags to post code and stack traces.)

      Comment

      Working...
      X