Package org.atomojo.server

Source Code of org.atomojo.server.Configuration$Server

/*
* Configuration.java
*
* Created on June 18, 2007, 3:01 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package org.atomojo.server;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.atomojo.app.client.Link;
import org.atomojo.app.client.LinkSet;
import org.atomojo.www.util.ProxyApplication;
import org.infoset.xml.Document;
import org.infoset.xml.DocumentLoader;
import org.infoset.xml.Element;
import org.infoset.xml.Name;
import org.infoset.xml.XMLException;
import org.infoset.xml.sax.SAXDocumentLoader;
import org.infoset.xml.util.XMLWriter;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.resource.Directory;
import org.restlet.resource.Finder;
import org.restlet.resource.ServerResource;
import org.restlet.routing.Extractor;
import org.restlet.routing.Filter;
import org.restlet.routing.Redirector;
import org.restlet.routing.Router;
import org.restlet.routing.Template;
import org.xml.sax.InputSource;

/**
*
* @author alex
*/
public class Configuration
{
   static Logger LOG = Logger.getLogger(Configuration.class.getName());
  
   public static final URI NAMESPACE = URI.create("http://www.atomojo.org/V/Server/2011/1/0");
   static final Name COMPONENT = Name.create(NAMESPACE,"component");
   static final Name CLIENT = Name.create(NAMESPACE,"client");
   static final Name SERVER = Name.create(NAMESPACE,"server");
   static final Name LIBRARY = Name.create(NAMESPACE,"library");
   static final Name AUTOCONF = Name.create(NAMESPACE,"autoconf");
   static final Name HOST = Name.create(NAMESPACE,"host");
   static final Name LINK = Name.create(NAMESPACE,"link");
   static final Name PARAMETER = Name.create(NAMESPACE,"parameter");
   static final Name CONTEXT = Name.create(NAMESPACE,"context");
   static final Name LOG_E = Name.create(NAMESPACE,"log");
   static final Name DEFINE = Name.create(NAMESPACE,"define");
   static final Name ROUTE = Name.create(NAMESPACE,"route");
   static final Name FILTER = Name.create(NAMESPACE,"filter");
   static final Name ROUTER = Name.create(NAMESPACE,"router");
   static final Name MATCH = Name.create(NAMESPACE,"match");
   static final Name ATTRIBUTE = Name.create(NAMESPACE,"attribute");
   static final Name NEXT = Name.create(NAMESPACE,"next");
   static final Name DEFAULT = Name.create(NAMESPACE,"default");
   static final Name CONTENT = Name.create(NAMESPACE,"content");
   static final Name REDIRECT = Name.create(NAMESPACE,"redirect");
   static final Name KEYSTORE = Name.create(NAMESPACE,"keystore");
   static final Name INCLUDE = Name.create(NAMESPACE,"include");

   static DocumentBuilder docBuilder = null;
   static {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      try {
         docBuilder = factory.newDocumentBuilder();
      } catch (Exception ex) {
         LOG.log(Level.SEVERE,"Cannot configure document builder.",ex);
      }
   }

  
   static Restlet getRestletInstance(Context context, Class targetClass)
      throws InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException
   {
      try {
         Constructor<Restlet> makeit = targetClass.getConstructor(Context.class);
         return makeit.newInstance(context);
      } catch (NoSuchMethodException ex) {
         Constructor<Restlet> makeit = targetClass.getConstructor();
         Restlet r = makeit.newInstance();
         r.setContext(context);
         return r;
      }
   }
  
   static boolean isServerResource(Class targetClass) {
      return ServerResource.class.isAssignableFrom(targetClass);
   }
  
   public class Server {
      String addr;
      int port;
      Protocol protocol;
      Map<String,Host> hosts;
      LinkSet links;
     
      public Server(String addr,int port,Protocol protocol)
      {
         this.addr = addr;
         this.port = port;
         this.protocol = protocol;
         this.hosts = new HashMap<String,Host>();
         this.links = new LinkSet();
      }
     
      public String getKey() {
         return this.addr+":"+this.port;
      }
     
      public String getAddress() {
         return addr;
      }
     
      public int getPort() {
         return port;
      }
     
      public Protocol getProtocol() {
         return protocol;
      }
     
