View Javadoc

1   /*
2    * To change this template, choose Tools | Templates
3    * and open the template in the editor.
4    */
5   
6   package org.lcsim.recon.tracking.seedtracker;
7   
8   import java.io.File;
9   import java.io.FileWriter;
10  import java.io.IOException;
11  import java.io.InputStream;
12  import java.util.ArrayList;
13  import java.util.List;
14  import org.jdom.Attribute;
15  import org.jdom.Comment;
16  import org.jdom.Document;
17  import org.jdom.Element;
18  import org.jdom.JDOMException;
19  import org.jdom.Namespace;
20  import org.jdom.input.SAXBuilder;
21  import org.jdom.output.Format;
22  import org.jdom.output.XMLOutputter;
23  import org.lcsim.event.EventHeader;
24  import org.lcsim.recon.tracking.seedtracker.SeedLayer.SeedType;
25  import org.lcsim.geometry.subdetector.BarrelEndcapFlag;
26  import org.lcsim.util.xml.ClasspathEntityResolver;
27  
28  /**
29   *
30   * @author cozzy
31   */
32  public class StrategyXMLUtils {
33  
34      /**
35       * Returns the default location in the resource hierarchy of the strategy xml files. 
36       * @return
37       */
38      public static String getDefaultStrategiesPrefix(){
39          return "org/lcsim/recon/tracking/seedtracker/strategies/"; 
40      }
41      
42      /**
43       * Returns a strategy list from an xml file in the default location
44       * in the resource hierarchy given the full path to the resource of the file
45       * (i.e. org/lcsim/contrib/seedtracker/strategybuilder/strategies/strategy.xml)
46       * 
47       * getDefaultStrategiesPrefix() may be helpful here. 
48       * @param resourceName the full name of the resource
49       * @return a list of strategies based on the resource xml file
50       */
51      public static List<SeedStrategy> getStrategyListFromResource(String resourceName) {
52          
53          return getStrategyListFromInputStream(StrategyXMLUtils.class.getClassLoader().
54                  getResourceAsStream(resourceName)); 
55      }
56      
57      /**
58       * Attempts to parse the given file as an XML file containing a well-formed
59       * list of strategies. If successful, a list of SeedStrategies corresponding
60       * to the strategies defined in the file is generated. 
61       * 
62       * @param file A File object corresponding to the XML file. 
63       * @return
64       */
65      public static List<SeedStrategy> getStrategyListFromFile(File file) {
66          
67          if (! file.exists() ){
68              throw new RuntimeException("File "+file.toString()+" not found"); 
69          }
70          
71          Document doc; 
72          SAXBuilder builder = new SAXBuilder();
73          builder.setValidation(true); 
74          builder.setFeature("http://apache.org/xml/features/validation/schema", true);
75          builder.setEntityResolver(new ClasspathEntityResolver());
76          try {
77              doc = builder.build(file);
78          } catch (JDOMException jdom) {
79              jdom.printStackTrace();
80              throw new RuntimeException("JDOM exception occurred. "+jdom.getMessage()); 
81          } catch (IOException io ) {
82              io.printStackTrace();
83              throw new RuntimeException("IO Exception occurred"); 
84          }
85         
86          return getStrategyListFromDocument(doc); 
87          
88      }
89      
90       /**
91       * Attempts to parse the given input stream as an XML file containing a well-formed
92       * list of strategies. If successful, a list of SeedStrategies corresponding
93       * to the strategies defined in the file is generated. This method will 
94       * be useful if you are attempting to load resources using getResourceAsStream(). 
95       * 
96       * @param stream An InputStream object corresponding to the XML file. 
97       * @return the list of strategies corresponding to the input stream
98       */
99      public static List<SeedStrategy> getStrategyListFromInputStream(InputStream stream){
100         
101         Document doc; 
102         SAXBuilder builder = new SAXBuilder(); 
103         builder.setValidation(true); 
104         builder.setFeature("http://apache.org/xml/features/validation/schema", true);
105         builder.setEntityResolver(new ClasspathEntityResolver());
106         try {
107             doc = builder.build(stream);
108             
109         } catch (JDOMException jdom) {
110             jdom.printStackTrace();
111             throw new RuntimeException("JDOM exception occurred"); 
112         } catch (IOException io ) {
113             io.printStackTrace();
114             throw new RuntimeException("IO Exception occurred"); 
115         }
116        
117         return getStrategyListFromDocument(doc); 
118     }
119     
120     private static List<SeedStrategy> getStrategyListFromDocument(Document doc) {
121         
122         Element listElement = doc.getRootElement(); 
123         List<SeedStrategy> ret = new ArrayList<SeedStrategy>(); 
124         
125         try {
126             for (Object o : listElement.getChildren("Strategy")){
127                 Element e = (Element) o; 
128                 SeedStrategy strat = new SeedStrategy(e.getAttributeValue("name")); 
129                 strat.putBadHitChisq(Double.valueOf(e.getChild("BadHitChisq").getText()));
130                 strat.putMaxChisq(Double.valueOf(e.getChild("MaxChisq").getText()));
131                 strat.putMaxDCA(Double.valueOf(e.getChild("MaxDCA").getText()));
132                 strat.putMaxZ0(Double.valueOf(e.getChild("MaxZ0").getText()));
133                 strat.putMinConfirm(Integer.valueOf(e.getChild("MinConfirm").getText()));
134                 strat.putMinHits(Integer.valueOf(e.getChild("MinHits").getText()));
135                 strat.putMinPT(Double.valueOf(e.getChild("MinPT").getText()));
136                 Element layers = e.getChild("Layers"); 
137                 for (Object ol : layers.getChildren("Layer")){
138                     Element l = (Element) ol; 
139                     String detName = l.getAttributeValue("detector_name"); 
140                     int layer_number = Integer.valueOf(l.getAttributeValue("layer_number")).intValue(); 
141                     SeedType type = SeedType.valueOf(l.getAttributeValue("type")); 
142                     BarrelEndcapFlag beflag = BarrelEndcapFlag.valueOf(l.getAttributeValue("be_flag")); 
143                     SeedLayer lyr = new SeedLayer(detName, layer_number, beflag, type); 
144                     strat.addLayer(lyr);
145                 }
146                 ret.add(strat);
147             }
148         } catch (NullPointerException npe) {
149             npe.printStackTrace();
150             throw new RuntimeException("NullPointerException thrown. See output for details. This probably means the XML is malformed"); 
151         }
152         
153         return ret; 
154     }
155     
156     
157     
158        /**
159      * Generates an XML file representing the given strategy list. 
160      * @param strategyList
161      * @param file file object where xml will be written
162      * @return a boolean denoting the success of the operation
163      */
164     
165     public static boolean writeStrategyListToFile(List<SeedStrategy> strategyList, File file){
166         return writeStrategyListToFile(strategyList, file, null);
167     }
168     
169     
170     /**
171      * Generates an XML file representing the given strategy list along with a top level comment. 
172      * @param strategyList
173      * @param file file object where xml will be written
174      * @param comment top-level comment 
175      * @return a boolean denoting the success of the operation
176      */
177     public static boolean writeStrategyListToFile(List<SeedStrategy> strategyList, File file, StrategyXMLMetadata meta) {
178         
179         Element listElement = new Element("StrategyList");
180         Document doc = new Document(listElement); 
181         Namespace xs = Namespace.getNamespace("xs", "http://www.w3.org/2001/XMLSchema-instance");
182         listElement.addNamespaceDeclaration(xs);
183         listElement.setAttribute(new Attribute("noNamespaceSchemaLocation","http://lcsim.org/recon/tracking/seedtracker/strategybuilder/strategies.xsd",xs));
184         if (meta!=null){
185             if (meta.comment!=null){
186                 listElement.addContent(new Comment(meta.comment)); 
187             }
188             if (meta.targetDetector!=null){
189                 listElement.addContent(new Element("TargetDetector").addContent(meta.targetDetector)); 
190             } else listElement.addContent(new Element("TargetDetector").addContent("None specified")); 
191         }  else listElement.addContent(new Element("TargetDetector").addContent("None specified")); 
192         
193         int counter = 1; 
194         for (SeedStrategy strat : strategyList){
195             listElement.addContent("\n");
196             listElement.addContent(new Comment(String.valueOf(counter++)));
197             Element strategy = new Element("Strategy");
198             
199             if (meta!=null && meta.strategyComments.containsKey(strat)){
200                 strategy.addContent(new Comment(meta.strategyComments.get(strat))); 
201             }
202             
203             strategy.setAttribute("name",strat.getName()); 
204             strategy.addContent(new Comment("Cutoffs"));
205             strategy.addContent(new Element("MinPT").addContent(String.valueOf(strat.getMinPT()))); 
206             strategy.addContent(new Element("MinHits").addContent(String.valueOf(strat.getMinHits())));
207             strategy.addContent(new Element("MinConfirm").addContent(String.valueOf(strat.getMinConfirm())));
208             strategy.addContent(new Element("MaxDCA").addContent(String.valueOf(strat.getMaxDCA()))); 
209             strategy.addContent(new Element("MaxZ0").addContent(String.valueOf(strat.getMaxZ0()))); 
210             strategy.addContent(new Element("MaxChisq").addContent(String.valueOf(strat.getMaxChisq())));
211             strategy.addContent(new Element("BadHitChisq").addContent(String.valueOf(strat.getBadHitChisq()))); 
212             
213             strategy.addContent(new Comment("Layers"));
214             Element layers = new Element("Layers"); 
215             for (SeedLayer lyr : strat.getLayerList()){
216                 Element layer = new Element("Layer"); 
217                 layer.setAttribute("type", lyr.getType().toString()); 
218                 layer.setAttribute("layer_number", String.valueOf(lyr.getLayer())); 
219                 layer.setAttribute("detector_name", lyr.getDetName()); 
220                 layer.setAttribute("be_flag", lyr.getBarrelEndcapFlag().toString()); 
221                 layers.addContent(layer); 
222             }
223             strategy.addContent(layers); 
224             listElement.addContent(strategy); 
225         }
226         try {
227             XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); 
228             FileWriter fw = new FileWriter(file); 
229             out.output(doc, fw);
230         } catch (Exception e){
231             e.printStackTrace();
232             return false; 
233         }
234         return true; 
235     }
236 }