source: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/Admin.java @ 998

Last change on this file since 998 was 998, checked in by gaba, 13 years ago

log4j

File size: 10.0 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.util.Properties;
10
11import javax.xml.parsers.DocumentBuilder;
12import javax.xml.parsers.DocumentBuilderFactory;
13import javax.xml.parsers.ParserConfigurationException;
14
15import org.w3c.dom.Document;
16import org.xml.sax.SAXException;
17
18import net.sf.json.JSON;
19import net.sf.json.JSONSerializer;
20import net.sf.json.xml.XMLSerializer;
21
22
23import eu.clarin.cmdi.mdservice.model.Query;
24import org.apache.log4j.Logger;
25import org.apache.log4j.xml.DOMConfigurator;
26
27/**
28 * Helper class, main-class to run as command-line java-app for testing
29 *
30 * @author vronk
31 *
32 */
33
34public class Admin {
35
36       
37        private static String config_path = "mdservice.properties";
38        private static Properties  config;
39        public  static Logger log = Logger.getLogger("Admin.class");
40       
41        public static String FATAL = "fatal";
42        public static String ERROR = "error";
43        public static String WARN = "warn";
44        public static String INFO = "info";
45        public static String DEBUG = "debug";
46        public static String TRACE = "trace";
47       
48        public static void main(String[] args) {               
49
50                //log = Logger.getLogger(Admin.class);
51                //DOMConfigurator.configure("log4j.xml");
52                //log.debug("WELCOME LOG4J");
53               
54                //String dirpath = "C:/apps/ApacheTomcat/webapps/mdservice/schemas";
55               
56                //CMDRegistryProxy cmdreg = new CMDRegistryProxy ();
57               
58                //cmdreg.readCompRegistryFromDir(dirpath);
59               
60                //System.out.println(cmdreg.listComponents());
61
62                testJSON();
63               
64                //loadConfig(config_path);
65               
66                /*
67                //Query q = new Query("dc.title=dino or dinosaur", Query.RECORDSET);
68                //Query q = new Query("( ( Date any 2005 ) or ( Date any 2001 ) ) and ( ( Description any part ) )", Query.RECORDSET);
69                Query q = new Query("( ( Date any 2005 ) or ( Country = \"United States\" ) ) and ( ( Description any part ) )", Query.RECORDSET);
70                //System.out.println(q.toXCQL());
71                System.out.println(q.toXPath());
72                */
73                //Query q = new Query("CMD", "cmdIndex");
74               
75                //try {
76                       
77                        /*
78
79                        Query q = new Query("Title=the", Query.RECORDSET, "olac" );
80                        q.execute();
81                 
82                 InputStream inputStream = q.getResult().getResultStream("htmltable");
83        */       
84                //MDTransformer.getMDTransformer(q.getResult().getResultStream("xml"),"model2html",);
85                /*
86                        MDRepoProxyAction mrpa = new MDRepoProxyAction();
87                        // crp.setCompname("cmdi-corpus-aac2");
88                        mrpa.setQ("Title any the");
89                        mrpa.setCollection("olac");
90                        mrpa.setActionkey("recordset");
91                        mrpa.setFormat("xml");
92                        mrpa.execute();
93                        InputStream inputStream = mrpa.getInputStream();
94                       
95                        Cache.getCache().putInCache("test", inputStream);
96                        */
97                       
98                        /*
99                        DCRProxyAction dcr = new DCRProxyAction();
100                        dcr.setDc("1253");
101                        InputStream     inputStream = MDTransformer.getMDTransformer().transformXML(dcr.getSourceStream(), "dcif2htmldiv");             
102
103                        */
104                        /*
105                        CompRegistryProxyAction crp = new CompRegistryProxyAction ();
106                        // crp.setCompname("cmdi-corpus-aac2");
107                        crp.setFormat("htmllist");
108                        crp.execute();
109                        InputStream inputStream = crp.getInputStream();
110        */
111                       
112                //      InputStream inputStream = MDRepositoryProxy.getMDRepo().getCollections(null);
113                       
114                        //copyStreams(inputStream,System.out);
115                        /*
116                } catch (IOException e1) {
117                        // TODO Auto-generated catch block
118                        e1.printStackTrace();
119                } catch (InterruptedException e1) {
120                        // TODO Auto-generated catch block
121                        e1.printStackTrace();
122                }       catch (Exception e) {
123                        Admin.notifyUser(e.getMessage());
124                }
125        */
126                       
127                //System.out.println(res.xmlString());
128                //System.out.println(res.toFormat("MODEL2VIEW"));
129               
130               
131                //System.out.println(res.xmlString());
132               
133//              MDRepositoryProxy.getMDRepo().queryModel("CMD", System.out);
134               
135                //testParse();
136               
137                /*
138                 * CMDComponent testcomp = new CMDComponent("C:/apps/ApacheTomcat/webapps/mdservice/schemas/component-olac.xml");
139                 
140                System.out.println(testcomp.name());
141                System.out.println("components:");
142                for (Iterator it = testcomp.components().iterator();
143                it.hasNext();) {
144                        CMDComponentType comp = (CMDComponentType)it.next();
145                        System.out.println(comp.getName() + " " + comp.getConceptLink() + "\n");
146                       
147                }
148
149                System.out.println("elements:");
150                for (Iterator it = testcomp.elements().iterator();
151                it.hasNext();) {
152                        CMDElementType comp = (CMDElementType)it.next();
153                        System.out.println(comp.getName() + " " + comp.getConceptLink() + "\n");
154                       
155                }
156                */
157        }
158
159        /*
160        public static void testCache (InputStream instream) {
161                String myKey = "myKey2";
162                String myValue;
163                int myRefreshPeriod = 1000;
164                GeneralCacheAdministrator admin = new GeneralCacheAdministrator();
165                System.out.print(admin.isMemoryCaching());
166                System.out.print(admin.getProperty("cache.path"));
167               
168                try {
169                    // Get from the cache
170                    myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);
171                    System.out.println("value from cache:" + myValue);
172                } catch (NeedsRefreshException nre) {
173                    try {
174                        // Get the value (probably from the database)
175        //              myValue = "This is the content retrieved.";
176                        // Store in the cache
177                        admin.putInCache(myKey, instream.toString());
178                        System.out.println("freshfromcache: " );
179                        System.out.println(admin.getFromCache(myKey, myRefreshPeriod));
180                        //copyStreams((InputStream) admin.getFromCache(myKey, myRefreshPeriod),System.out);
181                    } catch (Exception ex) {
182                        // We have the current content if we want fail-over.
183//                      myValue = (String) nre.getCacheContent();
184                        // It is essential that cancelUpdate is called if the
185                        // cached content is not rebuilt
186                        admin.cancelUpdate(myKey);
187                    }
188                //System.out.println(myValue);
189        }
190        */
191        public static void loadConfig() {
192                loadConfig(config_path);
193        }
194
195        public static void loadConfig(String configPath) {
196               
197                System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
198                InputStream config_file;
199                 
200                try {                   
201                        config_file = Admin.class.getClassLoader().getResourceAsStream(configPath);
202                       
203//                   System.out.println(config_file);
204                        if (config_file == null) {
205                             Admin.notifyUser("CONFIGURATION ERROR: Properties file not found!");
206                        } else {
207                               
208                                System.out.println("Reading configuration from: " + Admin.class.getClassLoader().getResource(configPath));
209                                //config_file = new FileInputStream(configPath);
210                                config = new Properties();
211                                config.load(config_file);       
212                        }
213                       
214                } catch (FileNotFoundException e) {
215                        // TODO Auto-generated catch block
216                        e.printStackTrace();
217                } catch (IOException e) {
218                        // TODO Auto-generated catch block
219                        e.printStackTrace();
220                } 
221        }
222       
223       
224        public static Properties getConfig() {
225                if (config==null)  {
226                        loadConfig(config_path);
227                }
228                return config;
229        }
230
231        public static void notifyUser(String msg ) {
232                notifyUser(msg, Admin.DEBUG);
233        }
234        public static void notifyUser(String msg, String type ) {
235                if (type.equals(Admin.FATAL)) {
236                        log.fatal(msg);
237                }
238                if (type.equals(Admin.ERROR)) {
239                        log.error(msg);
240                }
241                if (type.equals(Admin.WARN)) {
242                        log.warn(msg);
243                }
244                if (type.equals(Admin.INFO)) {
245                        log.info(msg);
246                }
247                if (type.equals(Admin.DEBUG)) {
248                        log.debug(msg);
249                }
250                if (type.equals(Admin.TRACE)) {
251                        log.trace(msg);
252                }
253                //System.out.println(msg);
254        }
255
256
257        public static InputStream loadFile(String path) {
258               
259                InputStream file=null;
260                 
261                try {                   
262                        file = Admin.class.getClassLoader().getResourceAsStream(path);
263                       
264//                   System.out.println(config_file);
265                        if (file == null) {
266                             Admin.notifyUser("File not found!: " + path);
267                        } else {
268                               
269                                System.out.println("Reading in: " + Admin.class.getClassLoader().getResource(path));
270                                //config_file = new FileInputStream(configPath);
271                //              Properties test = new Properties();
272                        //      test.load(file);
273                        }
274                        /*
275                } catch (FileNotFoundException e) {
276                        // TODO Auto-generated catch block
277                        e.printStackTrace();
278                        */
279                }   catch (Exception e) {
280                        // TODO Auto-generated catch block
281                        e.printStackTrace();
282                } 
283               
284                return file;
285        }
286       
287       
288        public static Document getXMLDocument(String path) {
289                Document retdoc=null;
290                try {
291                       
292                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
293                DocumentBuilder docBuilder;
294                        try {
295                                docBuilder = docFactory.newDocumentBuilder();               
296                                try {
297                                        Admin.notifyUser("trying to read from:" + path);
298                                        InputStream xmlstream =  loadFile(path);                                       
299                                        //retdoc= docBuilder.parse(fname);
300                                        retdoc= docBuilder.parse(xmlstream);
301                                        Admin.notifyUser("read in:" + retdoc);
302                                } catch (SAXException e) {
303                                                // TODO Auto-generated catch block
304                                                Admin.notifyUser(e.getMessage());
305                                                e.printStackTrace();
306                                }
307                        } catch (ParserConfigurationException e) {
308                                        // TODO Auto-generated catch block
309                                Admin.notifyUser(e.getMessage());
310                                        e.printStackTrace();
311                        }
312                       
313                 
314            }  catch (IOException ex){
315                //Admin.notifyUser("initCacheCounter:" + ex.toString());
316                ex.printStackTrace();
317            } catch (Exception e) {
318                Admin.notifyUser("Admin.getXMLDocument():" + e.getMessage());
319            }
320            return retdoc;
321        }
322       
323
324       
325public static void copyStreams (InputStream in, OutputStream out) throws IOException, InterruptedException {           
326               
327                byte[] buffer = new byte[1024];
328                int len = in.read(buffer);
329                while (len != -1) {
330                    out.write(buffer, 0, len);
331                    len = in.read(buffer);
332                    if (Thread.interrupted()) {
333                        throw new InterruptedException();
334                    }
335                }
336        }
337       
338public static void writeToFile (String path, InputStream in) { 
339        try
340            {
341                        File f=new File(path);     
342                    OutputStream out=new FileOutputStream(f);
343                    copyStreams(in,out);           
344                    out.close();           
345            }
346            catch (Exception e){
347                Admin.notifyUser("ERROR writeToFile");
348                e.printStackTrace();
349            }
350        }
351
352public static void testJSON() {
353Admin.notifyUser("JSON TEST");
354    String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
355    Query q = new Query("dc.title=dino or dinosaur", Query.RECORDSET);
356        JSON json = JSONSerializer.toJSON( str); 
357        XMLSerializer xmlSerializer = new XMLSerializer(); 
358        String xml = xmlSerializer.write( json ); 
359        Admin.notifyUser(xml);
360}
361
362}
363
364
Note: See TracBrowser for help on using the repository browser.