      public Map<String,Host> getHosts() {
         return hosts;
      }
     
      public LinkSet getLinks() {
         return links;
      }
     
     
   }

   public class Host {
      String name;
      String internalName;
      Map<String,String> logConf;
      Element conf;
      LinkSet linkSet;
     
      Class getTargetClass(Element child) {
         String ref = child.getAttributeValue("ref");
         String className = child.getAttributeValue("class");
         if (ref!=null && className!=null) {
            ClassLoader loader = loaders.get(ref.trim());
            if (loader==null) {
               LOG.severe("Cannot find a definition for '"+ref+"'");
               return null;
            }
            LOG.fine("ClassLoader: "+loader);
            try {
               return loader.loadClass(className);
            } catch (Exception ex) {
               LOG.log(Level.SEVERE,"Cannot load class '"+className+"' via "+ref,ex);
            }
         } else if (ref!=null) {
            Class def = definitions.get(ref.trim());
            if (def==null) {
               LOG.severe("Cannot find a definition for '"+ref+"'");
            }
            return def;
         } else if (className!=null) {
            try {
               return this.getClass().getClassLoader().loadClass(className.trim());
            } catch (Exception ex) {
               LOG.log(Level.SEVERE,"Cannot load class '"+className+"'",ex);
            }
         }
         return null;
      }
     
      public Host(String name, Element conf)
      {
         this(name,null,conf);
      }

      public Host(String name,String internalName,Element conf)
      {
         this.name = name;
         this.internalName = internalName;
         this.conf = conf;
         this.logConf = new HashMap<String,String>();
         Iterator<Element> logs = conf.getElementsByName(LOG_E);
         if (logs.hasNext()) {
            Element logE = logs.next();
            for (Name attName : logE.getAttributes().keySet()) {
               logConf.put(attName.toString(),logE.getAttributeValue(attName));
            }
         }
         this.linkSet = new LinkSet();
         Iterator<Element> links = conf.getElementsByName(LINK);
         while (links.hasNext()) {
            Element linkE = links.next();
            String href = linkE.getAttributeValue("href");
            if (href!=null) {
               URI tlocation = linkE.getBaseURI().resolve(href);
               String mtype = linkE.getAttributeValue("type");
               Link l = new Link(linkE.getAttributeValue("rel"),mtype==null ? null : MediaType.valueOf(mtype),tlocation);
               l.setIdentity(linkE.getAttributeValue("username"),linkE.getAttributeValue("password"));
               if (l.getRelation()!=null) {
                  linkSet.put(l.getRelation(),l);
               }
            }
         }
      }
     
      public String getName() {
         return name;
      }

      public String getInternalName() {
         return internalName;
      }

      public Map<String,String> getLogConfiguration() {
         return logConf;
      }
     
      public LinkSet getLinks() {
         return linkSet;
      }
     
      public void attach(Router router) {
         LOG.fine("attach() context: "+router.getContext());
         loadContext(router.getContext(),conf);
         Iterator<Element> elements = conf.getElementChildren();
         while (elements.hasNext()) {
            attach(router,elements.next(),false);
         }
      }
     
