View Javadoc

1   package net.sf.provisioner.config;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileNotFoundException;
6   import java.io.IOException;
7   import java.io.InputStream;
8   import java.util.ArrayList;
9   import java.util.Collection;
10  import java.util.Hashtable;
11  import java.util.Iterator;
12  import java.util.List;
13  
14  import net.sf.provisioner.responses.Response;
15  import net.sf.provisioner.utils.PathHelper;
16  
17  import org.apache.log4j.Logger;
18  import org.jdom.Document;
19  import org.jdom.Element;
20  import org.jdom.input.SAXBuilder;
21  
22  
23  /**
24   * Esta clase representa a un elemento de red y sus datos
25   * de acceso. Tiene un nombre que puede ser el numero de IP, 
26   * un tipo que sirve para determinar que interfaz se debe 
27   * utilizar para conectarse al mismo, usuario y password
28   * para aquellos elementos de red que requieran iniciar una
29   * sesion, clave de autenticacion para aquellos elementos de 
30   * red que utilicen este mecanismo de seguridad, y patrones
31   * de exito o fracaso para los elementos de red basados en 
32   * protocolo Telnet.
33   * 
34   *             
35   * @version $Revision: 1.1.2.1 $, $Date: 2007/11/12 01:57:22 $
36   * @author Gonzalo Espert
37   */
38  public class NetworkElement {
39  	
40  	
41  	/** Logger for this class and subclasses */
42  	Logger logger = Logger.getLogger(getClass());
43  	
44  	public String name = new String();
45  	public String port = new String();
46  	public String type = new String();
47  	public String user = "user";
48  	public String password = "password";
49  	public String authKey = "authKey";
50  	public String bin = "command";
51  	public String create = "create";
52  	public String delete = "delete";
53  	public String enable = "enable";
54  	public String disable = "disable";
55  	public String loginPrompt = "ogin username:";
56  	public String systemPrompt = ">";
57  	public String sudoPassword = "";
58  	public String sudoPasswordPrompt = "Password:";
59  	public String loginErrorSecuence = "Failed";
60  	public boolean sendInitialCRLF = false;
61  	public String parameter1 = "";
62  	public String parameter2 = "";
63  	public String parameter3 = "";
64  	public String parameter4 = "";
65  	public String parameter5 = "";
66  	
67  	public Hashtable responses = new Hashtable();
68  	
69  	String configPath;
70  	
71  	/**
72       * Constructor de un elemento de red en blanco.
73       * 
74       */
75  	public NetworkElement() {}
76  	
77  	/**
78       * Creates a NetworkElement with its properties populated using
79       * information in an XML file.
80       * 
81       * @param neName a name used to construct a reference to an XML file
82       * in Provisioner's config. file location.
83       * e.g. "intraway" is translated to "config/intraway.xml".
84       * 
85       */
86  	public NetworkElement(String neName) throws FileNotFoundException {
87  		this(new File(neName + ".xml"));
88  	}
89  
90      /**
91       * Creates a NetworkElement with its properties populated using 
92       * information in an XML file.
93       * 
94       * @param configFile an XML configuration file (see asterisk.xml and 
95       * intraway.xml for examples of the format.) 
96       */
97      public NetworkElement(File xmlConfig) throws FileNotFoundException {
98      	this(new FileInputStream(xmlConfig));    	    
99      }
100     
101     public NetworkElement(InputStream xmlConfig) {
102     	
103     	try {
104     	    Document d = new SAXBuilder().build(xmlConfig); 
105             List children = d.getContent();  
106             Iterator iterator = children.iterator();
107             while (iterator.hasNext()) {
108                 Element child = (Element) iterator.next();
109                 getParameters(child);
110             }
111         } catch (Exception e) {
112             logger.fatal("Error reading network element configuration file " + name);
113             e.printStackTrace();
114         }            
115     }
116 
117 	/**
118      * Metodo utilizado para obtener los parametros del elemento de red.
119      * 
120      * @param current
121      * 			Elemento del nodo del archivo xml
122      * 
123      * @param tipoOperacion
124      * 			               
125      */
126 	void getParameters(Element current) {
127 		
128 	    for (Element child : filterChildParameters(current)) {
129             String paramName = child.getAttributeValue("name").toLowerCase();
130             String value     = child.getAttributeValue("value");
131             
132 	    	if (paramName.equals("host"      )) name     = value; 
133 	    	if (paramName.equals("type"      )) type     = value;
134 	    	if (paramName.equals("username"  )) user     = value;
135 	    	if (paramName.equals("password"  )) password = value;
136 	    	if (paramName.equals("password_sudo")) {
137 	    		sudoPassword = value;
138 	    	}
139 	    	if (paramName.equals("password_authorisation")) {
140 	    		authKey = value;
141 	    	}
142 
143 	    	if (paramName.equals("bin"       )) bin      = value;
144 	    	if (paramName.equals("create"    )) create   = value;
145 	    	if (paramName.equals("delete"    )) delete   = value;
146 	    	if (paramName.equals("enable"    )) enable   = value;
147 	    	if (paramName.equals("disable"   )) disable  = value;
148 	    	if (paramName.equals("errorlogin")) loginErrorSecuence = value;
149 	    	
150 	    	/* Cargamos los parametros a enviar */
151 	    	if (paramName.equals("$1")) parameter1 = value;
152 	    	if (paramName.equals("$2")) parameter2 = value;
153 	    	if (paramName.equals("$3")) parameter3 = value;
154 	    	if (paramName.equals("$4")) parameter4 = value;
155 	    	if (paramName.equals("$5")) parameter5 = value;
156 	    	
157 	    	/* Cargamos las respuestas posibles del elemento de red de esta ruta */
158 	    	if (paramName.equals("responses")) {
159 	    		storePossibleResponses(child.getAttributeValue("value"));
160 	        }
161 	    }  
162 	}
163 	
164 	protected Collection<Element> filterChildParameters(Element currentElement) {
165 		List          children = currentElement.getChildren();
166 		List<Element> params   = new ArrayList<Element>();
167         for (Object c : children) {
168 		    Element child = (Element) c;
169 		    if (child.getName().equalsIgnoreCase("parameter")) {
170 		    	params.add(child);
171 		    }
172         }
173         return params;
174 	}
175 	
176 	/**
177      * Metodo utilizado para obtener las respuestas posibles del elemento de red.
178      * 
179      * @param archivo
180      * 			Nombre del archivo donde residen las respuestas posibles
181      * 			para este tipo de elemento de red
182      * 			               
183      */
184 	void storePossibleResponses(String responses) {
185 		
186 		/*File configFile = new File(responses);        
187 		if (!configFile.exists()) {
188             configFile = new File("config/" + responses + ".xml");
189         }
190         if (!configFile.exists()) {
191       	    Exception e = new FileNotFoundException("NetworkElement's config. not found: " + configFile);
192       	    logger.fatal(e);
193         	// TODO: returning isn't the best course of action here.
194         }
195         if (!configFile.canRead()) {
196         	Exception e = new IOException("NetworkElement's config. is not readable: " + configFile);
197         	logger.fatal(e);
198         	// TODO: returning isn't the best course of action here. 
199         	return;
200         }*/
201         
202 		InputStream configFile = null;
203 		try {
204 			configFile = PathHelper.pathToStream(responses);
205 		} catch (IOException ioe) {
206 			/* Failure is acceptable here.  It may be the 
207 			 * user wants the system to use the default
208 			 * config. dir. */ 
209 		}
210 		
211 		if (configFile == null) {
212 			try {
213 				configFile = PathHelper.pathToStream(this.configPath + responses + ".xml");
214 			} catch (IOException ioe) {
215 				logger.fatal("Couldn't find responses for '" + responses + "'", ioe);
216 				// TODO: is returning enough?  Should we throw something?
217 				return;
218 			}
219 		}
220 
221 		if (configFile == null) {
222 			logger.fatal("Couldn't find responses for '" + responses + "'");
223 			// TODO: is returning enough?  Should we throw something?
224 			return;
225 		}
226 		
227 		/* Recorremos el archivo xml y cargamos cada una de las
228 		 * respuestas posibles
229 		 */
230 		try {
231 			  
232 		      Document d = new SAXBuilder().build(configFile); 
233 		      List children = d.getContent();  
234 			  Iterator iterator = children.iterator();
235 			  while (iterator.hasNext()) {
236 			      Element child = (Element) iterator.next();
237 			      getResponses(child, "");
238 			  }
239 	    } catch (Exception e) {
240 	    	Exception wrapper = new Exception(
241 	    			"Error reading possible responses from configuration file "+ responses,
242 	    			e
243 	    	);
244 	    	logger.fatal(wrapper);	    	
245 	    }
246 	}
247     
248 	/**
249      * Metodo utilizado para obtener las respuestas posibles del elemento de red.
250      * 
251      * @param current
252      * 			Elemento del nodo del archivo xml
253      * @param operationType
254      * 			               
255      */
256 	void getResponses(Element current, String operationType) {
257 		
258 	    List children = current.getChildren();
259 	    Iterator iterator = children.iterator();
260 	    while (iterator.hasNext()) {
261 	      Element child = (Element) iterator.next();
262 	      if (child.getName().equalsIgnoreCase("operation"))
263 	    	  operationType = child.getAttributeValue("type");;
264 	      if (child.getName().equalsIgnoreCase("response")) {
265 	    	  
266 	    	  Response respuestaPosible = new Response();
267 	    	  respuestaPosible.tipoOperacion = operationType; 	    	  
268 	    	  respuestaPosible.result = child.getAttributeValue("result");
269 	    	  if (child.getAttributeValue("success").equalsIgnoreCase("yes")) respuestaPosible.successfull = true;
270 	    	  respuestaPosible.errorStr = child.getAttributeValue("respond");
271 	    	  if (child.getAttributeValue("retry").equalsIgnoreCase("yes")) respuestaPosible.retry = true;
272 			  
273 	    	  int i = this.responses.size();
274 	    	  this.responses.put(new Integer(i++), respuestaPosible);
275 	    	  
276 	      }  
277 	      getResponses(child, operationType);
278 	    }   
279 	}
280 	
281 	public String toString() {
282 		return "host=" + name + ":" + port + ", type=" + type + ", user=" + user;
283 	}
284 
285 	/**
286 	 * @return the configPath
287 	 */
288 	public String getConfigPath() {
289 		return configPath;
290 	}
291 
292 	/**
293 	 * @param configPath the configPath to set
294 	 */
295 	public void setConfigPath(String configPath) {
296 		this.configPath = configPath;
297 	}
298 }