AddPRResourceCustomiser.java
01 package gate.util.spring;
02 
03 import gate.Controller;
04 import gate.ProcessingResource;
05 import gate.Resource;
06 import gate.creole.SerialController;
07 
08 /**
09  * Resource customiser that customises a {@link SerialController} by
10  * adding an extra PR. By default the PR is added to the end of the
11  * controller's PR list, but can optionally be added at a specific
12  * index, or before or after another named PR.
13  */
14 public class AddPRResourceCustomiser implements ResourceCustomiser {
15 
16   private int index = -1;
17 
18   private String addBefore = null;
19 
20   private String addAfter = null;
21 
22   private ProcessingResource pr;
23 
24   public void customiseResource(Resource resthrows Exception {
25     if(!(res instanceof SerialController)) {
26       throw new IllegalArgumentException(this.getClass().getName()
27               " can only customise serial controllers");
28     }
29 
30     SerialController c = (SerialController)res;
31 
32     int indexToAdd = index;
33     if(indexToAdd < 0) {
34       if(addBefore != null) {
35         if(addAfter != null) {
36           throw new IllegalArgumentException(
37                   "Use either addBefore or addAfter, but not both");
38         }
39         else {
40           indexToAdd = findPR(addBefore, c);
41         }
42       }
43       else {
44         if(addAfter != null) {
45           indexToAdd = findPR(addAfter, c1;
46         }
47       }
48     }
49 
50     if(indexToAdd >= 0) {
51       c.add(indexToAdd, pr);
52     }
53     else {
54       c.add(pr);
55     }
56   }
57 
58   /**
59    * Find the index of the first PR with the given name in the
60    * controller.
61    
62    @param name the PR name to search for
63    @param c the controller
64    @return the index of the first PR with this name in the controller,
65    *         or -1 if no such PR exists.
66    */
67   private int findPR(String name, Controller c) {
68     int i = 0;
69     for(Object pr : c.getPRs()) {
70       if(name.equals(((ProcessingResource)pr).getName())) {
71         return i;
72       }
73       i++;
74     }
75 
76     return -1;
77   }
78 
79   public void setIndex(int index) {
80     this.index = index;
81   }
82 
83   public void setAddBefore(String addBefore) {
84     this.addBefore = addBefore;
85   }
86 
87   public void setAddAfter(String addAfter) {
88     this.addAfter = addAfter;
89   }
90 
91   public void setPr(ProcessingResource pr) {
92     this.pr = pr;
93   }
94 
95 }