      public void attachNext(Filter filter,Element child) {
         if (filter==null) {
            throw new RuntimeException("Filter is null!");
         }
         attach(null,filter,child,false);
      }
      public void attach(Router router,Element child,boolean defaultRoute) {
         attach(router,null,child,defaultRoute);
      }
      protected void attach(Router router,Filter filter,Element child,boolean defaultRoute) {
         Name name = child.getName();
         Context parentContext = router==null ? filter.getContext() : router.getContext();
         if (name.equals(ROUTER)) {
            String match = child.getAttributeValue("match");
            if (match==null && filter==null && !defaultRoute) {
               LOG.severe("The router element does not have the required match attribute.");
               return;
            }
            if (defaultRoute) {
               router.attachDefault(createRouter(parentContext,child));
            } else if (router!=null) {
               router.attach(match,createRouter(parentContext,child));
            } else {
               filter.setNext(createRouter(parentContext,child));
            }
         } else if (name.equals(ROUTE)) {
            String match = child.getAttributeValue("match");
            if (match==null && filter==null && !defaultRoute) {
               LOG.severe("The route element does not have the required match attribute.");
               return;
            }
            Class def = getTargetClass(child);
            if (def==null) {
               return;
            }
            if (isServerResource(def)) {
               Restlet finder = Finder.createFinder(def, Finder.class, hasParametersOrAttributes(child) ? createContext(parentContext,child) : parentContext,parentContext.getLogger());
               if (defaultRoute) {
                  LOG.fine("Mapping default -> "+def.getName());
                  router.attachDefault(finder);
               } else if (router!=null) {
                  LOG.fine("Mapping "+match+" -> "+def.getName());
                  router.attach(match,finder);
               } else {
                  filter.setNext(finder);
               }
            } else {
               try {
                  Restlet restlet = createRestlet(parentContext,def,child);
                  if (defaultRoute) {
                     LOG.fine("Mapping default -> "+def.getName());
                     router.attachDefault(restlet);
                  } else if (router!=null) {
                     LOG.fine("Mapping "+match+" -> "+def.getName());
                     router.attach(match,restlet);
                  } else {
                     filter.setNext(restlet);
                  }
               } catch (Exception ex) {
                  LOG.log(Level.SEVERE,"Cannot instantiate class: "+def.getName(),ex);
               }
            }
         } else if (name.equals(FILTER)) {
            String match = child.getAttributeValue("match");
            if (match==null && filter==null && !defaultRoute) {
               LOG.severe("The filter element does not have the required match attribute.");
               return;
            }
            Class def = getTargetClass(child);
            if (def==null) {
               return;
            }
            Filter childFilter = null;
            try {
               childFilter = createFilter(parentContext,def,child);
            } catch (Exception ex) {
               LOG.log(Level.SEVERE,"Cannot instantiate filter.",ex);
               return;
            }
            if (defaultRoute) {
               router.attachDefault(childFilter);
            } else if (router!=null) {
               router.attach(match,childFilter);
            } else {
               filter.setNext(childFilter);
            }
            Iterator<Element> elements = child.getElementChildren();
            while (elements.hasNext()) {
               Element nextChild = elements.next();
               if (nextChild.getName().equals(NEXT)) {
                  Iterator<Element> nextChildren = nextChild.getElementChildren();
                  while (nextChildren.hasNext()) {
                     attachNext(childFilter,nextChildren.next());
                  }
               }
            }
         } else if (name.equals(CONTENT)) {
            String match = child.getAttributeValue("match");
            if (match==null && filter==null && !defaultRoute) {
               LOG.severe("The content element does not have the required match attribute.");
               return;
            }
            Restlet restlet = createContent(parentContext,child);
            if (defaultRoute) {
               router.attachDefault(restlet);
            } else if (router!=null) {
               router.attach(match,restlet);
            } else {
               filter.setNext(restlet);
            }
         } else if (name.equals(REDIRECT)) {
            String match = child.getAttributeValue("match");
            if (match==null && filter==null && !defaultRoute) {
               LOG.severe("The content element does not have the required match attribute.");
               return;
            }
            String to = child.getAttributeValue("to");
            if (to==null) {
               LOG.severe("The redirect element is missing the required 'to' attribute.");
               return;
            }
           
            Reference targetRef = new Reference(to);
            Restlet restlet = null;
            if (targetRef.isAbsolute() && targetRef.getScheme().equals("riap")) {
               restlet = new Redirector(parentContext,to,Redirector.MODE_SERVER_INBOUND);
            } else {
               restlet = new Redirector(parentContext,to,Redirector.MODE_CLIENT_SEE_OTHER);
            }
            if (defaultRoute) {
               router.attachDefault(restlet);
            } else if (router!=null) {
               String [] extraction = null;
               if (match.charAt(match.length()-1)=='}') {
                  // seek to start of bracket expression
                  int pos = match.length()-2;
                  for (; pos>0 && match.charAt(pos)!='{'; pos--);
                  if (pos>=0 && match.charAt(pos+1)=='?') {
                     String expr = match.substring(pos+2,match.length()-1);
                     extraction = expr.split(",");
                     match = match.substring(0,pos);
                     LOG.fine("redirect extraction, match="+match+", expr="+expr);
                  }
               }
               if (extraction!=null) {
                  Extractor extractor = new Extractor(parentContext,restlet);
                  for (int i=0; i<extraction.length; i++) {
                     extractor.extractFromQuery(extraction[i], extraction[i], true);
                  }
                  router.attach(match,extractor);
               } else {
                  router.attach(match,restlet);
               }
            } else {
               filter.setNext(restlet);
            }
         } else if (name.equals(DEFAULT)) {
            Iterator<Element> elements = child.getElementChildren();
            while (elements.hasNext()) {
               attach(router,elements.next(),true);
            }
           
         }

      }
     
