incubator-lokahi-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tob...@apache.org
Subject svn commit: r392982 [15/25] - in /incubator/lokahi/lokahi/trunk: ./ conf/ database/ docs/ lib/ src/ src/java/ src/java/lokahi/ src/java/lokahi/core/ src/java/lokahi/core/agent/ src/java/lokahi/core/agent/callable/ src/java/lokahi/core/agent/callable/co...
Date Mon, 10 Apr 2006 16:20:11 GMT
Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCAction.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCAction.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCAction.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCAction.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,167 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import lokahi.core.api.function.Function;
+import lokahi.core.api.user.User;
+import lokahi.core.common.collection.TMCSet;
+import lokahi.core.common.interfaces.TMCDao;
+import org.apache.log4j.Logger;
+import org.apache.struts.action.Action;
+import org.apache.struts.action.ActionForm;
+import org.apache.struts.action.ActionForward;
+import org.apache.struts.action.ActionMapping;
+import org.apache.struts.action.ActionMessage;
+import org.apache.struts.action.ActionMessages;
+import org.apache.struts.validator.DynaValidatorForm;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.sql.SQLException;
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TMCAction.java,v 1.2 2006/03/07 22:05:24 drtobes Exp $
+ */
+public abstract class TMCAction<T extends TMCDao> extends Action {
+  static final Logger logger = Logger.getLogger(TMCAction.class);
+  protected static final String SESSION_LOGGED_IN_OBJ_PARAM = "User";
+  protected static final String LOGOUT_PARAM = "logout";
+  protected static final String FORWARD_LOGGED_OUT = "application.forward.login";
+  protected static final String FORWARD_LOGGED_OUT_WAP = "wap.failure";
+  protected static final String FORWARD_APPLICATION_ERROR = "application.forward.error";
+  protected static final String FORWARD_APPLICATION_ERROR_WAP = "wap.failure.action";
+  protected static final String FORWARD_APPLICATION_SUCCESS = "application.forward.administration.success";
+  protected static final String FORWARD_APPLICATION_SUCCESS_WAP = "wap.success.action";
+  protected static final String METHOD_PARAM = "methodToCall";
+  protected static final String WAP_PARAM = "wap";
+
+  protected static final String SUCCESS_MESSAGE = "tmc.actions.TMCAction.SUCCESS_MESSAGE";
+
+  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
+    User user;
+    ActionForward actionForward = null;
+    ActionMessages messages = new ActionMessages();
+    HttpSession session = request.getSession();
+    boolean wap = false;
+    DynaValidatorForm dynForm = (DynaValidatorForm) form;
+    if (dynForm.get("wap") != null && "true".equalsIgnoreCase((String) dynForm.get("wap"))) {
+      wap = true;
+    }
+    User userObj = (User) session.getAttribute(SESSION_LOGGED_IN_OBJ_PARAM);
+    if (userObj != null) {
+      user = userObj;
+      if (dynForm.getMap().containsKey(METHOD_PARAM)) {
+        String method = (String) dynForm.get(METHOD_PARAM);
+        if (method != null && !"".equals(method)) {
+          Function f = null;
+          f = Function.getFunction(method);
+          if (logger.isDebugEnabled()) {
+            logger.debug("f=" + f);
+          }
+          if (f == null) {
+            messages = this.addMessage(messages, new ActionMessage("error.badFunction"));
+          } else {
+            messages.add(this.executeFunctions(dynForm, f, user));
+          }
+          if (messages.size(ActionMessages.GLOBAL_MESSAGE) == 0) {
+            actionForward = this.successForward(wap, mapping);
+          } else {
+            //remove the message that is 'success'
+            Iterator i = messages.get(ActionMessages.GLOBAL_MESSAGE);
+            ActionMessages temp = new ActionMessages();
+            while (i.hasNext()) temp.add(ActionMessages.GLOBAL_MESSAGE, (ActionMessage) i.next());
+            messages = temp;
+            actionForward = this.errorForward(wap, mapping);
+          }
+        }
+      } else {
+        messages = this.addMessage(messages, new ActionMessage("error.errorForward", "Missing method"));
+      }
+    } else {
+      actionForward = this.login(wap, mapping);
+    }
+    if (actionForward == null) {
+      actionForward = this.errorForward(wap, mapping);
+    }
+    saveMessages(request, messages);
+    return actionForward;
+  }
+
+  protected Collection<T> getMultiTemplate(DynaValidatorForm dynaForm, Class<T> clazz) throws SQLException, IllegalAccessException, InstantiationException {
+    Collection<T> c = new TMCSet<T>();
+    String[] ids = (String[]) dynaForm.get("id");
+    if (ids != null && ids.length > 0) {
+      for (String id : ids) {
+        if (!"".equals(id)) {
+          T obj = clazz.newInstance();
+          obj = (T) obj.get((Integer.parseInt(id)));
+          c.add(obj);
+        }
+      }
+    }
+    return c;
+  }
+
+  public abstract ActionMessages executeFunctions(DynaValidatorForm form, Function f, User user);
+
+  public ActionForward login(boolean wap, ActionMapping mapping) {
+    return this.findForward(wap, mapping, FORWARD_LOGGED_OUT_WAP, FORWARD_LOGGED_OUT);
+  }
+
+  public ActionForward errorForward(boolean wap, ActionMapping mapping) {
+    return this.findForward(wap, mapping, FORWARD_APPLICATION_ERROR_WAP, FORWARD_APPLICATION_ERROR);
+  }
+
+  public ActionForward successForward(boolean wap, ActionMapping mapping) {
+    return this.findForward(wap, mapping, FORWARD_APPLICATION_SUCCESS_WAP, FORWARD_APPLICATION_SUCCESS);
+  }
+
+  private ActionForward findForward(boolean wap, ActionMapping mapping, String wapForward, String forward) {
+    ActionForward ret;
+    if (wap) {
+      ret = mapping.findForward(wapForward);
+    } else {
+      ret = mapping.findForward(forward);
+    }
+    return ret;
+  }
+
+  public ActionMessages addMessage(ActionMessages messages, String type, ActionMessage msg) {
+    if (msg != null) {
+      if (logger.isDebugEnabled()) {
+        logger.debug("Adding message " + msg.getKey());
+      }
+      if (messages == null) {
+        messages = new ActionMessages();
+      }
+      messages.add(type, msg);
+    }
+    return messages;
+  }
+
+  public ActionMessages addMessage(ActionMessages messages, ActionMessage msg) {
+    return this.addMessage(messages, ActionMessages.GLOBAL_MESSAGE, msg);
+  }
+
+}
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCActionServlet.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCActionServlet.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCActionServlet.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCActionServlet.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,30 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import org.apache.struts.action.ActionServlet;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TMCActionServlet.java,v 1.1 2006/03/02 19:19:48 drtobes Exp $
+ */
+public class TMCActionServlet extends ActionServlet {
+}
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCRSSAlertServlet.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCRSSAlertServlet.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCRSSAlertServlet.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCRSSAlertServlet.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,82 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import lokahi.core.api.alert.AlertDAO;
+import lokahi.core.api.alert.AlertTool;
+import lokahi.core.common.util.PropertiesFile;
+import org.apache.log4j.Logger;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.output.Format;
+import org.jdom.output.XMLOutputter;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Iterator;
+import java.util.SortedSet;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TMCRSSAlertServlet.java,v 1.1 2006/03/02 19:19:48 drtobes Exp $
+ */
+public class TMCRSSAlertServlet extends HttpServlet {
+  static final Logger logger = Logger.getLogger(TMCRSSAlertServlet.class);
+
+  public void doGet(HttpServletRequest request, HttpServletResponse response) {
+    AlertTool at = new AlertTool();
+    SortedSet<AlertDAO> s = at.getRecentAlerts();
+    Element e = new Element("rss");
+    e.setAttribute("version", "2.0");
+    Element channel = new Element("channel");
+    channel.addContent(new Element("title").setText("TMC Alerts"));
+    channel.addContent(new Element("link").setText(PropertiesFile.getConstantValue("application.full.url")));
+    channel.addContent(new Element("description").setText("Alerts powered by TMC: RSS Feed and Service created by Steve Toback"));
+    channel.addContent(new Element("ttl").setText("1440"));
+    Iterator<AlertDAO> i = s.iterator();
+    AlertDAO al = i.next();
+    channel.addContent(new Element("pubDate").setText(al.getSubmissionDateAsText()));
+    channel.addContent(al.buildXMLRepresention());
+    while (i.hasNext()) {
+      channel.addContent(i.next().buildXMLRepresention());
+    }
+    e.addContent(channel);
+    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
+    PrintWriter pw = null;
+    try {
+      pw = response.getWriter();
+    } catch (IOException e1) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e1.getMessage());
+      }
+    }
+    response.setContentType("text/xml");
+    pw.print(out.outputString(new Document(e)));
+  }
+
+  public void doPost(HttpServletRequest request, HttpServletResponse response) {
+    this.doGet(request, response);
+  }
+
+}
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCStartupServlet.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCStartupServlet.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCStartupServlet.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCStartupServlet.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,97 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import lokahi.core.common.database.ConnBean;
+import lokahi.core.common.database.DerbyBroker;
+import lokahi.core.common.util.PropertiesFile;
+import lokahi.core.controller.CheckJvmThread;
+import org.apache.log4j.xml.DOMConfigurator;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import java.sql.SQLException;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TMCStartupServlet.java,v 1.2 2006/03/07 19:52:07 drtobes Exp $
+ */
+public class TMCStartupServlet extends HttpServlet {
+  public static final String PROPS_ID = "properties";
+
+  /*	init() method is overridden to start the jvm startup thread
+  */
+  public void init() throws ServletException {
+    super.init();
+    ServletConfig servletcfg = this.getServletConfig();
+    String jvmHttp = this.getServletContext().getInitParameter("TmcJvmHttp");
+    String prefix = getServletContext().getRealPath("/");
+    String file = getInitParameter("log4j-init-file");
+    // if the log4j-init-file is not set, then no point in trying
+    System.out.println("Configuring log4j with file " + prefix + file);
+    if (file != null) {
+      DOMConfigurator.configure(prefix + file);
+    }
+    String propsName = servletcfg.getInitParameter(PROPS_ID);
+    PropertiesFile.load(this.getClass().getClassLoader().getResourceAsStream(propsName));
+    PropertiesFile.load(this.getClass().getClassLoader().getResourceAsStream("db.properties"));
+
+    // check for some specific init values that need non-standard action
+    ConnBean.initializePool(PropertiesFile.getConstantValue("tmc.database.uri"),
+                            PropertiesFile.getConstantValue("tmc.database.user"),
+                            PropertiesFile.getConstantValue("tmc.database.password"),
+                            PropertiesFile.getConstantValue("tmc.database.driver")
+    );
+    DerbyBroker.initalize();
+    // If the Authenticate Module used is LDAPAuthenticate, initialize the variables
+    String auth_module = PropertiesFile.getConstantValue("AuthenticateModule");
+    System.out.println("auth_module = " + auth_module);
+    if (PropertiesFile.getBooleanValue("tmc.thread.run")) {
+// start the thread - CheckJvmThread
+      CheckJvmThread thread = CheckJvmThread.getThreadInstance(jvmHttp);
+// set the 'runThread' variable to true
+      CheckJvmThread.startThread();
+// but the thread is not started yet, so let us start it now.
+      thread.start();
+    }
+
+  } // end init
+
+  /*  The destroy method stops the jvm start up thread if it is running
+   *	It also closes all connections in the connection pool and destroys the pool
+   */
+  public void destroy() {
+    // stop the thread - CheckJvmThread
+    if (PropertiesFile.getBooleanValue("tmc.thread.run")) {
+      CheckJvmThread.stopThread();
+      System.out.println("Thread stopped");
+      // Close all connections in the connection pool
+    }
+    try {
+      ConnBean.destroyPool();
+      DerbyBroker.shutDown();
+    } catch (SQLException e) {
+      System.out.println("Exception: " + e.getMessage());
+    }
+  } // end destroy
+
+}
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCVelocityServlet.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCVelocityServlet.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCVelocityServlet.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TMCVelocityServlet.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,141 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import org.apache.log4j.Logger;
+import org.apache.velocity.Template;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import org.apache.velocity.exception.MethodInvocationException;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.tools.view.servlet.VelocityViewServlet;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Enumeration;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TMCVelocityServlet.java,v 1.1 2006/03/02 19:19:48 drtobes Exp $
+ */
+public class TMCVelocityServlet extends VelocityViewServlet {
+  public static final String CONTEXT_BROWSER_INFO = "browser";
+  static final Logger logger = Logger.getLogger(TMCVelocityServlet.class);
+
+  public void init(ServletConfig config) throws ServletException {
+    super.init(config);
+  }
+
+  public void doPost(HttpServletRequest request, HttpServletResponse response)
+      throws ServletException, IOException {
+    doGet(request, response);
+  }
+
+  public void doGet(HttpServletRequest request, HttpServletResponse response)
+      throws ServletException, IOException {
+    Context context = null;
+    try {
+      context = fillContext(request, response);
+      setContentType(request, response);
+      Template template = handleRequest(request, response, context);
+      if (template == null) {
+        Velocity.warn("VelocityViewServlet: couldn't find template to match request.");
+      } else {
+        mergeTemplate(template, context, response);
+      }
+    } catch (ParseErrorException e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (MethodInvocationException e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (ResourceNotFoundException e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (UnsupportedEncodingException e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (IOException e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (Exception e) {
+      Velocity.error("VelocityViewServlet: Exception processing the template: " + e);
+      error(request, response, e);
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } finally {
+      requestCleanup(request, response, context);
+    }
+  }
+
+  private Context fillContext(HttpServletRequest request, HttpServletResponse response) {
+    Context context = createContext(request, response);
+    for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
+      String key = (String) e.nextElement();
+      String value = request.getParameter(key);
+      if (logger.isDebugEnabled()) {
+        if (!"password".equalsIgnoreCase(key)) {
+          logger.debug(key + " = " + value);
+        }
+      }
+      context.put(key, value);
+    }
+    return context;
+  }
+
+  /**
+   * Sets the content type of the response.  This is overridden to set the content type
+   * for our .vmcss to text/css instead of the text/html that the parent class sets it to
+   *
+   * @param request  servlet request from client
+   * @param response servlet reponse to client
+   */
+  protected void setContentType(HttpServletRequest request, HttpServletResponse response) {
+    if (request.getRequestURI().endsWith("wml")) {
+      response.setContentType("text/vnd.wap.wml");
+    } else if (request.getRequestURI().endsWith("vmcss")) {
+      response.setContentType("text/css");
+    } else {
+      response.setContentType("text/html");
+    }
+  }
+
+}
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TemplateAction.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TemplateAction.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TemplateAction.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/TemplateAction.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,378 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import lokahi.core.api.environment.Environment;
+import lokahi.core.api.function.Function;
+import lokahi.core.api.ipaddress.Ip;
+import lokahi.core.api.jobpool.JobPool;
+import lokahi.core.api.pool.HostingPool;
+import lokahi.core.api.pool.HostingPoolModel;
+import lokahi.core.api.project.Project;
+import lokahi.core.api.state.State;
+import lokahi.core.api.user.User;
+import lokahi.core.common.authorization.AuthorizationManager;
+import lokahi.core.common.authorization.Global;
+import lokahi.core.common.collection.TMCSet;
+import lokahi.core.common.exception.AuthorizationException;
+import lokahi.core.common.exception.TMCException;
+import lokahi.core.common.exception.TMCIllegalArgumentException;
+import lokahi.core.common.interfaces.FunctionableEntity;
+import lokahi.httpd.api.entity.VirtualHost;
+import lokahi.tomcat.api.entity.TomcatContext;
+import org.apache.log4j.Logger;
+import org.apache.struts.action.ActionMessage;
+import org.apache.struts.action.ActionMessages;
+import org.apache.struts.validator.DynaValidatorForm;
+
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.Collection;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: TemplateAction.java,v 1.2 2006/03/07 22:05:24 drtobes Exp $
+ */
+public class TemplateAction extends TMCAction {
+  static final Logger logger = Logger.getLogger(TemplateAction.class);
+
+  public ActionMessages executeFunctions(DynaValidatorForm form, Function f, User user) {
+    ActionMessages messages = new ActionMessages();
+    String method = f.getCommand();
+    if (logger.isDebugEnabled()) {
+      logger.debug("f=" + f);
+    }
+    try {
+      if ("AddVirtualHostToProject".equals(method)) {
+        if (user.isAllowed(f)) {
+          addVirtualHostToProject(form, f, user);
+          messages = this.addMessage(messages, new ActionMessage("project.add.vhost"));
+        } else {
+          messages = this.addMessage(messages, new ActionMessage("error.notAuthorized"));
+        }
+      } else if ("AddContext".equals(method)) {
+        addContext(f, form, user);
+      } else if ("AddUserToProject".equals(method)) {
+        addUserToProject(user, f, form);
+      } else if ("UpdateVirtualHost".equals(method)) {
+        updateVhost(user, f, form);
+      } else {
+        messages = this.addMessage(messages, new ActionMessage("error.errorForward", "Invalid method action" + method));
+      }
+    } catch (AuthorizationException e) {
+      messages = this.addMessage(messages, new ActionMessage("error.notAuthorized"));
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.db"));
+    } catch (TMCIllegalArgumentException e) {
+      messages = this.addMessage(messages, new ActionMessage("error.badData"));
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (TMCException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.badData"));
+    } catch (IOException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.badData"));
+    }
+    return messages;
+  }
+
+  private void proccesAbilityMap(User u, String[] map, int type, Project p) throws SQLException {
+    for (int i = 0; i < map.length; i++) {
+      String[] entityFunction = map[i].split(",");
+      if (logger.isDebugEnabled()) {
+        logger.debug("map[" + i + "]=" + map[i]);
+      }
+      if (!"".equals(entityFunction[0]) && !"".equals(entityFunction[1])) {
+        FunctionableEntity fe = getFunctionableEntity(entityFunction[0], type);
+        Function f = null;
+//        try {
+        f = Function.getFunction(Integer.parseInt(entityFunction[1]));
+//        } catch (SQLException e) {
+//          if (logger.isInfoEnabled()) {
+//            logger.info("Exception: " + e.getMessage());
+//          }
+//        }
+        if (f != null && fe != null) {
+          if (logger.isDebugEnabled()) {
+            logger.debug("f=" + f);
+            logger.debug("u=" + u);
+            logger.debug("fe=" + fe);
+            logger.debug("p=" + p);
+          }
+          AuthorizationManager.addAbility(u, f, fe, p);
+        }
+      } else {
+        if (logger.isDebugEnabled()) {
+          logger.debug("SPLIT IS NOT WORKING");
+        }
+      }
+    }
+  }
+
+  private FunctionableEntity getFunctionableEntity(String id, int type) {
+    return AuthorizationManager.getEntity(type, Integer.parseInt(id));
+  }
+
+  public void addVirtualHostToProject(DynaValidatorForm form, Function f, User user) throws SQLException, TMCIllegalArgumentException, IOException, AuthorizationException {
+    String sProjectId = (String) form.get("projectId");
+    String hostingPoolId = (String) form.get("hostingPoolId");
+    String vhostName = (String) form.get("vhostName");
+    String entry = (String) form.get("entry");
+    Collection<TomcatContext> contexts;
+    String[] contextName = null;
+    String[] docBase = null;
+    if (form.getMap().containsKey("contextName")) {
+      contextName = (String[]) form.get("contextName");
+      docBase = (String[]) form.get("docBase");
+    }
+    String[] ipId = (String[]) form.get("ipId");
+    String projectName = (String) form.get("projectName");
+    boolean catchAll = false;
+    if ("true".equalsIgnoreCase((String) form.get("catchAll"))) {
+      catchAll = true;
+    }
+    boolean nameBased = false;
+    if ("true".equalsIgnoreCase((String) form.get("nameVirtualHost"))) {
+      nameBased = true;
+    }
+    if (!(nameBased || catchAll)) {
+      nameBased = true;
+    }
+    Project p = null;
+    HostingPool hp = null;
+    if (!"".equals(sProjectId)) {
+      p = Project.getProject(Integer.parseInt(sProjectId));
+      hp = HostingPool.getHostingPool(Integer.parseInt(hostingPoolId), true);
+    } else if (!"".equals(projectName)) {
+      p = Project.store(new Project(projectName));
+    }
+    if (!"".equals(hostingPoolId)) {
+      hp = HostingPool.getHostingPool(Integer.parseInt(hostingPoolId), true);
+    }
+    if (hp == null || p == null) throw new TMCIllegalArgumentException("Project, Hosting Pool must be chosen");
+    State s = State.getState(8);
+    Environment e = hp.getEnv();
+    contexts = buildContexts(contextName, docBase, hp, s, e);
+    addVhost(hp, p, vhostName, entry, contexts, ipId, catchAll, nameBased, user, f);
+  }
+
+  private void addContext(Function f, DynaValidatorForm form, User user) throws SQLException, TMCIllegalArgumentException, IOException, AuthorizationException {
+    Project p = Project.getProject(Integer.parseInt((String) form.get("projectId")));
+    VirtualHost vh = VirtualHost.getVirtualHost(Integer.parseInt((String) form.get("vhostid")));
+    if (logger.isDebugEnabled()) {
+      logger.debug("vh=" + vh);
+      logger.debug("p=" + p);
+    }
+    JobPool jp = new JobPool(p, user, "", f);
+    jp = JobPool.store(jp);
+    if (p == null) throw new TMCIllegalArgumentException("Project Cannot be null");
+    if (!user.isAllowed(f, p, vh)) throw new AuthorizationException("User not allowed to do that");
+    TomcatContext tc = TomcatContext.getTomcatContext(Integer.parseInt((String) form.get("contextId")));
+    p.addTomcatContexts(tc);
+    Project.update(p);
+    vh.addContext(tc);
+    jp.setOptions("virtualhost: " + vh.getName() + " context: " + tc.getName());
+    JobPool.update(jp);
+    HostingPool hp = vh.getHostingPool();
+    HostingPoolModel hpm = new HostingPoolModel();
+    hpm.deployApacheConfs(p, user, jp, hp);
+  }
+
+  private void addUserToProject(User user, Function f, DynaValidatorForm form) throws AuthorizationException, SQLException, TMCIllegalArgumentException {
+    if (!user.isAllowed(f))
+      throw new AuthorizationException("User " + user.getUserName() + " Not allowed to " + f.getCommand());
+    if (form.getMap().containsKey("global")) {
+      String newUserName = (String) form.get("userName");
+      String[] functions = (String[]) form.get("functions");
+      boolean isNewUser = false;
+      User newUser = User.getUser(newUserName);
+      if (newUser == null) {
+        newUser = new User(newUserName);
+        User.store(newUser);
+        isNewUser = true;
+      }
+      Global g = new Global();
+      for (final String newVar : functions) {
+        Function func = Function.getFunction(Integer.parseInt(newVar));
+        if (isNewUser || !newUser.isAllowed(func)) {
+          AuthorizationManager.addAbility(newUser, func, g, 0);
+        }
+      }
+    } else {
+      if ("-1".equals(form.get("projectId"))) throw new TMCIllegalArgumentException("Project must be chosen");
+      Project p = Project.getProject(Integer.parseInt((String) form.get("projectId")));
+      if (!user.isAllowed(f, p))
+        throw new AuthorizationException("User " + user.getUserName() + " Not allowed to " + f.getCommand());
+      String[] contextFunctions = (String[]) form.get("contextFunction");
+      String[] vhostFunctions = (String[]) form.get("vhostFunctions");
+      String newUserName = (String) form.get("userName");
+      User newUser = User.getUser(newUserName);
+      if (newUser == null) {
+        newUser = new User(newUserName);
+        User.store(newUser);
+      } else {
+        AuthorizationManager.removeAbilities(newUser, p.getPk());
+      }
+      proccesAbilityMap(newUser, contextFunctions, 4, p);
+      proccesAbilityMap(newUser, vhostFunctions, 3, p);
+      newUser.addProject(p);
+    }
+  }
+
+  private void addVhost(HostingPool hp, Project p, String vhostName, String entry, Collection<TomcatContext> contexts, String[] ipId, boolean catchAll, boolean nameBased, User user, Function f) throws SQLException, TMCIllegalArgumentException, IOException, AuthorizationException {
+    if (hp == null || p == null) throw new TMCIllegalArgumentException("Project must be chosen");
+    State s = State.getState(8);
+    Environment e = hp.getEnv();
+    JobPool jp = new JobPool(p, user, vhostName, f);
+    jp = JobPool.store(jp);
+    if (!hp.isVhostAllowed(vhostName)) throw new TMCIllegalArgumentException("Name not allowed");
+    VirtualHost vh = new VirtualHost(vhostName, entry, e, s, hp, catchAll, nameBased);
+    Collection<Ip> ips = new TMCSet<Ip>();
+    for (int i = 0; i < ipId.length; i++) {
+      Ip ip = Ip.getIp(Integer.parseInt(ipId[i]), true);
+      ips.add(ip);
+    }
+    vh.setIps(ips);
+    vh.setContexts(contexts);
+    vh = VirtualHost.store(vh);
+    HostingPoolModel hpm = new HostingPoolModel();
+    hpm.addVirtualHost(vh, jp, hp, user);
+    if (p.addTomcatContexts(contexts)
+        && p.addVirtualHost(vh)
+        && Project.update(p)
+        ) {
+
+      //NICE it worked...
+
+    }
+
+  }
+
+  private void updateVhost(User user, Function f, DynaValidatorForm form) throws AuthorizationException, SQLException, TMCIllegalArgumentException, IOException {
+    if (!user.isAllowed(f))
+      throw new AuthorizationException("User " + user.getUserName() + " Not allowed to " + f.getCommand());
+    VirtualHost vhost = null;
+    if (form.get("id") != null && !"".equals(form.get("id"))) {
+      try {
+        vhost = VirtualHost.getVirtualHost(Integer.parseInt((String) form.get("id")));
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    String sProjectId = (String) form.get("projectId");
+    String hostingPoolId = (String) form.get("hostingPoolId");
+    String vhostName = (String) form.get("vhostName");
+    String entry = (String) form.get("entry");
+    String[] ipId = (String[]) form.get("ipId");
+    Collection<HostingPool> changedHPs = new TMCSet<HostingPool>();
+    boolean catchAll = false;
+    Project p = null;
+    if (!"".equals(sProjectId)) {
+      p = Project.getProject(Integer.parseInt(sProjectId));
+    }
+    JobPool jp = new JobPool(p, user, vhostName, f);
+    jp = JobPool.store(jp);
+    if ("true".equalsIgnoreCase((String) form.get("catchAll"))) {
+      catchAll = true;
+    }
+    boolean nameBased = false;
+    if ("true".equalsIgnoreCase((String) form.get("nameVirtualHost"))) {
+      nameBased = true;
+    }
+    if (!(nameBased || catchAll)) {
+      nameBased = true;
+    }
+    if (vhost != null) {
+      Collection<Ip> ips = new TMCSet<Ip>();
+      for (int i = 0; i < ipId.length; i++) {
+        try {
+          ips.add(Ip.getIp(Integer.parseInt(ipId[i]), true));
+        } catch (SQLException e) {
+          if (logger.isInfoEnabled()) {
+            logger.info("Exception: " + e.getMessage());
+          }
+        }
+      }
+      if (hostingPoolId != null && !"".equals(hostingPoolId)) {
+        HostingPool hp = null;
+        try {
+          hp = HostingPool.getHostingPool(Integer.parseInt(hostingPoolId), true);
+        } catch (SQLException e) {
+          if (logger.isInfoEnabled()) {
+            logger.info("Exception: " + e.getMessage());
+          }
+        }
+        if (hp != null) {
+          try {
+            changedHPs = vhost.changeHostingPool(hp, ips, nameBased, catchAll);
+          } catch (SQLException e) {
+            if (logger.isInfoEnabled()) {
+              logger.info("Exception: " + e.getMessage());
+            }
+          }
+        }
+      }
+      vhost.setEntry(entry);
+      vhost.setName(vhostName);
+
+      try {
+        VirtualHost.update(vhost);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+      HostingPoolModel hpm = new HostingPoolModel();
+      for (final HostingPool hp : changedHPs) {
+        hpm.checkLogAndDeploy(p, user, jp, hp, vhost);
+      }
+    }
+  }
+
+  private Collection<TomcatContext> buildContexts
+      (String[] contextName, String[] docBase, HostingPool
+          hp, State
+          s, Environment
+          e) throws SQLException, TMCIllegalArgumentException {
+    Collection<TomcatContext> contexts = new TMCSet<TomcatContext>();
+    if (!hp.isContextAllowed(contextName)) throw new TMCIllegalArgumentException("Name not allowed");
+    for (int i = 0; i < contextName.length; i++) {
+      TomcatContext tc = new TomcatContext(contextName[i], docBase[i], s, e, hp.getTomcatPool());
+      contexts.add(TomcatContext.store(tc));
+    }
+    return contexts;
+  }
+
+}
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/UserAction.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/UserAction.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/UserAction.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/core/gui/www/UserAction.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,165 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.core.gui.www;
+
+import lokahi.core.api.function.Function;
+import lokahi.core.api.project.Project;
+import lokahi.core.api.user.User;
+import lokahi.core.api.user.UserModel;
+import lokahi.core.common.collection.TMCSet;
+import lokahi.core.common.exception.AuthorizationException;
+import lokahi.core.common.exception.TMCException;
+import lokahi.core.common.exception.TMCIllegalArgumentException;
+import org.apache.log4j.Logger;
+import org.apache.struts.action.ActionMessage;
+import org.apache.struts.action.ActionMessages;
+import org.apache.struts.validator.DynaValidatorForm;
+
+import java.sql.SQLException;
+import java.util.Collection;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: UserAction.java,v 1.2 2006/03/07 22:05:24 drtobes Exp $
+ */
+public class UserAction extends TMCAction {
+  static final Logger logger = Logger.getLogger(UserAction.class);
+
+  public ActionMessages executeFunctions(DynaValidatorForm form, Function f, User user) {
+    ActionMessages messages = new ActionMessages();
+    try {
+      UserModel um = new UserModel();
+      if ("AddUser".equalsIgnoreCase(f.getCommand()) || "UpdateUser".equalsIgnoreCase(f.getCommand())) {
+        User newu = getTemplate(form, user);
+        um.perform(f, new Class[]{user.getClass(), newu.getClass(), f.getClass()}, new Object[]{user, newu, f});
+      } else if ("AddUserToProject".equalsIgnoreCase(f.getCommand())) {
+        addUserToProject(form, user, f);
+      } else {
+        Collection<User> c = getMultiTemplate(form);
+        um.perform(f, new Class[]{user.getClass(), Collection.class, f.getClass()}, new Object[]{user, c, f});
+      }
+    } catch (AuthorizationException e) {
+      messages = this.addMessage(messages, new ActionMessage("error.notAuthorized"));
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.db"));
+    } catch (TMCIllegalArgumentException e) {
+      messages = this.addMessage(messages, new ActionMessage("error.badData"));
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    } catch (NoSuchMethodException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.invalidFunction", f.getCommand()));
+    } catch (TMCException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      messages = this.addMessage(messages, new ActionMessage("error.badData"));
+    }
+    return messages;
+  }
+
+  private Collection<User> getMultiTemplate(DynaValidatorForm dynaForm) throws SQLException {
+    Collection<User> c = new TMCSet<User>();
+    String[] ids = (String[]) dynaForm.get("id");
+    if (ids != null && ids.length > 0) {
+      StringBuffer names = new StringBuffer();
+      for (final String newVar : ids) {
+        if (!"".equals(newVar)) {
+          User u = User.getUser(Integer.parseInt(newVar));
+          if (u != null) {
+            c.add(u);
+            names.append(u.getName());
+            names.append(',');
+          }
+        }
+      }
+    }
+    return c;
+  }
+
+  private User getTemplate(DynaValidatorForm dynaForm, User user) throws SQLException {
+    User u = new User();
+    String Id = null;
+    if (dynaForm.getMap().containsKey("userId")) {
+      Id = (String) dynaForm.get("userId");
+    }
+    String name = (String) dynaForm.get("userName");
+    String firstName = (String) dynaForm.get("firstName");
+    String lastName = (String) dynaForm.get("lastName");
+    String email = (String) dynaForm.get("email");
+    String comments = (String) dynaForm.get("comments");
+    String jobTitle = (String) dynaForm.get("jobTitle");
+    String[] projects = (String[]) dynaForm.get("projects");
+    if (Id != null && !"".equals(Id)) {
+      u.setPk(Integer.parseInt(Id));
+    }
+    u.setName(name);
+    u.setFirstName(firstName);
+    u.setLastName(lastName);
+    u.setEmail(email);
+    u.setComments(comments);
+    u.setJobTitle(jobTitle);
+    Collection<Project> c = new TMCSet<Project>();
+    if (projects.length > 0) {
+      if (logger.isDebugEnabled()) {
+        logger.debug("projects.length = " + projects.length);
+      }
+      for (final String newVar : projects) {
+        if (!"".equals(newVar)) {
+          Project p = Project.getProject(Integer.parseInt(newVar));
+          if (user.isAllowed("AddUserToProject", newVar)) {
+            c.add(p);
+          }
+        }
+      }
+    }
+    return u;
+  }
+
+  private void addUserToProject(DynaValidatorForm form, User user, Function f) throws SQLException, AuthorizationException, TMCIllegalArgumentException {
+    UserModel um = new UserModel();
+    if (!user.isAllowed(f) && form.getMap().containsKey("global")) {
+      throw new AuthorizationException("User " + user.getName() + " not allowed to Add User to All projects");
+    }
+    if (form.getMap().containsKey("global")) {
+      String newUserName = (String) form.get("userName");
+      String[] functions = (String[]) form.get("functions");
+      um.addUserToProject(user, f, newUserName, functions);
+    } else if ("-1".equals(form.get("projectId"))) {
+      throw new TMCIllegalArgumentException("Project Id cannot be equal to -1");
+    } else {
+      Project p = Project.getProject(Integer.parseInt((String) form.get("projectId")));
+      if (p == null) throw new TMCIllegalArgumentException("Project not found");
+      String[] contextFunctions = (String[]) form.get("contextFunction");
+      String[] vhostFunctions = (String[]) form.get("vhostFunctions");
+      String newUserName = (String) form.get("userName");
+      um.addUserToProject(user, f, newUserName, contextFunctions, vhostFunctions, p.getPk());
+    }
+  }
+
+}
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHost.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHost.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHost.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHost.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,756 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.httpd.api.entity;
+
+import lokahi.core.api.environment.Environment;
+import lokahi.core.api.ipaddress.Ip;
+import lokahi.core.api.jobpool.JobPool;
+import lokahi.core.api.pool.HostingPool;
+import lokahi.core.api.pool.HostingPoolModel;
+import lokahi.core.api.server.Hardware;
+import lokahi.core.api.state.State;
+import lokahi.core.api.user.User;
+import lokahi.core.common.collection.TMCSet;
+import lokahi.core.common.database.BrokerFactory;
+import lokahi.core.common.exception.AuthorizationException;
+import lokahi.core.common.exception.TMCIllegalArgumentException;
+import lokahi.core.common.interfaces.FunctionableEntity;
+import lokahi.core.common.interfaces.TMCBroker;
+import lokahi.core.common.interfaces.TMCDao;
+import lokahi.core.common.util.PropertiesFile;
+import lokahi.httpd.api.pool.ApachePool;
+import lokahi.httpd.api.worker.ApacheWorker;
+import lokahi.tomcat.api.entity.TomcatContext;
+import org.apache.log4j.Logger;
+
+import java.io.IOException;
+import java.sql.Blob;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: VirtualHost.java,v 1.4 2006/03/07 22:05:24 drtobes Exp $
+ */
+public class VirtualHost extends FunctionableEntity<VirtualHost> {
+  static final Logger logger = Logger.getLogger(VirtualHost.class);
+  private static final TMCBroker<VirtualHost> broker = new BrokerFactory<VirtualHost>().getBroker();
+  private static final int objectId = 3;
+  private int pk;
+  private String name;
+  private int envId;
+  private int stateId;
+  private String entry = "";
+  private int externalProjectId;
+  private ApachePool ap;
+
+  private boolean catchAll;
+  private boolean nameBased;
+  private Collection<Ip> ips;
+  private Collection<TomcatContext> contexts;
+  private int hostingPoolId;
+
+  private HostingPool hostingPool;
+
+  private Environment env;
+  private State state;
+
+  public int getObjectId() {
+    return objectId;
+  }
+
+  public int getPk() {
+    return pk;
+  }
+
+  public void setPk(int pk) {
+    this.pk = pk;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public int getEnvId() {
+    return envId;
+  }
+
+  public void setEnvId(int envId) {
+    this.envId = envId;
+  }
+
+  public int getStateId() {
+    return stateId;
+  }
+
+  public void setStateId(int stateId) {
+    this.stateId = stateId;
+  }
+
+  public boolean isCatchAll() {
+    return catchAll;
+  }
+
+  public void setCatchAll(boolean catchAll) {
+    this.catchAll = catchAll;
+  }
+
+  public int getCatchAll() {
+    return catchAll ? 1 : 0;
+  }
+
+  public void setCatchAll(int catchAll) {
+    this.catchAll = catchAll == 1;
+  }
+
+  public int getNameBased() {
+    return nameBased ? 1 : 0;
+  }
+
+  public void setNameBased(int nameBased) {
+    this.nameBased = nameBased == 1;
+  }
+
+  public boolean isNameBased() {
+    return nameBased;
+  }
+
+  public void setNameBased(boolean nameBased) {
+    this.nameBased = nameBased;
+  }
+
+  public int getExternalProjectId() {
+    return externalProjectId;
+  }
+
+  public void setExternalProjectId(int externalProjectId) {
+    this.externalProjectId = externalProjectId;
+  }
+
+  public void setEntry(byte[] content) throws SQLException {
+    if (content != null) {
+      this.entry = new String(content);
+    } else {
+      this.entry = "";
+    }
+  }
+
+  public Collection<TomcatContext> getContexts() {
+    if (contexts == null) {
+      try {
+        contexts = TomcatContext.getTomcatContexts(this);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    if (logger.isDebugEnabled()) {
+      logger.debug("contexts=" + contexts);
+    }
+    return contexts;
+  }
+
+  public Collection<TomcatContext> getContextsNoDB() {
+    if (contexts == null) {
+      contexts = new TMCSet<TomcatContext>();
+    }
+    return contexts;
+  }
+
+  public void setContexts(Collection<TomcatContext> contexts) {
+    this.contexts = contexts;
+  }
+
+  public void setIps(Collection<Ip> ips) {
+    this.ips = ips;
+  }
+
+  public void setHostingPool(HostingPool hostingPool) {
+    this.hostingPool = hostingPool;
+    if (hostingPool != null) {
+      this.setHostingPoolId(hostingPool.getPk());
+    }
+  }
+
+  public int getHostingPoolId() {
+    return hostingPoolId;
+  }
+
+  public void setHostingPoolId(int hostingPoolId) {
+    this.hostingPoolId = hostingPoolId;
+    if (this.hostingPool != null && this.hostingPoolId != this.hostingPool.getPk()) {
+      this.setHostingPool(null);
+    }
+  }
+
+  public String getEntry() {
+    if (entry == null) {
+      entry = "";
+    }
+    return entry;
+  }
+
+  public void setEntry(String entry) {
+    this.entry = entry;
+  }
+
+  public State getState() {
+    if (state == null) {
+      this.state = State.getState(this.getStateId());
+    }
+    return state;
+  }
+
+  public void setState(State state) {
+    this.state = state;
+    if (state != null) {
+      this.setStateId(state.getPk());
+    }
+  }
+
+  public Environment getEnv() {
+    if (env == null) {
+      try {
+        this.env = Environment.getEnviroment(this.getEnvId(), true);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    return env;
+  }
+
+  public void setEnv(Environment env) {
+    this.env = env;
+    if (env != null) {
+      this.setEnvId(env.getPk());
+    }
+  }
+
+  public FunctionableEntity getObject(int id) throws SQLException {
+    return getVirtualHost(id);
+  }
+
+  public FunctionableEntity getParent() {
+    return null;
+  }
+
+  public Collection<Ip> getIps() {
+    if (ips == null) {
+      try {
+        ips = Ip.getIps(this, true);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    return ips;
+  }
+
+  public Collection<Ip> getIpsNoDB() {
+    if (ips == null) {
+      ips = new TMCSet<Ip>();
+    }
+    return ips;
+  }
+
+  public VirtualHost() {
+  }
+
+  public VirtualHost(String name, String entry, Environment env, State state, HostingPool hp, boolean catchAll, boolean nameBased) {
+    this.setName(name);
+    this.setEntry(entry);
+    this.setEnv(env);
+    this.setState(state);
+    this.setHostingPool(hp);
+    this.setCatchAll(catchAll);
+    this.setNameBased(nameBased);
+  }
+
+  public VirtualHost(int pk, String name, int envId, int stateId, int hpId, int catchAll, int nameBased, int exPid, Blob entry) throws SQLException {
+    this.setPk(pk);
+    this.setName(name);
+    this.setEnvId(envId);
+    this.setStateId(stateId);
+    this.setHostingPoolId(hpId);
+    this.setCatchAll(catchAll);
+    this.setNameBased(nameBased);
+    this.setExternalProjectId(exPid);
+//    this.ap = ap;
+    if (entry != null)
+      this.setEntry(entry.getBytes(1, (int) entry.length()));
+  }
+
+  public VirtualHost(int pk, String name, int envId, int stateId, int hpId, int catchAll, int nameBased, int exPid, ApachePool ap, Blob entry) throws SQLException {
+    this.setPk(pk);
+    this.setName(name);
+    this.setEnvId(envId);
+    this.setStateId(stateId);
+    this.setHostingPoolId(hpId);
+    this.setCatchAll(catchAll);
+    this.setNameBased(nameBased);
+    this.setExternalProjectId(exPid);
+    this.ap = ap;
+    if (entry != null)
+      this.setEntry(entry.getBytes(1, (int) entry.length()));
+  }
+
+  public VirtualHost fillObject(ResultSet r) throws SQLException {
+    return new VirtualHost(r.getInt("VHOST_ID"),
+                           r.getString("VHOST_NAME"),
+                           r.getInt("ENV_ID"),
+                           r.getInt("STATE_ID"),
+                           r.getInt("HOSTING_POOL_ID"),
+                           r.getInt("CATCHALL"),
+                           r.getInt("NAMEBASED"),
+                           r.getInt("ex_project_id"),
+                           new ApachePool(r.getInt("POOL_ID"), r.getString("POOL_NAME"), r.getInt("POOL_ENV_ID")),
+                           r.getBlob("vhost_entry"));
+  }
+
+  /**
+   * @param hp
+   * @param newIps
+   * @param isNameBased
+   * @param isCatchAll
+   *
+   * @return
+   * @throws SQLException
+   */
+  public Collection<HostingPool> changeHostingPool(HostingPool hp, Collection<Ip> newIps, boolean isNameBased, boolean isCatchAll) throws SQLException {
+    Collection<HostingPool> ret = new TMCSet<HostingPool>();
+    ret.add(this.getHostingPool());
+    this.setHostingPool(hp);
+    this.removeIps(this.getIps());
+    this.addIps(newIps);
+    this.setNameBased(isNameBased);
+    this.setCatchAll(isCatchAll);
+    ret.add(hp);
+    return ret;
+  }
+
+  public void addIps(Collection<Ip> c) throws SQLException {
+    for (final Ip ip : c) {
+      this.addIp(ip);
+    }
+  }
+
+  public void addContexts(Collection<TomcatContext> c) throws SQLException {
+    for (TomcatContext tc : c) {
+      this.addContext(tc);
+    }
+  }
+
+  public void addIp(Ip ip) throws SQLException {
+    this.addRel("apache.entity.rel.ip.add", ip);
+  }
+
+  public void addContext(TomcatContext tc) throws SQLException {
+    this.addRel("apache.entity.rel.context.add", tc);
+  }
+
+  private void addRel(String statement, TMCDao dao) throws SQLException {
+    broker.modifyRelationship(statement, this.getPk(), dao.getPk());
+  }
+
+  public void removeIps(Collection<Ip> c) throws SQLException {
+    for (Ip ip : c) {
+      this.removeIp(ip);
+    }
+  }
+
+  public void removeContexts(Collection<TomcatContext> c) throws SQLException {
+    for (TomcatContext tc : c) {
+      this.removeContext(tc);
+    }
+  }
+
+  public void removeIp(Ip ip) throws SQLException {
+    this.removeRel("apache.entity.rel.ip.delete", ip);
+  }
+
+  public void removeContext(TomcatContext tc) throws SQLException {
+    this.removeRel("apache.entity.rel.context.delete", tc);
+  }
+
+  private void removeRel(String statement, TMCDao dao) throws SQLException {
+    broker.delete(statement, this.getPk(), dao.getPk());
+  }
+
+  public static void update(VirtualHost vh) throws SQLException {
+    broker.update("apache.entity.update", vh.getPk(), vh.getName(), vh.getStateId(), vh.getEnvId(), vh.getHostingPoolId(), vh.getCatchAll(), vh.getNameBased(), vh.getExternalProjectId(), (vh.getEntry()).getBytes());
+  }
+
+  public static boolean delete(Collection<VirtualHost> c, User u, JobPool jp) throws SQLException, TMCIllegalArgumentException, AuthorizationException {
+    Collection<HostingPool> modifiedHPs = new TMCSet<HostingPool>();
+    if (c != null) {
+      for (final VirtualHost vh : c) {
+        modifiedHPs.add(vh.getHostingPool());
+        delete(vh);
+      }
+    }
+    HostingPoolModel hpm = new HostingPoolModel();
+    try {
+      hpm.deployApacheConfs(null, u, jp, modifiedHPs);
+    } catch (IOException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    }
+    return true;
+  }
+
+  public static boolean delete(VirtualHost vh) throws SQLException {
+    return broker.delete("apache.entity.delete", vh.getPk());
+  }
+
+  public static VirtualHost store(VirtualHost vh) throws SQLException {
+    vh.setPk(broker.save("apache.entity.store", vh.getName(), vh.getStateId(), vh.getEnvId(), vh.getHostingPoolId(), vh.getCatchAll(), vh.getNameBased(), vh.getExternalProjectId(), (vh.getEntry()).getBytes()));
+    vh.addContexts(vh.getContextsNoDB());
+    vh.addIps(vh.getIpsNoDB());
+    return vh;
+  }
+
+  public static Collection<VirtualHost> getVirtualHosts() throws SQLException {
+    Collection<VirtualHost> c;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.all");
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return c;
+  }
+
+  public static Collection<VirtualHost> getVirtualHosts(String name) throws SQLException {
+    Collection<VirtualHost> c;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.by.name", name);
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return c;
+  }
+
+  public ApachePool getApachePool() {
+    if (ap == null) {
+      try {
+        this.ap = ApachePool.getApachePool(this);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    return ap;
+  }
+
+  public boolean isDefault() {
+    boolean ret = false;
+    if (this.getIps() != null) {
+      Iterator i = ips.iterator();
+      while (i.hasNext() && !ret) {
+        Ip ip = (Ip) i.next();
+        if (ip.getName().trim().startsWith("_default_")) {
+          ret = true;
+        }
+      }
+    }
+    return ret;
+  }
+
+  public Collection<HostingPool> getPotentialHostingPools() {
+    ApachePool ap = this.getApachePool();
+    Collection<HostingPool> c = null;
+    if (ap != null) {
+      try {
+        c = HostingPool.getHostingPools(ap, true);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    return c;
+  }
+
+  public HostingPool getHostingPool() {
+    if (hostingPool == null) {
+      try {
+        hostingPool = HostingPool.getHostingPool(hostingPoolId, true);
+      } catch (SQLException e) {
+        if (logger.isInfoEnabled()) {
+          logger.info("Exception: " + e.getMessage());
+        }
+      }
+    }
+    return hostingPool;
+  }
+
+  public static Collection<VirtualHost> getVirtualHosts(int pId) throws SQLException {
+    Collection<VirtualHost> c;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.by.projectid", pId);
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return c;
+  }
+
+  public static Collection<VirtualHost> getVirtualHosts(HostingPool hp) throws SQLException {
+    Collection<VirtualHost> c;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.by.hostingpool", hp.getPk());
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return c;
+  }
+
+  public static Collection<VirtualHost> getVirtualHosts(ApacheWorker aw) throws SQLException {
+    Collection<VirtualHost> c;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.by.worker", aw.getPk());
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return c;
+  }
+
+  public static VirtualHost getVirtualHost(int id) throws SQLException {
+    VirtualHost vh = new VirtualHost();
+    return vh.get(id);
+  }
+
+  public Ip getIp(Hardware h) {
+    Ip ret = null;
+    Collection<Ip> c = this.getIps();
+    if (c != null && h != null) {
+      Iterator i = c.iterator();
+      while (ret == null && i.hasNext()) {
+        Ip ip = (Ip) i.next();
+        if (h.hasIp(ip)) {
+          ret = ip;
+        }
+      }
+    }
+    return ret;
+  }
+
+  public StringBuffer buildVhostEntry(Hardware h) {
+    final StringBuffer ret = new StringBuffer();
+    if (this.getIp(h) != null) {
+      ret.append("<VirtualHost ");
+      ret.append(this.getIp(h).getName());
+      ret.append(":80>\n");
+      ret.append(this.buildFullEntry());
+      ret.append("</VirtualHost>\n");
+    }
+    return ret;
+  }
+
+  private StringBuffer buildFullEntry() {
+    StringBuffer ret = new StringBuffer();
+    ret.append("ServerName ");
+    ret.append(this.getName());
+    ret.append('\n');
+    ret.append(this.getEntry());
+    if (!ret.toString().endsWith("\n")) {
+      ret.append('\n');
+    }
+    if (this.getContexts() != null && !this.getContexts().isEmpty()) {
+      ret.append("<IfModule mod_jk.c>\n");
+      for (final TomcatContext tc : this.getContexts()) {
+        if (tc != null) {
+          ret.append("JkMount ");
+          ret.append(tc.getName().trim());
+          ret.append("/* ");
+          ret.append(tc.getWorkerName());
+          ret.append('\n');
+        }
+      }
+      ret.append("</IfModule>\n");
+    }
+    return ret;
+  }
+
+  public String buildVhostEntriesForWeb() {
+    String ret;
+    Collection<Ip> c = this.getIps();
+    StringBuffer sb = new StringBuffer();
+    sb.append("IPs hosted on:\n\n");
+    for (final Ip ip : c) {
+      sb.append(ip.getName());
+      sb.append('\n');
+    }
+    sb.append('\n');
+    sb.append("<VirtualHost 'ABOVE IPs':80>\n");
+    sb.append(this.buildFullEntry());
+    sb.append("</VirtualHost>\n");
+    ret = sb.toString().replaceAll(">", "&gt;");
+    ret = ret.replaceAll("<", "&lt;");
+    ret = ret.replaceAll("\n", "<BR>");
+    return ret;
+  }
+
+  public String getLogDirective(String directive) {
+    String work = this.getEntry();
+    String ret = "";
+    if (work != null) {
+      int errorIndex = work.toLowerCase().indexOf(directive);
+      if (errorIndex >= 0) {
+        work = work.substring(errorIndex + directive.length());
+        errorIndex = work.indexOf("\n");
+        if (errorIndex != -1) {
+          work = work.substring(0, errorIndex);
+        }
+        work = work.trim();
+        errorIndex = work.lastIndexOf("/");
+        work = work.substring(0, errorIndex);
+        work = work.trim();
+        if (logger.isDebugEnabled()) {
+          logger.debug("Setting ret to " + work);
+        }
+        ret = work;
+      }
+    }
+    return ret;
+  }
+
+  public static Collection<VirtualHost> getVirtualHost(String pattern) {
+    Collection<VirtualHost> c = null;
+    try {
+      c = broker.getObjects(VirtualHost.class, false, "apache.entity.by.name", pattern);
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+    }
+    return c;
+  }
+
+  public StringBuilder buildShortXMLRepresentation() {
+    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(5, 1);
+    map.put("id", Integer.toString(this.getPk()));
+    map.put("name", this.getName());
+    map.put("envId", Integer.toString(this.getEnvId()));
+    map.put("hpId", Integer.toString(this.getHostingPoolId()));
+    map.put("href", PropertiesFile.getConstantValue("rest.servlet.url") + "virtualhost/" + this.getPk() + '/');
+    return elementBuilder("virtualhost", map);
+  }
+
+  public StringBuilder buildXMLRepresention() {
+    StringBuilder ret = new StringBuilder();
+    ret.append("<virtualhost>\n");
+    ret.append(elementBuilder("id", Integer.toString(this.getPk())));
+    ret.append(elementBuilder("name", this.getName()));
+    ret.append(elementBuilder("catchAll", Boolean.toString(this.isCatchAll())));
+    ret.append(elementBuilder("nameBased", Boolean.toString(this.isNameBased())));
+    ret.append(elementBuilder("entry", this.getEntry()));
+    ret.append(this.getHostingPool().buildShortXMLRepresentation());
+    ret.append(this.getEnv().buildShortXMLRepresentation());
+    ret.append(this.getState().buildShortXMLRepresentation());
+    for (final Ip ip : this.getIps()) {
+      ret.append(ip.buildXMLRepresention());
+    }
+    for (TomcatContext tc : this.getContexts()) {
+      ret.append(tc.buildShortXMLRepresentation());
+    }
+    ret.append("</virtualhost>\n");
+    return ret;
+  }
+
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (!(o instanceof VirtualHost)) return false;
+
+    final VirtualHost virtualHost = (VirtualHost) o;
+
+    if (envId != virtualHost.envId) return false;
+    if (pk != virtualHost.pk) return false;
+    if (stateId != virtualHost.stateId) return false;
+    if (entry != null ? !entry.equals(virtualHost.entry) : virtualHost.entry != null) return false;
+    if (name != null ? !name.equals(virtualHost.name) : virtualHost.name != null) return false;
+
+    return true;
+  }
+
+  public int hashCode() {
+    int result;
+    result = pk;
+    result = 29 * result + (name != null ? name.hashCode() : 0);
+    result = 29 * result + envId;
+    result = 29 * result + stateId;
+    result = 29 * result + (entry != null ? entry.hashCode() : 0);
+    return result;
+  }
+
+  public String toString() {
+    final StringBuffer buf = new StringBuffer();
+    buf.append("VirtualHost");
+    buf.append("{pk=").append(pk);
+    buf.append(",name=").append(name);
+    buf.append(",envId=").append(envId);
+    buf.append(",stateId=").append(stateId);
+    buf.append(",entry=").append(entry);
+    buf.append(",env=").append(env);
+    buf.append(",state=").append(state);
+    buf.append('}');
+    return buf.toString();
+  }
+
+  public VirtualHost get(int id) throws SQLException {
+    VirtualHost vh;
+    try {
+      vh = broker.getObject(VirtualHost.class, "apache.entity.by.id", false, id);
+    } catch (SQLException e) {
+      if (logger.isInfoEnabled()) {
+        logger.info("Exception: " + e.getMessage());
+      }
+      throw e;
+    }
+    return vh;
+  }
+}
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHostModel.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHostModel.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHostModel.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/entity/VirtualHostModel.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,146 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.httpd.api.entity;
+
+import lokahi.core.api.function.Function;
+import lokahi.core.api.job.Job;
+import lokahi.core.api.jobpool.JobPool;
+import lokahi.core.api.pool.HostingPool;
+import lokahi.core.api.state.State;
+import lokahi.core.api.user.User;
+import lokahi.core.common.collection.TMCSet;
+import lokahi.core.common.exception.AuthorizationException;
+import lokahi.core.common.exception.TMCIllegalArgumentException;
+import lokahi.core.common.interfaces.LokahiModel;
+import lokahi.httpd.api.pool.ApachePool;
+import lokahi.httpd.api.worker.ApacheWorker;
+import lokahi.httpd.api.worker.ApacheWorkerModel;
+
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.Collection;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: VirtualHostModel.java,v 1.3 2006/03/07 20:18:53 drtobes Exp $
+ */
+public class VirtualHostModel extends LokahiModel<VirtualHost> {
+
+  public void addVirtualHost(User u, VirtualHost a, Function f) throws AuthorizationException, TMCIllegalArgumentException, SQLException, IOException {
+    this.jpInit(f, u, a.getName());
+    if (u.isAllowed(f) && "AddVirtualHost".equals(f.getCommand())) {
+      VirtualHost.store(a);
+    } else {
+      throw new AuthorizationException("User " + u.getName() + " Not allowed to " + f.getName());
+    }
+    jp.setState(State.COMPLETE);
+    JobPool.update(jp);
+  }
+
+  public void deleteVirtualHost(User u, VirtualHost vh, Function f) throws SQLException, AuthorizationException, TMCIllegalArgumentException {
+    if (vh == null || vh.getPk() < 1) throw new TMCIllegalArgumentException("Virtualhost can not be null");
+    this.jpInit(f, u, vh.getName());
+    this.deleteVHost(u, vh, f);
+    jp.setState(State.COMPLETE);
+    JobPool.update(jp);
+  }
+
+  private void deleteVHost(User u, VirtualHost vh, Function f) throws AuthorizationException, SQLException {
+    if (u.isAllowed(f) && "DeleteVirtualHost".equals(f.getCommand())) {
+      VirtualHost.delete(vh);
+    } else {
+      throw new AuthorizationException("User " + u.getName() + " Not allowed to " + f.getName());
+    }
+  }
+
+  public void deleteVirtualHost(User u, Collection<VirtualHost> c, Function f) throws SQLException, AuthorizationException, TMCIllegalArgumentException {
+    this.jpInit(f, u);
+    StringBuffer names = new StringBuffer();
+    for (final VirtualHost vh : c) {
+      names.append(vh.getName());
+      names.append(',');
+      this.deleteVHost(u, vh, f);
+    }
+    jp.setOptions(names.toString());
+    jp.setState(State.COMPLETE);
+    JobPool.update(jp);
+  }
+
+  public void updateVirtualHost(User u, VirtualHost vh, Function f) throws AuthorizationException, TMCIllegalArgumentException, SQLException, IOException, TMCIllegalArgumentException {
+    this.jpInit(f, u, vh.getName());
+    if (u.isAllowed(f) && "UpdateVirtualHost".equals(f.getCommand())) {
+      if (vh.getPk() > 1 && vh.getName() != null && !"".equals(vh.getName())) {
+        VirtualHost.update(vh);
+        HostingPool hp = vh.getHostingPool();
+        ApachePool ap = hp.getApachePool();
+        ApacheWorkerModel awm = new ApacheWorkerModel();
+        Collection<ApacheWorker> c = ap.getApaches();
+        for (final ApacheWorker aw : c) {
+          this.createLogDirs(aw, vh);
+          awm.deployApacheConfig(f, jp, aw);
+        }
+      } else {
+        throw new TMCIllegalArgumentException("VirtualHost can not be null");
+      }
+    } else {
+      throw new AuthorizationException("User " + u.getName() + " Not allowed to " + f.getName());
+    }
+    jp.setState(State.COMPLETE);
+    JobPool.update(jp);
+  }
+
+  public Collection<VirtualHost> getObjects() throws SQLException {
+    return new TMCSet<VirtualHost>(VirtualHost.getVirtualHosts());
+  }
+
+  public VirtualHost getObject(int id) throws SQLException {
+    return VirtualHost.getVirtualHost(id);
+  }
+
+  public VirtualHost viewVirtualHost(int id) throws SQLException {
+    return VirtualHost.getVirtualHost(id);
+  }
+
+  public Collection<VirtualHost> viewVirtualHosts() throws SQLException {
+    return VirtualHost.getVirtualHosts();
+  }
+
+  private void createLogDirs(ApacheWorker aw, VirtualHost vh) throws SQLException, IOException {
+    String errorLog = vh.getLogDirective("errorLog");
+    String customLog = vh.getLogDirective("customlog");
+    Job j1 = null;
+    if (errorLog != null && !"".equals(errorLog)) {
+      j1 = new Job(errorLog, aw.getHardware(), Function.getFunction("MakeDir"), jp);
+      j1 = Job.store(j1);
+    }
+    Job j2;
+    if (customLog != null && !"".equals(customLog)) {
+      if (j1 != null) {
+        j2 = new Job(j1, customLog, aw.getHardware(), Function.getFunction("MakeDir"), jp);
+      } else {
+        j2 = new Job(customLog, aw.getHardware(), Function.getFunction("MakeDir"), jp);
+      }
+      Job.store(j2);
+    }
+  }
+
+}
+
+
+
+
+
+

Added: incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/pool/AMPoolWorker.java
URL: http://svn.apache.org/viewcvs/incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/pool/AMPoolWorker.java?rev=392982&view=auto
==============================================================================
--- incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/pool/AMPoolWorker.java (added)
+++ incubator/lokahi/lokahi/trunk/src/java/lokahi/httpd/api/pool/AMPoolWorker.java Mon Apr 10 09:19:33 2006
@@ -0,0 +1,121 @@
+/*
+* Copyright 2006  The Apache Software Foundation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package lokahi.httpd.api.pool;
+
+import lokahi.core.common.database.BrokerFactory;
+import lokahi.core.common.interfaces.Cacheable;
+import lokahi.core.common.interfaces.TMCBroker;
+import lokahi.httpd.api.worker.ApacheWorker;
+import org.apache.log4j.Logger;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collection;
+
+/**
+ * @author Stephen Toback
+ * @version $Id: AMPoolWorker.java,v 1.4 2006/03/07 20:18:52 drtobes Exp $
+ */
+public class AMPoolWorker implements Cacheable {
+  static final Logger logger = Logger.getLogger(AMPoolWorker.class);
+  private static final TMCBroker<AMPoolWorker> broker = new BrokerFactory<AMPoolWorker>().getBroker();
+
+  private int poolId;
+  private int workerId;
+
+  public AMPoolWorker() {
+  }
+
+  public AMPoolWorker(int poolId, int workerId) {
+    this.poolId = poolId;
+    this.workerId = workerId;
+  }
+
+  public AMPoolWorker(ApachePool ap, ApacheWorker aw) {
+    if (ap != null && aw != null) {
+      this.poolId = ap.getPk();
+      this.workerId = aw.getPk();
+    }
+  }
+
+  public int getPoolId() {
+    return poolId;
+  }
+
+  public void setPoolId(int poolId) {
+    this.poolId = poolId;
+  }
+
+  public int getWorkerId() {
+    return workerId;
+  }
+
+  public void setWorkerId(int workerId) {
+    this.workerId = workerId;
+  }
+
+  public AMPoolWorker fillObject(ResultSet r) throws SQLException {
+    return new AMPoolWorker(r.getInt("POOL_ID"), r.getInt("WORKER_ID"));
+  }
+
+  public ApacheWorker getWorker() throws SQLException {
+    return ApacheWorker.getApacheWorker(workerId, false);
+  }
+
+  public ApachePool getPool() throws SQLException {
+    return ApachePool.getApachePool(poolId);
+  }
+
+  public static void save(AMPoolWorker rel) throws SQLException {
+    broker.modifyRelationship("apache.pool.rel.worker.add", rel.getPoolId(), rel.getWorkerId());
+  }
+
+  public static void delete(AMPoolWorker rel) throws SQLException {
+    broker.modifyRelationship("apache.pool.rel.worker.delete", rel.getPoolId(), rel.getWorkerId());
+  }
+
+  public Collection<AMPoolWorker> getAll() throws SQLException {
+    return broker.getObjects(AMPoolWorker.class, false, "apache.pool.rel.worker.all");
+  }
+
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (!(o instanceof AMPoolWorker)) return false;
+
+    final AMPoolWorker amPoolWorker = (AMPoolWorker) o;
+
+    if (poolId != amPoolWorker.poolId) return false;
+    if (workerId != amPoolWorker.workerId) return false;
+
+    return true;
+  }
+
+  public int hashCode() {
+    int result;
+    result = poolId;
+    result = 29 * result + workerId;
+    return result;
+  }
+
+  public String toString() {
+    return "AMPoolWorker{" +
+        "poolId=" + poolId +
+        ", workerId=" + workerId +
+        '}';
+  }
+}
+
+



Mime
View raw message