001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.schedule;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025
026import lucee.commons.io.IOUtil;
027import lucee.commons.io.res.Resource;
028import lucee.commons.io.res.util.ResourceUtil;
029import lucee.commons.security.Credentials;
030import lucee.commons.security.CredentialsImpl;
031import lucee.runtime.Info;
032import lucee.runtime.config.Config;
033import lucee.runtime.engine.ThreadLocalPageContext;
034import lucee.runtime.op.Caster;
035import lucee.runtime.op.date.DateCaster;
036import lucee.runtime.type.dt.Date;
037import lucee.runtime.type.dt.DateImpl;
038import lucee.runtime.type.dt.DateTime;
039import lucee.runtime.type.dt.Time;
040import lucee.runtime.type.dt.TimeImpl;
041
042import org.apache.xerces.parsers.DOMParser;
043import org.apache.xml.serialize.OutputFormat;
044import org.apache.xml.serialize.XMLSerializer;
045import org.w3c.dom.Document;
046import org.w3c.dom.Element;
047import org.w3c.dom.Node;
048import org.w3c.dom.NodeList;
049import org.xml.sax.InputSource;
050import org.xml.sax.SAXException;
051
052
053/**
054 * 
055 */
056public final class StorageUtil {
057
058    /**
059         * create xml file from a resource definition
060         * @param file 
061     * @param resourcePath 
062         * @throws IOException
063         */
064        public void loadFile(File file,String resourcePath) throws IOException {
065                loadFile(ResourceUtil.toResource(file), resourcePath);
066        }
067    /**
068         * create xml file from a resource definition
069         * @param res 
070     * @param resourcePath 
071         * @throws IOException
072         */
073        public void loadFile(Resource res,String resourcePath) throws IOException {
074                res.createFile(true);
075                InputStream is = new Info().getClass().getResourceAsStream(resourcePath);
076        IOUtil.copy(is,res,true);
077        }
078
079    /**
080     * load a XML Document as DOM representation
081     * @param file XML File to load
082     * @return DOM Object
083     * @throws SAXException
084     * @throws IOException
085     */
086    public Document loadDocument(Resource file) throws SAXException, IOException {
087        DOMParser parser = new DOMParser();
088            
089                InputStream in = null;
090                try {
091                        in = file.getInputStream();
092                        InputSource source = new InputSource(in);
093                        parser.parse(source);
094                }
095                finally {
096                        IOUtil.closeEL(in);
097                }
098        
099        return parser.getDocument();
100    }
101    
102    public Document loadDocument(String content) throws SAXException, IOException {
103        DOMParser parser = new DOMParser();
104            
105                InputSource source = new InputSource(content);
106                parser.parse(source);
107                
108        return parser.getDocument();
109    }
110
111    /**
112     * return XML Element matching name
113     * @param list source node list
114     * @param key key to compare
115     * @param value value to compare
116     * @return matching XML Element
117     */
118    public Element getElement(NodeList list,String key, String value) {
119        int len=list.getLength();
120        for(int i=0;i<len;i++) {
121            Node n=list.item(i);
122            if(n instanceof Element) {
123                Element el = (Element)n;
124                if(el.getAttribute(key).equalsIgnoreCase(value)) return el;
125            }
126        }
127        return null;
128    }
129    
130        /**
131     * store loaded data to xml file
132         * @param doc 
133         * @param file 
134         * @throws IOException
135     */
136    public synchronized void store(Document doc,File file) throws IOException {
137        store(doc, ResourceUtil.toResource(file));
138    }
139    
140        /**
141     * store loaded data to xml file
142         * @param doc 
143         * @param res 
144         * @throws IOException
145     */
146    public synchronized void store(Document doc,Resource res) throws IOException {
147        OutputFormat format = new OutputFormat(doc, null, true);
148                format.setLineSeparator("\r\n");
149                format.setLineWidth(72);
150                
151                OutputStream os=null;
152                try {
153                        XMLSerializer serializer = new XMLSerializer(os=res.getOutputStream(), format);
154                        serializer.serialize(doc.getDocumentElement());
155                }
156                finally {
157                        IOUtil.closeEL(os);
158                }
159    }
160
161    
162    /**
163     * reads a XML Element Attribute ans cast it to a String
164     * @param el XML Element to read Attribute from it
165     * @param attributeName Name of the Attribute to read
166     * @return Attribute Value
167     */
168    public String toString(Element el,String attributeName) {
169        return el.getAttribute(attributeName);
170    }
171    
172    /**
173     * reads a XML Element Attribute ans cast it to a String
174     * @param el XML Element to read Attribute from it
175     * @param attributeName Name of the Attribute to read
176     * @param defaultValue if attribute doesn't exist return default value
177     * @return Attribute Value
178     */
179    public String toString(Element el,String attributeName, String defaultValue) {
180        String value = el.getAttribute(attributeName);
181        return (value==null)?defaultValue:value;
182    }
183
184    /**
185     * reads a XML Element Attribute ans cast it to a File
186     * @param el XML Element to read Attribute from it
187     * @param attributeName Name of the Attribute to read
188     * @return Attribute Value
189     */
190    /*public File toFile(Element el,String attributeName) {
191        String attributeValue = el.getAttribute(attributeName);
192        if(attributeValue==null || attributeValue.trim().length()==0) return null;
193        return new File(attributeValue);
194    }*/
195
196    public Resource toResource(Config config,Element el,String attributeName) {
197        String attributeValue = el.getAttribute(attributeName);
198        if(attributeValue==null || attributeValue.trim().length()==0) return null;
199        return config.getResource(attributeValue);
200    }
201    
202    /**
203     * reads a XML Element Attribute ans cast it to a boolean value
204     * @param el XML Element to read Attribute from it
205     * @param attributeName Name of the Attribute to read
206     * @return Attribute Value
207     */
208    public boolean toBoolean(Element el,String attributeName) {
209        return Caster.toBooleanValue(el.getAttribute(attributeName),false);
210    }
211    
212    /**
213     * reads a XML Element Attribute ans cast it to a boolean value
214     * @param el XML Element to read Attribute from it
215     * @param attributeName Name of the Attribute to read
216     * @param defaultValue if attribute doesn't exist return default value
217     * @return Attribute Value
218     */
219    public boolean toBoolean(Element el,String attributeName, boolean defaultValue) {
220        String value = el.getAttribute(attributeName);
221        if(value==null) return defaultValue;
222        return Caster.toBooleanValue(value,false);
223    }
224
225    /**
226     * reads a XML Element Attribute ans cast it to a int value
227     * @param el XML Element to read Attribute from it
228     * @param attributeName Name of the Attribute to read
229     * @return Attribute Value
230     */
231    public int toInt(Element el,String attributeName) {
232        return Caster.toIntValue(el.getAttribute(attributeName),Integer.MIN_VALUE);
233    }
234    
235    public long toLong(Element el,String attributeName) {
236        return Caster.toLongValue(el.getAttribute(attributeName),Long.MIN_VALUE);
237    }
238    
239    /**
240     * reads a XML Element Attribute ans cast it to a int value
241     * @param el XML Element to read Attribute from it
242     * @param attributeName Name of the Attribute to read
243     * @param defaultValue if attribute doesn't exist return default value
244     * @return Attribute Value
245     */
246    public int toInt(Element el,String attributeName, int defaultValue) {
247        String value = el.getAttribute(attributeName);
248        if(value==null) return defaultValue;
249        int intValue=Caster.toIntValue(value,Integer.MIN_VALUE);
250        if(intValue==Integer.MIN_VALUE) return defaultValue;
251        return intValue;
252    }
253
254    /**
255     * reads a XML Element Attribute ans cast it to a DateTime Object
256     * @param config 
257     * @param el XML Element to read Attribute from it
258     * @param attributeName Name of the Attribute to read
259     * @return Attribute Value
260     */
261    public DateTime toDateTime(Config config, Element el,String attributeName) {
262        String str=el.getAttribute(attributeName);
263        if(str==null) return null;
264        return DateCaster.toDateAdvanced(str,ThreadLocalPageContext.getTimeZone(config),null);
265    }
266    
267    /**
268     * reads a XML Element Attribute ans cast it to a DateTime
269     * @param el XML Element to read Attribute from it
270     * @param attributeName Name of the Attribute to read
271     * @param defaultValue if attribute doesn't exist return default value
272     * @return Attribute Value
273     */
274    public DateTime toDateTime(Element el,String attributeName, DateTime defaultValue) {
275        
276        String value = el.getAttribute(attributeName);
277        if(value==null) return defaultValue;
278        DateTime dtValue=Caster.toDate(value,false,null,null);
279        if(dtValue==null) return defaultValue;
280        return dtValue;
281    }
282
283    /**
284     * reads a XML Element Attribute ans cast it to a Date Object
285     * @param el XML Element to read Attribute from it
286     * @param attributeName Name of the Attribute to read
287     * @return Attribute Value
288     */
289    public Date toDate(Config config,Element el,String attributeName) {
290        DateTime dt = toDateTime(config,el,attributeName);
291        if(dt==null) return null;
292        return new DateImpl(dt);
293    }
294    
295    /**
296     * reads a XML Element Attribute ans cast it to a Date
297     * @param el XML Element to read Attribute from it
298     * @param attributeName Name of the Attribute to read
299     * @param defaultValue if attribute doesn't exist return default value
300     * @return Attribute Value
301     */
302    public Date toDate(Element el,String attributeName, Date defaultValue) {
303        return new DateImpl(toDateTime(el,attributeName,defaultValue));
304    }
305
306    /**
307     * reads a XML Element Attribute ans cast it to a Time Object
308     * @param config 
309     * @param el XML Element to read Attribute from it
310     * @param attributeName Name of the Attribute to read
311     * @return Attribute Value
312     */
313    public Time toTime(Config config, Element el,String attributeName) {
314        DateTime dt = toDateTime(config,el,attributeName);
315        if(dt==null) return null;
316        return new TimeImpl(dt);
317    }
318    
319    /**
320     * reads a XML Element Attribute ans cast it to a Date
321     * @param el XML Element to read Attribute from it
322     * @param attributeName Name of the Attribute to read
323     * @param defaultValue if attribute doesn't exist return default value
324     * @return Attribute Value
325     */
326    public Time toTime(Element el,String attributeName, Time defaultValue) {
327        return new TimeImpl(toDateTime(el,attributeName,defaultValue));
328    }
329
330    /**
331     * reads 2 XML Element Attribute ans cast it to a Credential
332     * @param el XML Element to read Attribute from it
333     * @param attributeUser Name of the user Attribute to read
334     * @param attributePassword Name of the password Attribute to read
335     * @return Attribute Value
336     */
337    public Credentials toCredentials(Element el,String attributeUser, String attributePassword) {
338        String user = el.getAttribute(attributeUser);
339        String pass = el.getAttribute(attributePassword);
340        if(user==null) return null;
341        if(pass==null)pass="";
342        return CredentialsImpl.toCredentials(user,pass);
343    }
344
345    /**
346     * reads 2 XML Element Attribute ans cast it to a Credential
347     * @param el XML Element to read Attribute from it
348     * @param attributeUser Name of the user Attribute to read
349     * @param attributePassword Name of the password Attribute to read
350     * @param defaultCredentials
351     * @return Attribute Value
352     */
353    public Credentials toCredentials(Element el,String attributeUser, String attributePassword, Credentials defaultCredentials) {
354        String user = el.getAttribute(attributeUser);
355        String pass = el.getAttribute(attributePassword);
356        if(user==null) return defaultCredentials;
357        if(pass==null)pass="";
358        return CredentialsImpl.toCredentials(user,pass);
359    }
360
361    /**
362     * sets a string value to a XML Element
363     * @param el Element to set value on it
364     * @param key key to set
365     * @param value value to set
366     */
367    public void setString(Element el, String key, String value) {
368        if(value!=null)el.setAttribute(key,value);
369    }
370
371    /**
372     * sets a file value to a XML Element
373     * @param el Element to set value on it
374     * @param key key to set
375     * @param value value to set
376     */
377    public void setFile(Element el, String key, File value) {
378        setFile(el, key, ResourceUtil.toResource(value));
379    }
380
381    /**
382     * sets a file value to a XML Element
383     * @param el Element to set value on it
384     * @param key key to set
385     * @param value value to set
386     */
387    public void setFile(Element el, String key, Resource value) {
388        if(value!=null && value.toString().length()>0)el.setAttribute(key,value.getAbsolutePath());
389    }
390
391    /**
392     * sets a boolean value to a XML Element
393     * @param el Element to set value on it
394     * @param key key to set
395     * @param value value to set
396     */
397    public void setBoolean(Element el, String key, boolean value) {
398        el.setAttribute(key,String.valueOf(value));
399    }
400
401    /**
402     * sets a int value to a XML Element
403     * @param el Element to set value on it
404     * @param key key to set
405     * @param value value to set
406     */
407    public void setInt(Element el, String key, int value) {
408        el.setAttribute(key,String.valueOf(value));
409    }
410
411    /**
412     * sets a datetime value to a XML Element
413     * @param el Element to set value on it
414     * @param key key to set
415     * @param value value to set
416     */
417    public void setDateTime(Element el, String key, DateTime value) {
418        if(value!=null){
419            String str = value.castToString(null);
420            if(str!=null)el.setAttribute(key,str);
421        }
422    }
423    
424    /**
425     * sets a Credentials to a XML Element
426     * @param el
427     * @param username
428     * @param password
429     * @param credentials
430     */
431    public void setCredentials(Element el, String username, String password, Credentials c) {
432        if(c==null) return;
433        if(c.getUsername()!=null)el.setAttribute(username,c.getUsername());
434        if(c.getPassword()!=null)el.setAttribute(password,c.getPassword());
435    }
436}