      public Router createRouter(Context parentContext,Element routerConf) {
         Context routerContext = hasParametersOrAttributes(routerConf) ? createContext(parentContext,routerConf) : parentContext;
         Router router = new Router(routerContext);
         router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
         String method = routerConf.getAttributeValue("method");
         if ("best".equals(method)) {
            router.setRoutingMode(Router.MODE_BEST_MATCH);
         } else if ("first".equals(method)) {
            router.setRoutingMode(Router.MODE_FIRST_MATCH);
         } else if ("last".equals(method)) {
            router.setRoutingMode(Router.MODE_LAST_MATCH);
         } else if ("next".equals(method)) {
            router.setRoutingMode(Router.MODE_NEXT_MATCH);
         } else if ("random".equals(method)) {
            router.setRoutingMode(Router.MODE_RANDOM_MATCH);
         }
         String matching = routerConf.getAttributeValue("matching");
         if ("starts-with".equals(matching)) {
            router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
         } else if ("equals".equals(matching)) {
            router.setDefaultMatchingMode(Template.MODE_EQUALS);
         }
         Iterator<Element> elements = routerConf.getElementChildren();
         while (elements.hasNext()) {
            attach(router,elements.next(),false);
         }
         return router;
      }
     
      protected boolean hasParametersOrAttributes(Element useConf) {
         Iterator<Element> children = useConf.getElementChildren();
         if (children.hasNext()) {
            Element child = children.next();
            return child.getName().equals(PARAMETER) || child.getName().equals(ATTRIBUTE);
         }
         return false;
      }
     
      public Restlet createContent(Context parentContext,Element contentConf) {
         String href = contentConf.getAttributeValue("href");
         if (href==null) {
            return null;
         }
         URI source = contentConf.getBaseURI().resolve(href);
         String scheme = source.getScheme();
         if (scheme.equals("http") || scheme.equals("https")) {
            LOG.fine("  Content proxy to: "+source);
            ProxyApplication proxy = new ProxyApplication(parentContext,source.toString());
            proxy.getTunnelService().setEnabled(false);
            return proxy;
         } else {
            final String uri = source.toString();
            final String indexName = contentConf.getAttributeValue("index");
            // hope the directory resource can handle it
            LOG.fine("  Content directory: "+source);
            Application app = new Application(parentContext) {
               public Restlet createRoot() {
                  Directory directory = new Directory(getContext(),uri);
                  directory.setIndexName(indexName==null ? "index.html" : indexName);
                  return directory;
               }
            };
            return app;
         }
        
      }

      public Restlet createRestlet(Context parentContext,Element useConf)
         throws ClassNotFoundException,InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException
      {
         Class def = getTargetClass(useConf);
         if (def==null) {
            return null;
         }
         String className = useConf.getAttributeValue("class");
         Class targetClass = this.getClass().getClassLoader().loadClass(className);
         return createRestlet(parentContext,targetClass,useConf);
      }
     
      protected Context createContext(Context parentContext, Element useConf)
      {
         Context appContext = parentContext.createChildContext();
         LinkSet confLinks = linkSet;
         boolean hasLinks = false;
         Iterator<Element> appLinks = useConf.getElementsByName(LINK);
         while (appLinks.hasNext()) {
            if (!hasLinks) {
               LinkSet set = new LinkSet();
               set.addLinkSet(linkSet);
               confLinks = set;
            }
            Element linkE = appLinks.next();
            String href = linkE.getAttributeValue("href");
            if (href!=null) {
               URI tlocation = linkE.getBaseURI().resolve(href);
               String mtype = linkE.getAttributeValue("type");
               Link l = new Link(linkE.getAttributeValue("rel"),mtype==null ? null : MediaType.valueOf(mtype),tlocation);
               l.setIdentity(linkE.getAttributeValue("username"),linkE.getAttributeValue("password"));
               if (l.getRelation()!=null) {
                  confLinks.put(l.getRelation(),l);
               }
            }
         }
        
         loadContext(appContext,useConf);
         String copy = useConf.getAttributeValue("copy");
         if (copy==null || "parameters".equals(copy) || "all".equals(copy)) {
            for (Parameter param : parentContext.getParameters()) {
               appContext.getParameters().add(param);
            }
         }
        
         if (copy==null || "attributes".equals(copy) || "all".equals(copy)) {
            for (String key : parentContext.getAttributes().keySet()) {
               appContext.getAttributes().put(key,parentContext.getAttributes().get(key));
            }
         }
         return appContext;
      }
     
      protected void loadContext(Context appContext,Element useConf)
      {
         LOG.fine("Loading context: "+appContext);
        
         Iterator<Element> children = useConf.getElementChildren();
         while (children.hasNext()) {
            Element child = children.next();
            if (child.getName().equals(ATTRIBUTE)) {
               Element attrE = child;
               String name = attrE.getAttributeValue("name");
               String value = attrE.getAttributeValue("value");
               String href = attrE.getAttributeValue("href");
               if (href!=null) {
                  value = attrE.getBaseURI().resolve(href).toString();
               }
               Class def = getTargetClass(attrE);
               if (value!=null) {
                  LOG.fine("Attribute: "+name+"="+value);
                  appContext.getAttributes().put(name,value);
               } else if (def!=null) {
                  try {
                     Object obj = null;
                     try {
                        Constructor<Object> makeit = def.getConstructor(Context.class);
                        obj = makeit.newInstance(appContext);
                     } catch (NoSuchMethodException ex) {
                        Constructor<Restlet> makeit = def.getConstructor();
                        obj = makeit.newInstance();
                     }
                     LOG.fine("Attribute: "+name+"="+obj);
                     appContext.getAttributes().put(name,obj);
                  } catch (Exception ex) {
                     LOG.log(Level.SEVERE,"Cannot instantiate "+def.getName()+" for attribute "+name);
                  }
               } else {
                  List<Object> values = new ArrayList<Object>();
                  Iterator<Element> attChildren = attrE.getElementChildren();
                  while (attChildren.hasNext()) {
                     Element attChild = attChildren.next();
                     if (attChild.getName().equals(PARAMETER)) {
                        String pname = attChild.getAttributeValue("name");
                        if (pname!=null) {
                           String pvalue = attChild.getAttributeValue("value");
                           String phref = attChild.getAttributeValue("href");
                           if (phref!=null) {
                              pvalue = attChild.getBaseURI().resolve(phref).toString();
                           }
                           if (pvalue==null) {
                              pvalue = "";
                           }
                           values.add(new Parameter(pname,pvalue));
                        }
                     } else {
                        // Switch to DOM
                        try {
                           StringWriter xml = new StringWriter();
                           XMLWriter.writeElement(attChild, xml);
                           LOG.fine("Attribute XML: "+xml.toString());
                           values.add(docBuilder.parse(new InputSource(new StringReader(xml.toString()))));
                        } catch (Exception ex) {
                           LOG.log(Level.SEVERE,"Cannot serialize attribute XML.",ex);
                        }

                     }
                  }
                  LOG.fine("Attribute: "+name+" is list of values.");
                  appContext.getAttributes().put(name,values);
               }
            } else if (child.getName().equals(PARAMETER)) {
               Element paramE = child;
               String pname = paramE.getAttributeValue("name");
               if (pname!=null) {
                  String value = paramE.getAttributeValue("value");
                  String href = paramE.getAttributeValue("href");
                  if (href!=null) {
                     value = paramE.getBaseURI().resolve(href).toString();
                  }
                  String resource = paramE.getAttributeValue("resource");
                  String ref = paramE.getAttributeValue("ref");
                  LOG.fine("resource="+resource+", ref="+ref);
                  if (resource!=null && ref!=null) {
                     ClassLoader loader = loaders.get(ref);
                     if (loader==null) {
                        Class targetClass = definitions.get(ref);
                        if (targetClass!=null) {
                           targetClass.getClassLoader();
                        }
                     }
                     if (loader!=null) {
                        URL uvalue = loader.getResource(resource);
                        if (uvalue!=null) {
                           value = uvalue.toString();
                        }
                     } else {
                        LOG.warning("Cannot find definition of "+ref);
                     }
                  }
                  if (value==null) {
                     value = "";
                  }
                  LOG.fine("Setting parameter "+pname+"="+value);
                  if ("true".equals(paramE.getAttributeValue("replace"))) {
                     Parameter toRemove;
                     while ((toRemove = appContext.getParameters().getFirst(pname))!=null) {
                        appContext.getParameters().remove(toRemove);
                     }
                  }
                  appContext.getParameters().add(pname,value);
               }
              
            } else if (child.getName().equals(INCLUDE)) {
               String href = child.getAttributeValue("href");
               if (href==null) {
                  continue;
               }
               URI location = child.getBaseURI().resolve(href);
               try {
                  Document included = docLoader.load(location);
                  Element top = included.getDocumentElement();
                  if (!top.getName().equals(CONTEXT)) {
                     continue;
                  }
                  loadContext(appContext,top);
               } catch (Exception ex) {
                  LOG.log(Level.SEVERE,"Cannot load included document: "+location,ex);
               }
            }
         }
        
      }
     
      public Restlet createRestlet(Context parentContext,Class targetClass,Element useConf)
         throws InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException
      {
         LOG.fine("Creating restlet: "+targetClass);
         Context appContext = createContext(parentContext,useConf);
         return getRestletInstance(appContext,targetClass);
      }
     
      public Filter createFilter(Context parentContext, Element child)
         throws ClassNotFoundException,InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException
      {
         LOG.fine("Creating restlet as filter...");
         return (Filter)createRestlet(parentContext,child);
      }

      public Filter createFilter(Context parentContext, Class targetClass, Element child)
         throws ClassNotFoundException,InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException
      {
         LOG.fine("Creating restlet as filter...");
         return (Filter)createRestlet(parentContext,targetClass,child);
      }

   }
  

   long autoconfCheck;
   Map<String,ClassLoader> loaders;
   Map<String,Class> definitions;
   List<Server> servers;
   List<Protocol> clients;
   File keyStorePath;
   String keyStorePassword;
   DocumentLoader docLoader;
  
   /** Creates a new instance of Configuration */
   public Configuration()
   {
      this.autoconfCheck = 180*1000;
      this.loaders = new HashMap<String,ClassLoader>();
      this.definitions = new HashMap<String,Class>();
      this.servers = new ArrayList<Server>();
      this.clients = new ArrayList<Protocol>();
      this.docLoader = new SAXDocumentLoader();
   }
  
  
   public Host createHost(Element hostE)
      throws XMLException
   {
      String name = hostE.getAttributeValue("name");
      String internalName = hostE.getAttributeValue("internal");
      Host host = new Host(name,internalName,hostE);

      return host;
     
   }
   public void load(URI location)
      throws IOException,XMLException
   {
      Document doc = docLoader.load(location);
      Element top = doc.getDocumentElement();
      if (!top.getName().equals(COMPONENT)) {
         throw new XMLException("Expecting "+COMPONENT+" but found "+top.getName());
      }
      String value = top.getAttributeValue("autoconf-check");
      if (value!=null) {
         autoconfCheck = Long.parseLong(value) * 1000;
      }
     
      Element keyStoreE = top.getFirstElementNamed(KEYSTORE);
      if (keyStoreE!=null) {
         URI fileRef = keyStoreE.getBaseURI().resolve(keyStoreE.getAttributeValue("file"));
         this.keyStorePath = new File(fileRef.getSchemeSpecificPart());
         this.keyStorePassword = keyStoreE.getAttributeValue("password");
      }
     
      Iterator<Element> appdefElements = top.getElementsByName(DEFINE);
      while (appdefElements.hasNext()) {
         Element appdefE = appdefElements.next();
         String name = appdefE.getAttributeValue("name");
         String className = appdefE.getAttributeValue("class");
        
         String ref = appdefE.getAttributeValue("ref");
         if (ref!=null) {
            ClassLoader theLoader = loaders.get(ref.trim());
            if (theLoader==null) {
               throw new XMLException("Cannot find definition: "+ref);
            }
            if (className==null || name==null) {
               continue;
            }
            try {
               Class cdef = theLoader.loadClass(className);
               definitions.put(name,cdef);
            } catch (ClassNotFoundException ex) {
               throw new XMLException("Cannot find class: "+ex.getMessage(),ex);
            }
            continue;
         }
        
         if (name!=null) {
            List<URL> libraries = new ArrayList<URL>();
            Iterator<Element> libraryElements = appdefE.getElementsByName(LIBRARY);
            while (libraryElements.hasNext()) {
               Element libE = libraryElements.next();
               String href = libE.getAttributeValue("href");
               if (href!=null) {
                  URI u = libE.getBaseURI().resolve(href);
                  libraries.add(u.toURL());
               }
            }
            ClassLoader theLoader = this.getClass().getClassLoader();
            if (libraries.size()!=0) {
               URL [] list = new URL[libraries.size()];
               list = libraries.toArray(list);
               theLoader = new URLClassLoader(list,this.getClass().getClassLoader());
               LOG.fine("ClassLoader: "+name+" -> "+theLoader);
               LOG.fine("  Libraries: "+libraries);
               loaders.put(name, theLoader);
            }
            if (className!=null) {
               try {
                  Class cdef = theLoader.loadClass(className);
                  definitions.put(name,cdef);
               } catch (ClassNotFoundException ex) {
                  throw new XMLException("Cannot find class: "+ex.getMessage(),ex);
               }
            }
         } else if (name!=null) {
            LOG.warning("The 'class' attribute is missing on the definition of '"+name+"'");
         }
      }
     
      Iterator<Element> clientElements = top.getElementsByName(CLIENT);
      while (clientElements.hasNext()) {
         Element clientDef = clientElements.next();
         String protocol = clientDef.getAttributeValue("protocol");
         if (protocol!=null) {
            Protocol p = Protocol.valueOf(protocol.trim());
            clients.add(p);
         }
      } 
     
      Iterator<Element> interfaceElements = top.getElementsByName(SERVER);
      while (interfaceElements.hasNext()) {
         Element serverE = interfaceElements.next();
         String addr = serverE.getAttributeValue("address");
         String portS = serverE.getAttributeValue("port");
         String protocol = serverE.getAttributeValue("protocol");
         Protocol p = Protocol.HTTP;
         if (protocol!=null) {
            p = Protocol.valueOf(protocol.trim());
         }
         int port = portS==null ? p.getDefaultPort() : Integer.parseInt(portS);
         Server server = new Server(addr,port,p);
         servers.add(server);
        
         Iterator<Element> links = serverE.getElementsByName(LINK);
         while (links.hasNext()) {
            Element linkE = links.next();
            String href = linkE.getAttributeValue("href");
            if (href!=null) {
               URI tlocation = linkE.getBaseURI().resolve(href);
               String mtype = linkE.getAttributeValue("type");
               Link l = new Link(linkE.getAttributeValue("rel"),mtype==null ? null : MediaType.valueOf(mtype),tlocation);
               l.setIdentity(linkE.getAttributeValue("username"),linkE.getAttributeValue("password"));
               if (l.getRelation()!=null) {
                  server.getLinks().put(l.getRelation(),l);
               }
            }
         }
        
         Iterator<Element> hostElements = serverE.getElementsByName(HOST);
         while (hostElements.hasNext()) {
            Element hostE = hostElements.next();
            Host host = createHost(hostE);
            server.getHosts().put(host.getName(),host);
         }
      }
     
   }
  
   public long getAutoConfigurationCheckWait() {
      return autoconfCheck;
   }
  
   public File getKeyStorePath()
   {
      return keyStorePath;
   }
  
   public String getKeyStorePassword()
   {
      return keyStorePassword;
   }
  
   public List<Protocol> getClients() {
      return clients;
   }

   public List<Server> getServers() {
      return servers;
   }

   public void setKeyStorePath(File keyStorePath)
   {
      this.keyStorePath = keyStorePath;
   }

   public void setKeyStorePassword(String keyStorePassword)
   {
      this.keyStorePassword = keyStorePassword;
   }
  
}
TOP

Related Classes of org.atomojo.server.Configuration$Server

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.