Home » geronimo-2.2-source-release » org.apache.geronimo.console.databasemanager.wizard » [javadoc | source]

    1   /**
    2    *  Licensed to the Apache Software Foundation (ASF) under one or more
    3    *  contributor license agreements.  See the NOTICE file distributed with
    4    *  this work for additional information regarding copyright ownership.
    5    *  The ASF licenses this file to You under the Apache License, Version 2.0
    6    *  (the "License"); you may not use this file except in compliance with
    7    *  the License.  You may obtain a copy of the License at
    8    *
    9    *     http://www.apache.org/licenses/LICENSE-2.0
   10    *
   11    *  Unless required by applicable law or agreed to in writing, software
   12    *  distributed under the License is distributed on an "AS IS" BASIS,
   13    *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    *  See the License for the specific language governing permissions and
   15    *  limitations under the License.
   16    */
   17   package org.apache.geronimo.console.databasemanager.wizard;
   18   
   19   import java.io.BufferedOutputStream;
   20   import java.io.ByteArrayOutputStream;
   21   import java.io.File;
   22   import java.io.FileOutputStream;
   23   import java.io.FileReader;
   24   import java.io.IOException;
   25   import java.io.PrintWriter;
   26   import java.io.Serializable;
   27   import java.io.StringReader;
   28   import java.io.StringWriter;
   29   import java.io.UnsupportedEncodingException;
   30   import java.net.MalformedURLException;
   31   import java.net.URI;
   32   import java.net.URL;
   33   import java.net.URLClassLoader;
   34   import java.net.URLDecoder;
   35   import java.net.URLEncoder;
   36   import java.sql.Connection;
   37   import java.sql.DatabaseMetaData;
   38   import java.sql.Driver;
   39   import java.sql.SQLException;
   40   import java.util.ArrayList;
   41   import java.util.Arrays;
   42   import java.util.Collections;
   43   import java.util.Comparator;
   44   import java.util.HashMap;
   45   import java.util.HashSet;
   46   import java.util.LinkedHashMap;
   47   import java.util.List;
   48   import java.util.Map;
   49   import java.util.Properties;
   50   import java.util.Random;
   51   import java.util.Set;
   52   import java.util.SortedSet;
   53   
   54   import javax.enterprise.deploy.model.DDBean;
   55   import javax.enterprise.deploy.model.DDBeanRoot;
   56   import javax.enterprise.deploy.shared.ModuleType;
   57   import javax.enterprise.deploy.spi.DeploymentConfiguration;
   58   import javax.enterprise.deploy.spi.DeploymentManager;
   59   import javax.enterprise.deploy.spi.Target;
   60   import javax.enterprise.deploy.spi.TargetModuleID;
   61   import javax.enterprise.deploy.spi.status.ProgressObject;
   62   import javax.portlet.ActionRequest;
   63   import javax.portlet.ActionResponse;
   64   import javax.portlet.PortletConfig;
   65   import javax.portlet.PortletException;
   66   import javax.portlet.PortletRequest;
   67   import javax.portlet.PortletRequestDispatcher;
   68   import javax.portlet.PortletSession;
   69   import javax.portlet.RenderRequest;
   70   import javax.portlet.RenderResponse;
   71   import javax.portlet.WindowState;
   72   import javax.xml.parsers.DocumentBuilder;
   73   import javax.xml.parsers.DocumentBuilderFactory;
   74   
   75   import org.apache.commons.fileupload.FileItem;
   76   import org.apache.commons.fileupload.disk.DiskFileItemFactory;
   77   import org.apache.commons.fileupload.portlet.PortletFileUpload;
   78   import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting;
   79   import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition;
   80   import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance;
   81   import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager;
   82   import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot;
   83   import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB;
   84   import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter;
   85   import org.apache.geronimo.connector.deployment.jsr88.SinglePool;
   86   import org.apache.geronimo.connector.outbound.PoolingAttributes;
   87   import org.apache.geronimo.console.BasePortlet;
   88   import org.apache.geronimo.console.ajax.ProgressInfo;
   89   import org.apache.geronimo.console.databasemanager.ManagementHelper;
   90   import org.apache.geronimo.console.util.PortletManager;
   91   import org.apache.geronimo.converter.DatabaseConversionStatus;
   92   import org.apache.geronimo.converter.JDBCPool;
   93   import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter;
   94   import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter;
   95   import org.apache.geronimo.deployment.service.jsr88.EnvironmentData;
   96   import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable;
   97   import org.apache.geronimo.gbean.AbstractName;
   98   import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
   99   import org.apache.geronimo.kernel.config.ConfigurationManager;
  100   import org.apache.geronimo.kernel.config.ConfigurationUtil;
  101   import org.apache.geronimo.kernel.management.State;
  102   import org.apache.geronimo.kernel.proxy.GeronimoManagedBean;
  103   import org.apache.geronimo.kernel.repository.Artifact;
  104   import org.apache.geronimo.kernel.repository.FileWriteMonitor;
  105   import org.apache.geronimo.kernel.repository.ListableRepository;
  106   import org.apache.geronimo.kernel.repository.WriteableRepository;
  107   import org.apache.geronimo.kernel.util.XmlUtil;
  108   import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory;
  109   import org.apache.geronimo.management.geronimo.ResourceAdapterModule;
  110   import org.slf4j.Logger;
  111   import org.slf4j.LoggerFactory;
  112   import org.w3c.dom.Document;
  113   import org.w3c.dom.Element;
  114   import org.w3c.dom.Node;
  115   import org.w3c.dom.NodeList;
  116   import org.xml.sax.InputSource;
  117   
  118   /**
  119    * A portlet that lets you configure and deploy JDBC connection pools.
  120    *
  121    * @version $Rev: 810492 $ $Date: 2009-09-02 05:54:37 -0700 (Wed, 02 Sep 2009) $
  122    */
  123   public class DatabasePoolPortlet extends BasePortlet {
  124       private static final Logger log = LoggerFactory.getLogger(DatabasePoolPortlet.class);
  125       private final static Set<String> INCLUDE_ARTIFACTIDS = new HashSet<String>(Arrays.asList("system-database"));
  126   
  127       private final static Set<String> EXCLUDE_GROUPIDS = new HashSet<String>(Arrays.asList("org.apache.geronimo.modules",
  128               "org.apache.geronimo.configs",
  129               "org.apache.geronimo.applications",
  130               "org.apache.geronimo.assemblies",
  131               "org.apache.cxf",
  132               "org.apache.tomcat",
  133               "org.tranql",
  134               "commons-cli",
  135               "commons-io",
  136               "commons-logging",
  137               "commons-lang",
  138               "axis",
  139               "org.apache.axis2",
  140               "org.apache.directory",
  141               "org.apache.activemq",
  142               "org.apache.openejb",
  143               "org.apache.myfaces",
  144               "org.mortbay.jetty"));
  145       private final static String DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers";
  146       private final static String CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam";
  147       private final static String DRIVER_INFO_URL = "http://geronimo.apache.org/driver-downloads.properties";
  148       private static final String LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp";
  149       private static final String EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp";
  150       private static final String SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp";
  151       private static final String BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp";
  152       private static final String CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp";
  153       private static final String TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp";
  154       private static final String DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp";
  155       private static final String DOWNLOAD_STATUS_VIEW = "/WEB-INF/view/dbwizard/downloadStatus.jsp";
  156       private static final String SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp";
  157       private static final String IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp";
  158       private static final String IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp";
  159       private static final String USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp";
  160       private static final String LIST_MODE = "list";
  161       private static final String EDIT_MODE = "edit";
  162       private static final String SELECT_RDBMS_MODE = "rdbms";
  163       private static final String BASIC_PARAMS_MODE = "params";
  164       private static final String CONFIRM_URL_MODE = "url";
  165       private static final String TEST_CONNECTION_MODE = "test";
  166       private static final String SHOW_PLAN_MODE = "plan";
  167       private static final String DOWNLOAD_MODE = "download";
  168       private static final String DOWNLOAD_STATUS_MODE = "downloadStatus";
  169       private static final String EDIT_EXISTING_MODE = "editExisting";
  170       private static final String DELETE_MODE = "delete";
  171       private static final String SAVE_MODE = "save";
  172       private static final String IMPORT_START_MODE = "startImport";
  173       private static final String IMPORT_UPLOAD_MODE = "importUpload";
  174       private static final String IMPORT_STATUS_MODE = "importStatus";
  175       private static final String IMPORT_COMPLETE_MODE = "importComplete";
  176       private static final String WEBLOGIC_IMPORT_MODE = "weblogicImport";
  177       private static final String USAGE_MODE = "usage";
  178       private static final String IMPORT_EDIT_MODE = "importEdit";
  179       private static final String MODE_KEY = "mode";
  180       private static final String LOCAL = "LOCAL";
  181       private static final String XA = "XA";
  182       private static final String NONE = "NONE";
  183       private static final String[] ORDERED_PROPERTY_NAMES = { "property-DatabaseName", "property-CreateDatabase", "property-UserName", "property-Password" };
  184   
  185       private PortletRequestDispatcher listView;
  186       private PortletRequestDispatcher editView;
  187       private PortletRequestDispatcher selectRDBMSView;
  188       private PortletRequestDispatcher basicParamsView;
  189       private PortletRequestDispatcher confirmURLView;
  190       private PortletRequestDispatcher testConnectionView;
  191       private PortletRequestDispatcher downloadView;
  192       private PortletRequestDispatcher downloadStatusView;
  193       private PortletRequestDispatcher planView;
  194       private PortletRequestDispatcher importUploadView;
  195       private PortletRequestDispatcher importStatusView;
  196       private PortletRequestDispatcher usageView;
  197       private Map<String, String> rarPathMap;
  198   
  199       public void init(PortletConfig portletConfig) throws PortletException {
  200           super.init(portletConfig);
  201           listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW);
  202           editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW);
  203           selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW);
  204           basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW);
  205           confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW);
  206           testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW);
  207           downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW);
  208           downloadStatusView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_STATUS_VIEW);
  209           planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW);
  210           importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW);
  211           importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW);
  212           usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW);
  213           rarPathMap = new HashMap<String, String>();
  214           rarPathMap.put("TranQL XA Resource Adapter for DB2", "tranql-connector-db2-xa");
  215           rarPathMap.put("TranQL Client Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-client-local");
  216           rarPathMap.put("TranQL Client XA Resource Adapter for Apache Derby", "tranql-connector-derby-client-xa");
  217   //      rarPathMap.put("TranQL Embedded Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local");
  218   //      rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-xa");
  219           rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local");
  220           rarPathMap.put("TranQL XA Resource Adapter for Informix", "tranql-connector-informix-xa");
  221           rarPathMap.put("TranQL Client Local Transaction Resource Adapter for MySQL", "tranql-connector-mysql-local");
  222           rarPathMap.put("TranQL Client XA Resource Adapter for MySQL", "tranql-connector-mysql-xa");
  223           rarPathMap.put("TranQL Local Resource Adapter for Oracle", "tranql-connector-oracle-local");
  224           rarPathMap.put("TranQL XA Resource Adapter for Oracle", "tranql-connector-oracle-xa");
  225           rarPathMap.put("TranQL Local Resource Adapter for PostgreSQL", "tranql-connector-postgresql-local");
  226           rarPathMap.put("TranQL XA Resource Adapter for PostgreSQL", "tranql-connector-postgresql-xa");
  227           rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2000", "tranql-connector-sqlserver2000-xa");
  228           rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2005", "tranql-connector-sqlserver2005-xa");
  229       }
  230   
  231       public void destroy() {
  232           listView = null;
  233           editView = null;
  234           selectRDBMSView = null;
  235           basicParamsView = null;
  236           confirmURLView = null;
  237           testConnectionView = null;
  238           downloadView = null;
  239           downloadStatusView = null;
  240           planView = null;
  241           importUploadView = null;
  242           importStatusView = null;
  243           usageView = null;
  244           rarPathMap.clear();
  245           super.destroy();
  246       }
  247   
  248       public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) {
  249           PortletSession session = request.getPortletSession(true);
  250           DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY,
  251                   PortletSession.APPLICATION_SCOPE);
  252           if (results == null) {
  253               DriverDownloader downloader = new DriverDownloader();
  254               try {
  255                   results = downloader.loadDriverInfo(new URL(DRIVER_INFO_URL));
  256                   session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE);
  257               } catch (MalformedURLException e) {
  258                   log.error("Unable to download driver data", e);
  259                   results = new DriverDownloader.DriverInfo[0];
  260               }
  261           }
  262           return results;
  263       }
  264   
  265       /**
  266        * Loads data about a resource adapter.  Depending on what we already have, may load
  267        * the name and description, but always loads the config property descriptions.
  268        *
  269        * @param request             Pass it or die
  270        * @param rarPath             If we're creating a new RA, the path to identify it
  271        * @param displayName         If we're editing an existing RA, its name
  272        * @param adapterAbstractName If we're editing an existing RA, its AbstractName
  273        * @return resource adapter parameter data object
  274        */
  275       public ResourceAdapterParams getRARConfiguration(PortletRequest request, String rarPath, String displayName, String adapterAbstractName) {
  276           PortletSession session = request.getPortletSession(true);
  277           if (rarPath != null && !rarPath.equals("")) {
  278               ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(
  279                       CONFIG_SESSION_KEY + "-" + rarPath, PortletSession.APPLICATION_SCOPE);
  280               if (results == null) {
  281                   results = loadConfigPropertiesByPath(request, rarPath);
  282                   session.setAttribute(CONFIG_SESSION_KEY + "-" + rarPath, results, PortletSession.APPLICATION_SCOPE);
  283                   session.setAttribute(CONFIG_SESSION_KEY + "-" + results.displayName, results, PortletSession.APPLICATION_SCOPE);
  284               }
  285               return results;
  286           } else if (displayName != null && !displayName.equals(
  287                   "") && adapterAbstractName != null && !adapterAbstractName.equals("")) {
  288               ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(
  289                       CONFIG_SESSION_KEY + "-" + displayName, PortletSession.APPLICATION_SCOPE);
  290               if (results == null) {
  291                   results = loadConfigPropertiesByAbstractName(request, rarPathMap.get(displayName), adapterAbstractName);
  292                   session.setAttribute(CONFIG_SESSION_KEY + "-" + displayName, results, PortletSession.APPLICATION_SCOPE);
  293               }
  294               return results;
  295           } else {
  296               throw new IllegalArgumentException();
  297           }
  298       }
  299   
  300       public void processAction(ActionRequest actionRequest,
  301                                 ActionResponse actionResponse) throws PortletException, IOException {
  302           String mode = actionRequest.getParameter(MODE_KEY);
  303           if (mode.equals(IMPORT_UPLOAD_MODE)) {
  304               processImportUpload(actionRequest, actionResponse);
  305               actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
  306               return;
  307           }
  308           PoolData data = new PoolData();
  309           data.load(actionRequest);
  310           if (mode.equals("process-" + SELECT_RDBMS_MODE)) {
  311               DatabaseDriver info = getDatabaseInfo(actionRequest, data);
  312               if (info != null) {
  313                   data.rarPath = info.getRAR().toString();
  314                   if (info.isSpecific()) {
  315                       data.adapterDisplayName = "Unknown"; // will pick these up when we process the RA type in the render request
  316                       data.adapterDescription = "Unknown";
  317                       actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
  318                   } else {
  319                       data.driverClass = info.getDriverClassName();
  320                       data.urlPrototype = info.getURLPrototype();
  321                       actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
  322                   }
  323               } else {
  324                   actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE);
  325               }
  326           } else if (mode.equals("process-" + DOWNLOAD_MODE)) {
  327               String name = actionRequest.getParameter("driverName");
  328               DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest);
  329               DriverDownloader.DriverInfo found = null;
  330               for (DriverDownloader.DriverInfo driver : drivers) {
  331                   if (driver.getName().equals(name)) {
  332                       found = driver;
  333                       break;
  334                   }
  335               }
  336               if (found != null) {
  337                   data.jars = new String[]{found.getRepositoryURI()};
  338                   WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0];
  339                   final PortletSession session = actionRequest.getPortletSession();
  340                   ProgressInfo progressInfo = new ProgressInfo();
  341                   progressInfo.setMainMessage("Downloading " + found.getName());
  342                   session.setAttribute(ProgressInfo.PROGRESS_INFO_KEY, progressInfo, PortletSession.APPLICATION_SCOPE);
  343                   // Start the download monitoring
  344                   new Thread(new Downloader(found, progressInfo, repo)).start();
  345                   actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_STATUS_MODE);
  346               } else {
  347                   actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_MODE);
  348               }
  349           } else if (mode.equals("process-" + DOWNLOAD_STATUS_MODE)) {
  350               if (data.getDbtype() == null || data.getDbtype().equals("Other")) {
  351                   actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
  352               } else {
  353                   actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
  354               }
  355           } else if (mode.equals("process-" + BASIC_PARAMS_MODE)) {
  356               DatabaseDriver info;
  357               info = getDatabaseInfo(actionRequest, data);
  358               if (info != null) {
  359                   data.url = populateURL(info.getURLPrototype(), info.getURLParameters(), data.getUrlProperties());
  360               }
  361               if (attemptDriverLoad(actionRequest, data) != null) {
  362                   actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE);
  363               } else {
  364                   actionResponse.setRenderParameter("driverError", "Unable to load driver " + data.driverClass);
  365                   actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
  366               }
  367           } else if (mode.equals("process-" + CONFIRM_URL_MODE)) {
  368               String test = actionRequest.getParameter("test");
  369               if (test == null || test.equals("true")) {                              
  370                   try {
  371                       String targetDBInfo = attemptConnect(actionRequest, data);
  372                       actionResponse.setRenderParameter("targetDBInfo", targetDBInfo);
  373                       actionResponse.setRenderParameter("connected", "true");
  374                   } catch (Exception e) {
  375                       StringWriter writer = new StringWriter();
  376                       PrintWriter temp = new PrintWriter(writer);
  377                       e.printStackTrace(temp);
  378                       temp.flush();
  379                       temp.close();                   
  380                       addErrorMessage(actionRequest, getLocalizedString(actionRequest, "dbwizard.testConnection.connectionError"), writer.getBuffer().toString());
  381                       actionResponse.setRenderParameter("connected", "false");
  382                   }                             
  383                   actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE);
  384               } else {
  385                   save(actionRequest, actionResponse, data, false);
  386               }
  387           } else if (mode.equals(SAVE_MODE)) {
  388               save(actionRequest, actionResponse, data, false);
  389           } else if (mode.equals(SHOW_PLAN_MODE)) {
  390               String plan = save(actionRequest, actionResponse, data, true);
  391               actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan);
  392               actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE);
  393           } else if (mode.equals(EDIT_EXISTING_MODE)) {
  394               final String name = actionRequest.getParameter("adapterAbstractName");
  395               loadConnectionFactory(actionRequest, name, data.getAbstractName(), data);
  396               actionResponse.setRenderParameter("adapterAbstractName", name);
  397               actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
  398           } else if (mode.equals(SELECT_RDBMS_MODE)) {
  399               if (data.getAdapterDisplayName() == null) { // Set a default for a new pool
  400                   data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter";
  401               }
  402               actionResponse.setRenderParameter(MODE_KEY, mode);
  403           } else if (mode.equals(WEBLOGIC_IMPORT_MODE)) {
  404               String domainDir = actionRequest.getParameter("weblogicDomainDir");
  405               String libDir = actionRequest.getParameter("weblogicLibDir");
  406               try {
  407                   DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir);
  408                   actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status));
  409                   actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
  410               } catch (Exception e) {
  411                   log.error("Unable to import", e);
  412                   actionResponse.setRenderParameter("from", actionRequest.getParameter("from"));
  413                   actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE);
  414               }
  415           } else if (mode.equals(IMPORT_START_MODE)) {
  416               actionResponse.setRenderParameter("from", actionRequest.getParameter("from"));
  417               actionResponse.setRenderParameter(MODE_KEY, mode);
  418           } else if (mode.equals(IMPORT_EDIT_MODE)) {
  419               ImportStatus status = getImportStatus(actionRequest);
  420               int index = Integer.parseInt(actionRequest.getParameter("importIndex"));
  421               status.setCurrentPoolIndex(index);
  422               loadImportedData(actionRequest, data, status.getCurrentPool());
  423               actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
  424           } else if (mode.equals(IMPORT_COMPLETE_MODE)) {
  425               ImportStatus status = getImportStatus(actionRequest);
  426               log.warn("Import Results:"); //todo: create a screen for this
  427               log.warn("  " + status.getSkippedCount() + " ignored");
  428               log.warn("  " + status.getStartedCount() + " reviewed but not deployed");
  429               log.warn("  " + status.getPendingCount() + " not reviewed");
  430               log.warn("  " + status.getFinishedCount() + " deployed");
  431               actionRequest.getPortletSession().removeAttribute("ImportStatus");
  432           } else if (mode.equals(DELETE_MODE)) {
  433               String name = actionRequest.getParameter("adapterAbstractName");
  434               loadConnectionFactory(actionRequest, name, data.getAbstractName(), data);
  435               delete(actionRequest, actionResponse, data);
  436           } else {
  437               actionResponse.setRenderParameter(MODE_KEY, mode);
  438           }
  439           data.store(actionResponse);
  440       }
  441   
  442       private static class Downloader implements Runnable {
  443           private WriteableRepository repo;
  444           private DriverDownloader.DriverInfo driver;
  445           private ProgressInfo progressInfo;
  446   
  447           public Downloader(DriverDownloader.DriverInfo driver, ProgressInfo progressInfo, WriteableRepository repo) {
  448               this.driver = driver;
  449               this.progressInfo = progressInfo;
  450               this.repo = repo;
  451           }
  452   
  453           public void run() {
  454               DriverDownloader downloader = new DriverDownloader();
  455               try {
  456                   downloader.loadDriver(repo, driver, new FileWriteMonitor() {
  457                       private int fileSize;
  458   
  459                       public void writeStarted(String fileDescription, int fileSize) {
  460                           this.fileSize = fileSize;
  461                           log.info("Downloading " + fileDescription);
  462                       }
  463   
  464                       public void writeProgress(int bytes) {
  465                           int kbDownloaded = (int) Math.floor(bytes / 1024);
  466                           if (fileSize > 0) {
  467                               int percent = (bytes * 100) / fileSize;
  468                               progressInfo.setProgressPercent(percent);
  469                               progressInfo.setSubMessage(kbDownloaded + " / " + fileSize / 1024 + " Kb downloaded");
  470                           } else {
  471                               progressInfo.setSubMessage(kbDownloaded + " Kb downloaded");
  472                           }
  473                       }
  474   
  475                       public void writeComplete(int bytes) {
  476                           log.info("Finished downloading " + bytes + " b");
  477                       }
  478                   });
  479               } catch (IOException e) {
  480                   log.error("Unable to download database driver", e);
  481               } finally {
  482                   progressInfo.setFinished(true);
  483               }
  484           }
  485       }
  486   
  487       private void loadImportedData(PortletRequest request, PoolData data, ImportStatus.PoolProgress progress) throws PortletException {
  488           if (!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) {
  489               JDBCPool pool = (JDBCPool) progress.getPool();
  490               data.dbtype = "Other";
  491               data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter";
  492               data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis());
  493               data.driverClass = pool.getDriverClass();
  494               data.idleTimeout = pool.getIdleTimeoutMillis() != null ? Integer.toString(
  495                       pool.getIdleTimeoutMillis().intValue() / (60 * 1000)) : null;
  496               data.maxSize = getImportString(pool.getMaxSize());
  497               data.minSize = getImportString(pool.getMinSize());
  498               data.name = pool.getName();
  499               data.password = pool.getPassword();
  500               data.url = pool.getJdbcURL();
  501               data.user = pool.getUsername();
  502               if (pool.getDriverClass() != null) {
  503                   DatabaseDriver info = getDatabaseInfoFromDriver(request, data);
  504                   if (info != null) {
  505                       data.rarPath = info.getRAR().toString();
  506                       data.urlPrototype = info.getURLPrototype();
  507                   } else {
  508                       throw new PortletException("Don't recognize database driver " + data.driverClass + "!");
  509                   }
  510               }
  511           } else {
  512               //todo: handle XA
  513           }
  514       }
  515   
  516       private static String getImportString(Integer value) {
  517           return value == null ? null : value.toString();
  518       }
  519   
  520       private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException {
  521           String type = request.getParameter("importSource");
  522           response.setRenderParameter("importSource", type);
  523           if (!PortletFileUpload.isMultipartContent(request)) {
  524               throw new PortletException("Expected file upload");
  525           }
  526   
  527           PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory());
  528           try {
  529               List<FileItem> items = uploader.parseRequest(request);
  530               for (FileItem item : items) {
  531                   if (!item.isFormField()) {
  532                       File file = File.createTempFile("geronimo-import", "");
  533                       file.deleteOnExit();
  534                       log.debug("Writing database pool import file to " + file.getAbsolutePath());
  535                       item.write(file);
  536                       DatabaseConversionStatus status = processImport(file, type);
  537                       request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status));
  538                       return true;
  539                   } else {
  540                       throw new PortletException("Not expecting any form fields");
  541                   }
  542               }
  543           } catch (PortletException e) {
  544               throw e;
  545           } catch (Exception e) {
  546               throw new PortletException(e);
  547           }
  548           return false;
  549       }
  550   
  551       private DatabaseConversionStatus processImport(File importFile, String type) throws PortletException, IOException {
  552           if (type.equals("JBoss 4")) {
  553               return JBoss4DatabaseConverter.convert(new FileReader(importFile));
  554           } else if (type.equals("WebLogic 8.1")) {
  555               return WebLogic81DatabaseConverter.convert(new FileReader(importFile));
  556           } else {
  557               throw new PortletException("Unknown import type '" + type + "'");
  558           }
  559       }
  560   
  561       private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String rarPath) {
  562           DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager();
  563           try {
  564               URL url = getRAR(request, rarPath).toURL();
  565               ConnectorDeployable deployable = new ConnectorDeployable(url);
  566               final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot();
  567               String adapterName = null, adapterDesc = null;
  568               String[] test = ddBeanRoot.getText("connector/display-name");
  569               if (test != null && test.length > 0) {
  570                   adapterName = test[0];
  571               }
  572               test = ddBeanRoot.getText("connector/description");
  573               if (test != null && test.length > 0) {
  574                   adapterDesc = test[0];
  575               }
  576               DDBean[] definitions = ddBeanRoot.getChildBean(
  577                       "connector/resourceadapter/outbound-resourceadapter/connection-definition");
  578               List<ConfigParam> configs = new ArrayList<ConfigParam>();
  579               if (definitions != null) {
  580                   for (DDBean definition : definitions) {
  581                       String iface = definition.getText("connectionfactory-interface")[0];
  582                       if (iface.equals("javax.sql.DataSource")) {
  583                           DDBean[] beans = definition.getChildBean("config-property");
  584                           for (DDBean bean : beans) {
  585                               String name = bean.getText("config-property-name")[0].trim();
  586                               String type = bean.getText("config-property-type")[0].trim();
  587                               test = bean.getText("config-property-value");
  588                               String value = test == null || test.length == 0 ? null : test[0].trim();
  589                               test = bean.getText("description");
  590                               String desc = test == null || test.length == 0 ? null : test[0].trim();
  591                               configs.add(new ConfigParam(name, type, desc, value));
  592                           }
  593                       }
  594                   }
  595               }
  596               return new ResourceAdapterParams(adapterName, adapterDesc, rarPath.substring(11, rarPath.length()-5), configs.toArray(new ConfigParam[configs.size()]));
  597           } catch (Exception e) {
  598               log.error("Unable to read configuration properties", e);
  599               return null;
  600           } finally {
  601               if (mgr != null) mgr.release();
  602           }
  603       }
  604   
  605       private ResourceAdapterParams loadConfigPropertiesByAbstractName(PortletRequest request, String rarPath, String abstractName) {
  606           ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request,
  607                   new AbstractName(URI.create(abstractName)));
  608           String dd = module.getDeploymentDescriptor();
  609           DocumentBuilderFactory factory = XmlUtil.newDocumentBuilderFactory();
  610           factory.setValidating(false);
  611           factory.setNamespaceAware(true);
  612           try {
  613               DocumentBuilder builder = factory.newDocumentBuilder();
  614               final StringReader reader = new StringReader(dd);
  615               Document doc = builder.parse(new InputSource(reader));
  616               reader.close();
  617               Element elem = doc.getDocumentElement(); // connector
  618               String displayName = getFirstText(elem.getElementsByTagName("display-name"));
  619               String description = getFirstText(elem.getElementsByTagName("description"));
  620               elem = (Element) elem.getElementsByTagName("resourceadapter").item(0);
  621               elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0);
  622               NodeList defs = elem.getElementsByTagName("connection-definition");
  623               List<ConfigParam> all = new ArrayList<ConfigParam>();
  624               for (int i = 0; i < defs.getLength(); i++) {
  625                   final Element def = (Element) defs.item(i);
  626                   String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim();
  627                   if (iface.equals("javax.sql.DataSource")) {
  628                       NodeList configs = def.getElementsByTagName("config-property");
  629                       for (int j = 0; j < configs.getLength(); j++) {
  630                           Element config = (Element) configs.item(j);
  631                           String name = getFirstText(config.getElementsByTagName("config-property-name")).trim();
  632                           String type = getFirstText(config.getElementsByTagName("config-property-type")).trim();
  633                           String test = getFirstText(config.getElementsByTagName("config-property-value"));
  634                           String value = test == null ? null : test.trim();
  635                           test = getFirstText(config.getElementsByTagName("description"));
  636                           String desc = test == null ? null : test.trim();
  637                           all.add(new ConfigParam(name, type, desc, value));
  638                       }
  639                   }
  640               }
  641               return new ResourceAdapterParams(displayName, description, rarPath, all.toArray(new ConfigParam[all.size()]));
  642           } catch (Exception e) {
  643               log.error("Unable to read resource adapter DD", e);
  644               return null;
  645           }
  646       }
  647   
  648       private String getFirstText(NodeList list) {
  649           if (list.getLength() == 0) {
  650               return null;
  651           }
  652           Element first = (Element) list.item(0);
  653           StringBuffer buf = new StringBuffer();
  654           NodeList all = first.getChildNodes();
  655           for (int i = 0; i < all.getLength(); i++) {
  656               Node node = all.item(i);
  657               if (node.getNodeType() == Node.TEXT_NODE) {
  658                   buf.append(node.getNodeValue());
  659               }
  660           }
  661           return buf.toString();
  662       }
  663   
  664       private void loadConnectionFactory(ActionRequest actionRequest, String adapterName, String factoryName, PoolData data) {
  665           AbstractName abstractAdapterName = new AbstractName(URI.create(adapterName));
  666           AbstractName abstractFactoryName = new AbstractName(URI.create(factoryName));
  667   
  668           ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest,
  669                   abstractAdapterName);
  670           JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest,
  671                   abstractFactoryName);
  672           data.adapterDisplayName = adapter.getDisplayName();
  673           data.adapterDescription = adapter.getDescription();
  674           try {
  675               data.name = (String) abstractFactoryName.getName().get("name");
  676               if (data.isGeneric()) {
  677                   data.url = (String) factory.getConfigProperty("ConnectionURL");
  678                   data.driverClass = (String) factory.getConfigProperty("Driver");
  679                   data.user = (String) factory.getConfigProperty("UserName");
  680                   data.password = (String) factory.getConfigProperty("Password");
  681               } else {
  682                   ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(),
  683                           data.getAdapterDisplayName(), adapterName);
  684                   for (int i = 0; i < params.getConfigParams().length; i++) {
  685                       ConfigParam cp = params.getConfigParams()[i];
  686                       Object value = factory.getConfigProperty(cp.getName());
  687                       data.properties.put("property-" + cp.getName(), value == null ? null : value.toString());
  688                   }
  689                   data.sort();
  690               }
  691           } catch (Exception e) {
  692               log.error("Unable to look up connection property", e);
  693           }
  694           //todo: push the lookup into ManagementHelper
  695           PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer();
  696           data.minSize = Integer.toString(pool.getPartitionMinSize());
  697           data.maxSize = Integer.toString(pool.getPartitionMaxSize());
  698           data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds());
  699           data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes());
  700   
  701       }
  702   
  703       protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  704           if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) {
  705               return;
  706           }
  707           try {
  708               String mode = renderRequest.getParameter(MODE_KEY);
  709               PoolData data = new PoolData();
  710               data.load(renderRequest);
  711               renderRequest.setAttribute("pool", data);
  712               // If not headed anywhere in particular, send to list
  713               if (mode == null || mode.equals("")) {
  714                   mode = LIST_MODE;
  715               }
  716               // If headed to list but there's an import in progress, redirect to import status
  717               if (mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) {
  718                   mode = IMPORT_STATUS_MODE;
  719               }
  720   
  721               if (mode.equals(LIST_MODE)) {
  722                   renderList(renderRequest, renderResponse);
  723               } else if (mode.equals(EDIT_MODE)) {
  724                   renderEdit(renderRequest, renderResponse, data);
  725               } else if (mode.equals(SELECT_RDBMS_MODE)) {
  726                   renderSelectRDBMS(renderRequest, renderResponse);
  727               } else if (mode.equals(DOWNLOAD_MODE)) {
  728                   renderDownload(renderRequest, renderResponse);
  729               } else if (mode.equals(DOWNLOAD_STATUS_MODE)) {
  730                   renderDownloadStatus(renderRequest, renderResponse);
  731               } else if (mode.equals(BASIC_PARAMS_MODE)) {
  732                   renderBasicParams(renderRequest, renderResponse, data);
  733               } else if (mode.equals(CONFIRM_URL_MODE)) {
  734                   renderConfirmURL(renderRequest, renderResponse);
  735               } else if (mode.equals(TEST_CONNECTION_MODE)) {
  736                   renderTestConnection(renderRequest, renderResponse);
  737               } else if (mode.equals(SHOW_PLAN_MODE)) {
  738                   renderPlan(renderRequest, renderResponse, data);
  739               } else if (mode.equals(IMPORT_START_MODE)) {
  740                   renderImportUploadForm(renderRequest, renderResponse);
  741               } else if (mode.equals(IMPORT_STATUS_MODE)) {
  742                   renderImportStatus(renderRequest, renderResponse);
  743               } else if (mode.equals(USAGE_MODE)) {
  744                   renderUsage(renderRequest, renderResponse);
  745               }
  746           } catch (Throwable e) {
  747               log.error("Unable to render portlet", e);
  748           }
  749       }
  750   
  751       private void renderUsage(RenderRequest request, RenderResponse response) throws IOException, PortletException {
  752           usageView.include(request, response);
  753       }
  754   
  755       private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException, PortletException {
  756           request.setAttribute("status", getImportStatus(request));
  757           populatePoolList(request);
  758           importStatusView.include(request, response);
  759       }
  760   
  761       private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException, PortletException {
  762           request.setAttribute("from", request.getParameter("from"));
  763           importUploadView.include(request, response);
  764       }
  765   
  766       private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  767           populatePoolList(renderRequest);
  768           listView.include(renderRequest, renderResponse);
  769       }
  770   
  771       private void populatePoolList(PortletRequest renderRequest) {
  772           ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource");
  773           List<ConnectionPool> list = new ArrayList<ConnectionPool>();
  774           for (ResourceAdapterModule module : modules) {
  775               AbstractName moduleName = PortletManager.getManagementHelper(renderRequest).getNameFor(module);
  776   
  777               JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module,
  778                       "javax.sql.DataSource");
  779               for (JCAManagedConnectionFactory db : databases) {
  780                   AbstractName dbName = PortletManager.getManagementHelper(renderRequest).getNameFor(db);
  781                   list.add(new ConnectionPool(moduleName, dbName, (String) dbName.getName().get(NameFactory.J2EE_NAME),
  782                           ((GeronimoManagedBean) db).getState()));
  783               }
  784           }
  785           Collections.sort(list);
  786           renderRequest.setAttribute("pools", list);
  787       }
  788   
  789       private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException {
  790           if (data.abstractName == null || data.abstractName.equals("")) {
  791               DatabaseDriver info = getDatabaseInfo(renderRequest, data);
  792               loadDriverJARList(renderRequest, info);
  793           }
  794           if (!data.isGeneric()) {
  795               ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(),
  796                       data.getAdapterDisplayName(), renderRequest.getParameter("adapterAbstractName"));
  797               data.adapterDisplayName = params.getDisplayName();
  798               data.adapterDescription = params.getDescription();
  799               data.adapterRarPath = params.getRarPath();
  800               Map<String, ConfigParam> map = new HashMap<String, ConfigParam>();
  801               boolean more = false;
  802               for (int i = 0; i < params.getConfigParams().length; i++) {
  803                   ConfigParam param = params.getConfigParams()[i];
  804                   if (!data.properties.containsKey("property-" + param.getName())) {
  805                       data.properties.put("property-" + param.getName(), param.getDefaultValue());
  806                       more = true;
  807                   }
  808                   map.put("property-" + param.getName(), param);
  809               }
  810               if (more) {
  811                   data.loadPropertyNames();
  812               }
  813               data.sort();
  814               renderRequest.setAttribute("ConfigParams", map);
  815           }
  816           editView.include(renderRequest, renderResponse);
  817       }
  818   
  819       private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  820           renderRequest.setAttribute("databases", getAllDrivers(renderRequest));
  821           selectRDBMSView.include(renderRequest, renderResponse);
  822       }
  823   
  824       private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  825           renderRequest.setAttribute("drivers", getDriverInfo(renderRequest));
  826           downloadView.include(renderRequest, renderResponse);
  827       }
  828   
  829       private void renderDownloadStatus(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  830           downloadStatusView.include(renderRequest, renderResponse);
  831       }
  832   
  833       private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException {
  834           DatabaseDriver info = getDatabaseInfo(renderRequest, data);
  835           loadDriverJARList(renderRequest, info);
  836           // Make sure all properties available for the DB are listed
  837           if (info != null) {
  838               for (String param : info.getURLParameters()) {
  839                   final String key = "urlproperty-" + param;
  840                   if (!data.getUrlProperties().containsKey(key)) {
  841                       data.getUrlProperties().put(key,
  842                               param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? info.getDefaultPort() : null);
  843                   }
  844               }
  845           }
  846           // Pass on errors
  847           renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError"));
  848   
  849           basicParamsView.include(renderRequest, renderResponse);
  850       }
  851   
  852       private void loadDriverJARList(RenderRequest renderRequest, DatabaseDriver info) {
  853           // List the available JARs
  854           List<String> list = new ArrayList<String>();
  855           ListableRepository[] repos = PortletManager.getCurrentServer(renderRequest).getRepositories();
  856           Set<Artifact> dependencyFilters = info == null? null : info.getDependencyFilters();
  857           for (ListableRepository repo : repos) {
  858               SortedSet<Artifact> artifacts = repo.list();
  859               for (Artifact artifact : artifacts) {
  860                   if (dependencyFilters != null) {
  861                       for (Artifact filter: dependencyFilters) {
  862                           // It is too strict if using artifact.matches(filter)
  863                           if (filter.getGroupId() != null && artifact.getGroupId().indexOf(filter.getGroupId()) == -1) continue;
  864                           if (filter.getArtifactId() != null && artifact.getArtifactId().indexOf(filter.getArtifactId()) == -1) continue;
  865                           if (filter.getVersion() != null && !artifact.getVersion().equals(filter.getVersion())) continue;
  866                           if (filter.getType() != null && !artifact.getType().equals(filter.getType())) continue;
  867                           list.add(artifact.toString());
  868                       }
  869   
  870                   } else if (INCLUDE_ARTIFACTIDS.contains(artifact.getArtifactId())
  871                           || !EXCLUDE_GROUPIDS.contains(artifact.getGroupId())) {
  872                       list.add(artifact.toString());
  873                   }
  874               }
  875           }
  876           Collections.sort(list);
  877           renderRequest.setAttribute("availableJars", list);
  878       }
  879   
  880       private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  881           confirmURLView.include(renderRequest, renderResponse);
  882       }
  883   
  884       private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
  885           // Pass on results
  886           renderRequest.setAttribute("targetDBInfo", renderRequest.getParameter("targetDBInfo"));
  887           renderRequest.setAttribute("connected", Boolean.valueOf(renderRequest.getParameter("connected")));
  888           testConnectionView.include(renderRequest, renderResponse);
  889       }
  890   
  891       private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException {
  892           // Pass on results
  893           renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan"));
  894           // Digest the RAR URI
  895           String path = PortletManager.getRepositoryEntry(renderRequest, data.getRarPath()).getPath();
  896           String base = PortletManager.getCurrentServer(renderRequest).getServerInfo().getCurrentBaseDirectory();
  897           if (base != null && path.startsWith(base)) {
  898               path = path.substring(base.length());
  899               if (path.startsWith("/")) {
  900                   path = path.substring(1);
  901               }
  902           } else {
  903               int pos = path.lastIndexOf('/');
  904               path = path.substring(pos + 1);
  905           }
  906           renderRequest.setAttribute("rarRelativePath", path);
  907   
  908           planView.include(renderRequest, renderResponse);
  909       }
  910   
  911       private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException {
  912           Class driverClass = attemptDriverLoad(request, data);
  913           Driver driver = (Driver) driverClass.newInstance();
  914           if (driver.acceptsURL(data.url)) {
  915               Properties props = new Properties();
  916               if (data.user != null) {
  917                   props.put("user", data.user);
  918               }
  919               if (data.password != null) {
  920                   props.put("password", data.password);
  921               }
  922               Connection con = null;
  923               try {
  924                   con = driver.connect(data.url, props);
  925                   final DatabaseMetaData metaData = con.getMetaData();
  926                   return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
  927               } finally {
  928                   if (con != null) {
  929                       try {
  930                           con.close();
  931                       } catch (SQLException e) {
  932                           //ignore
  933                       }
  934                   }
  935               }
  936           } else throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url);
  937       }
  938   
  939       private void delete(PortletRequest request, ActionResponse response, PoolData data) {
  940           // check to make sure the abstract name does not begin with 'org.apache.geronimo.configs'
  941           // if it does not - then delete it -- otherwise it is a system database
  942           if (data.getAbstractName() != null) {
  943               boolean isSystemDatabasePool = (data.getAbstractName().indexOf("org.apache.geronimo.configs") == 0);
  944   
  945               if (!isSystemDatabasePool) {
  946                   DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager();
  947                   try {
  948                       // retrieve all running modules
  949                       TargetModuleID[] runningIds = mgr.getRunningModules(ModuleType.RAR, mgr.getTargets());
  950   
  951                       // index of module to keep
  952                       int index = -1;
  953   
  954                       // only keep module id that is associated with selected DB pool
  955                       for (int i = 0; i < runningIds.length; i++) {
  956                           if (data.getAbstractName().contains(runningIds[i].getModuleID())) {
  957                               index = i;
  958                               break;
  959                           }
  960                       }
  961                       TargetModuleID[] ids = {runningIds[index]};
  962   
  963                       // undeploy the db pool
  964                       ProgressObject po = mgr.undeploy(ids);
  965                       waitForProgress(po);
  966   
  967                       if (po.getDeploymentStatus().isCompleted()) {
  968                           log.info("Undeployment completed successfully!");
  969                       }
  970                   } catch (Exception e) {
  971                       log.error("Undeployment unsuccessful!");
  972                   } finally {
  973                       if (mgr != null) mgr.release();
  974                   }
  975               }
  976           }
  977       }
  978   
  979       private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) {
  980           ImportStatus status = getImportStatus(request);
  981           if (data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool
  982               data.name = data.name.replaceAll("\\s", "");
  983               DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager();
  984               try {
  985                   File rarFile = getRAR(request, data.getRarPath());
  986                   ConnectorDeployable deployable = new ConnectorDeployable(rarFile.toURL());
  987                   DeploymentConfiguration config = mgr.createConfiguration(deployable);
  988                   final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot();
  989                   Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot);
  990                   ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean(
  991                           ddBeanRoot.getChildBean(root.getXpaths()[0])[0]);
  992   
  993                   EnvironmentData environment = new EnvironmentData();
  994                   connector.setEnvironment(environment);
  995                   org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact();
  996                   environment.setConfigId(configId);
  997                   configId.setGroupId("console.dbpool");
  998                   configId.setVersion("1.0");
  999                   configId.setType("car");
 1000                   
 1001                   String artifactId = data.name;
 1002                   // simply replace / with _ if / exists within the artifactId
 1003                   // this is needed because we don't allow / within the artifactId
 1004                   artifactId = artifactId.replace('/', '_');
 1005   
 1006                   // Let's check whether the artifact exists
 1007                   ConfigurationManager configurationManager = ConfigurationUtil.getConfigurationManager(PortletManager.getKernel());
 1008                   if (configurationManager.isInstalled(new Artifact(configId.getGroupId(), artifactId,
 1009                           configId.getVersion(), configId.getType()))) {
 1010                       artifactId = artifactId + "_" + new Random(System.currentTimeMillis()).nextInt(99);
 1011                   }
 1012   
 1013                   configId.setArtifactId(artifactId);
 1014   
 1015                   String[] jars = data.getJars();
 1016                   int length = jars[jars.length - 1].length() == 0 ? jars.length - 1 : jars.length;
 1017                   org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length];
 1018                   for (int i = 0; i < dependencies.length; i++) {
 1019                       dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact();
 1020                   }
 1021                   environment.setDependencies(dependencies);
 1022                   for (int i = 0; i < dependencies.length; i++) {
 1023                       Artifact tmp = Artifact.create(jars[i]);
 1024                       dependencies[i].setGroupId(tmp.getGroupId());
 1025                       dependencies[i].setArtifactId(tmp.getArtifactId());
 1026                       dependencies[i].setVersion(tmp.getVersion().toString());
 1027                       dependencies[i].setType(tmp.getType());
 1028                   }
 1029   
 1030                   ResourceAdapter adapter = connector.getResourceAdapter()[0];
 1031                   ConnectionDefinition definition = new ConnectionDefinition();
 1032                   adapter.setConnectionDefinition(new ConnectionDefinition[]{definition});
 1033                   definition.setConnectionFactoryInterface("javax.sql.DataSource");
 1034                   ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance();
 1035                   definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance});
 1036                   instance.setName(data.getName());
 1037                   ConfigPropertySetting[] settings = instance.getConfigPropertySetting();
 1038                   if (data.isGeneric()) { // it's a generic TranQL JDBC pool
 1039                       for (ConfigPropertySetting setting : settings) {
 1040                           if (setting.getName().equals("UserName")) {
 1041                               setting.setValue(data.user);
 1042                           } else if (setting.getName().equals("Password")) {
 1043                               setting.setValue(data.password);
 1044                           } else if (setting.getName().equals("ConnectionURL")) {
 1045                               setting.setValue(data.url);
 1046                           } else if (setting.getName().equals("Driver")) {
 1047                               setting.setValue(data.driverClass);
 1048                           }
 1049                       }
 1050                   } else { // it's an XA driver or non-TranQL RA
 1051                       for (ConfigPropertySetting setting : settings) {
 1052                           String value = data.properties.get("property-" + setting.getName());
 1053                           setting.setValue(value == null ? "" : value);
 1054                       }
 1055                   }
 1056                   ConnectionManager manager = instance.getConnectionManager();
 1057                   if(XA.equals(data.transactionType)){
 1058                       manager.setTransactionXA(true);
 1059                   } else if (NONE.equals(data.transactionType)){
 1060                       manager.setTransactionNone(true);
 1061                   } else {
 1062                       manager.setTransactionLocal(true);
 1063                   }
 1064   
 1065                   SinglePool pool = new SinglePool();
 1066                   manager.setPoolSingle(pool);
 1067                   pool.setMatchOne(true);
 1068                   // Max Size needs to be set before the minimum.  This is because 
 1069                   // the connection manager will constrain the minimum based on the 
 1070                   // current maximum value in the pool.  We might consider adding a  
 1071                   // setPoolConstraints method to allow specifying both at the same time.
 1072                   if (data.maxSize != null && !data.maxSize.equals("")) {
 1073                       pool.setMaxSize(new Integer(data.maxSize));
 1074                   }
 1075                   if (data.minSize != null && !data.minSize.equals("")) {
 1076                       pool.setMinSize(new Integer(data.minSize));
 1077                   }
 1078                   if (data.blockingTimeout != null && !data.blockingTimeout.equals("")) {
 1079                       pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout));
 1080                   }
 1081                   if (data.idleTimeout != null && !data.idleTimeout.equals("")) {
 1082                       pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout));
 1083                   }
 1084   
 1085                   if (planOnly) {
 1086                       ByteArrayOutputStream out = new ByteArrayOutputStream();
 1087                       config.save(out);
 1088                       out.close();
 1089                       return new String(out.toByteArray(), "US-ASCII");
 1090                   } else {
 1091                       File tempFile = File.createTempFile("console-deployment", ".xml");
 1092                       tempFile.deleteOnExit();
 1093                       log.debug("Writing database pool deployment plan to " + tempFile.getAbsolutePath());
 1094                       BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
 1095                       config.save(out);
 1096                       out.flush();
 1097                       out.close();
 1098                       Target[] targets = mgr.getTargets();
 1099                       if (null == targets) {
 1100                           throw new IllegalStateException("No target to distribute to");
 1101                       }
 1102                       targets = new Target[] {targets[0]};
 1103                       
 1104                       ProgressObject po = mgr.distribute(targets, rarFile, tempFile);
 1105                       waitForProgress(po);
 1106                       if (po.getDeploymentStatus().isCompleted()) {
 1107                           TargetModuleID[] ids = po.getResultTargetModuleIDs();
 1108                           po = mgr.start(ids);
 1109                           waitForProgress(po);
 1110                           if (po.getDeploymentStatus().isCompleted()) {
 1111                               ids = po.getResultTargetModuleIDs();
 1112                               if (status != null) {
 1113                                   status.getCurrentPool().setName(data.getName());
 1114                                   status.getCurrentPool().setConfigurationName(ids[0].getModuleID());
 1115                                   status.getCurrentPool().setFinished(true);
 1116                                   response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
 1117                               }
 1118   
 1119                               log.info("Deployment completed successfully!");
 1120                           }
 1121                       } else if (po.getDeploymentStatus().isFailed()) {
 1122                           data.deployError = "Unable to deploy: " + data.name;
 1123                           response.setRenderParameter(MODE_KEY, EDIT_MODE);
 1124                           log.info("Deployment Failed!");
 1125                       }
 1126                   }
 1127               } catch (Exception e) {
 1128                   log.error("Unable to save connection pool", e);
 1129               } finally {
 1130                   if (mgr != null) mgr.release();
 1131               }
 1132           } else { // We're saving updates to an existing pool
 1133               if (planOnly) {
 1134                   throw new UnsupportedOperationException("Can't update a plan for an existing deployment");
 1135               }
 1136               try {
 1137                   JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(
 1138                           request, new AbstractName(URI.create(data.getAbstractName())));
 1139                   if (data.isGeneric()) {
 1140                       factory.setConfigProperty("ConnectionURL", data.getUrl());
 1141                       factory.setConfigProperty("UserName", data.getUser());
 1142                       factory.setConfigProperty("Password", data.getPassword());
 1143                   } else {
 1144                       for (Map.Entry<String, String> entry : data.getProperties().entrySet()) {
 1145                           factory.setConfigProperty(entry.getKey().substring("property-".length()),
 1146                                   entry.getValue());
 1147                       }
 1148                   }
 1149                   //todo: push the lookup into ManagementHelper
 1150                   PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer();
 1151                   pool.setPartitionMinSize(
 1152                           data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize));
 1153                   pool.setPartitionMaxSize(
 1154                           data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize));
 1155                   pool.setBlockingTimeoutMilliseconds(
 1156                           data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt(
 1157                                   data.blockingTimeout));
 1158                   pool.setIdleTimeoutMinutes(
 1159                           data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt(
 1160                                   data.idleTimeout));
 1161               } catch (Exception e) {
 1162                   log.error("Unable to save connection pool", e);
 1163               }
 1164           }
 1165           return null;
 1166       }
 1167   
 1168       private static void waitForProgress(ProgressObject po) {
 1169           while (po.getDeploymentStatus().isRunning()) {
 1170               try {
 1171                   Thread.sleep(100);
 1172               } catch (InterruptedException e) {
 1173                   e.printStackTrace();
 1174               }
 1175           }
 1176       }
 1177   
 1178       private static ImportStatus getImportStatus(PortletRequest request) {
 1179           return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus");
 1180       }
 1181   
 1182       private static File getRAR(PortletRequest request, String rarPath) {
 1183           org.apache.geronimo.kernel.repository.Artifact artifact = org.apache.geronimo.kernel.repository.Artifact.create(
 1184                   rarPath);
 1185           ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();
 1186           for (ListableRepository repo : repos) {
 1187               // if the artifact is not fully resolved then try to resolve it
 1188               if (!artifact.isResolved()) {
 1189                   SortedSet results = repo.list(artifact);
 1190                   if (!results.isEmpty()) {
 1191                       artifact = (Artifact) results.first();
 1192                   } else {
 1193                       continue;
 1194                   }
 1195               }
 1196               File url = repo.getLocation(artifact);
 1197               if (url != null) {
 1198                   if (url.exists() && url.canRead() && !url.isDirectory()) {
 1199                       return url;
 1200                   }
 1201               }
 1202           }
 1203           return null;
 1204       }
 1205   
 1206       /**
 1207        * WARNING: This method relies on having access to the same repository
 1208        * URLs as the server uses.
 1209        *
 1210        * @param request portlet request
 1211        * @param data    info about jars to include
 1212        * @return driver class
 1213        */
 1214       private static Class attemptDriverLoad(PortletRequest request, PoolData data) {
 1215           List<URL> list = new ArrayList<URL>();
 1216           try {
 1217               String[] jars = data.getJars();
 1218               if (jars == null) {
 1219                   log.error("Driver load failed since no jar files were selected.");
 1220                   return null;
 1221               }
 1222               ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();
 1223   
 1224               for (String jar : jars) {
 1225                   Artifact artifact = Artifact.create(
 1226                           jar);
 1227                   for (ListableRepository repo : repos) {
 1228                       File url = repo.getLocation(artifact);
 1229                       if (url != null) {
 1230                           list.add(url.toURL());
 1231                       }
 1232                   }
 1233               }
 1234               URLClassLoader loader = new URLClassLoader(list.toArray(new URL[list.size()]),
 1235                       DatabasePoolPortlet.class.getClassLoader());
 1236               try {
 1237                   return loader.loadClass(data.driverClass);
 1238               } catch (ClassNotFoundException e) {
 1239                   return null;
 1240               }
 1241           } catch (Exception e) {
 1242               e.printStackTrace();
 1243               return null;
 1244           }
 1245       }
 1246   
 1247       private static String populateURL(String url, List<String> keys, Map properties) {
 1248           for (String key : keys) {
 1249               String value = (String) properties.get("urlproperty-" + key);
 1250               if (value == null || value.equals("")) {
 1251                   int begin = url.indexOf("{" + key + "}");
 1252                   int end = begin + key.length() + 2;
 1253                   for (int j = begin - 1; j >= 0; j--) {
 1254                       char c = url.charAt(j);
 1255                       if (c == ';' || c == ':') {
 1256                           begin = j;
 1257                           break;
 1258                       } else if (c == '/') {
 1259                           if (url.length() > end && url.charAt(end) == '/') {
 1260                               begin = j; // Don't leave // if foo is null for /<foo>/
 1261                           }
 1262                           break;
 1263                       }
 1264                   }
 1265                   url = url.substring(0, begin) + url.substring(end);
 1266               } else {
 1267                   if (value.indexOf('\\') != -1 || value.indexOf('$') != -1) {
 1268                       // value contains backslash or dollar sign and needs preprocessing for replaceAll to work properly
 1269                       StringBuffer temp = new StringBuffer();
 1270                       char[] valueChars = value.toCharArray();
 1271                       for (char valueChar : valueChars) {
 1272                           if (valueChar == '\\' || valueChar == '$') {
 1273                               temp.append('\\');
 1274                           }
 1275                           temp.append(valueChar);
 1276                       }
 1277                       value = temp.toString();
 1278                   }
 1279                   url = url.replaceAll("\\{" + key + "\\}", value);
 1280               }
 1281           }
 1282           return url;
 1283       }
 1284   
 1285       private static DatabaseDriver[] getAllDrivers(PortletRequest request) {
 1286           DatabaseDriver[] result = (DatabaseDriver[]) PortletManager.getGBeansImplementing(request,
 1287                   DatabaseDriver.class);
 1288           Arrays.sort(result, new Comparator<DatabaseDriver>() {
 1289               public int compare(DatabaseDriver o1, DatabaseDriver o2) {
 1290                   String name1 = o1.getName();
 1291                   String name2 = o2.getName();
 1292                   if (name1.equals("Other")) name1 = "zzzOther";
 1293                   if (name2.equals("Other")) name2 = "zzzOther";
 1294                   return name1.compareTo(name2);
 1295               }
 1296           });
 1297           return result;
 1298       }
 1299   
 1300       private static DatabaseDriver getDatabaseInfo(PortletRequest request, PoolData data) {
 1301           DatabaseDriver info = null;
 1302           DatabaseDriver[] all = getAllDrivers(request);
 1303           for (DatabaseDriver next : all) {
 1304               if (next.getName().equals(data.getDbtype())) {
 1305                   info = next;
 1306                   break;
 1307               }
 1308           }
 1309           return info;
 1310       }
 1311   
 1312       private static DatabaseDriver getDatabaseInfoFromDriver(PortletRequest request, PoolData data) {
 1313           DatabaseDriver info = null;
 1314           DatabaseDriver[] all = getAllDrivers(request);
 1315           for (DatabaseDriver next : all) {
 1316               if (next.getDriverClassName() != null && next.getDriverClassName().equals(data.getDriverClass())) {
 1317                   info = next;
 1318                   break;
 1319               }
 1320           }
 1321           return info;
 1322       }
 1323   
 1324       public static class PoolData implements Serializable {
 1325           private static final long serialVersionUID = 1L;
 1326           private String name;
 1327           private String dbtype;
 1328           private String user;
 1329           private String password;
 1330           private Map<String, String> properties = new LinkedHashMap<String, String>(); // Configuration for non-Generic drivers
 1331           private Map<String, Object> urlProperties = new HashMap<String, Object>(); // URL substitution for Generic drivers
 1332           private Map<String, String> propertyNames; //todo: store these in the ConfigParam instead
 1333           private String driverClass;
 1334           private String url;
 1335           private String urlPrototype;
 1336           private String[] jars;
 1337           private String minSize;
 1338           private String maxSize;
 1339           private String blockingTimeout;
 1340           private String idleTimeout;
 1341           private String abstractName;
 1342           private String adapterDisplayName;
 1343           private String adapterDescription;
 1344           private String adapterRarPath;
 1345           private String rarPath;
 1346           private String transactionType;
 1347           private String importSource;
 1348           private Map<String, String> abstractNameMap; // generated as needed, don't need to read/write it
 1349           private String deployError;
 1350   
 1351           public void load(PortletRequest request) {
 1352               name = request.getParameter("name");
 1353               if (name != null && name.equals("")) name = null;
 1354               driverClass = request.getParameter("driverClass");
 1355               if (driverClass != null && driverClass.equals("")) driverClass = null;
 1356               dbtype = request.getParameter("dbtype");
 1357               if (dbtype != null && dbtype.equals("")) dbtype = null;
 1358               user = request.getParameter("user");
 1359               if (user != null && user.equals("")) user = null;
 1360               password = request.getParameter("password");
 1361               if (password != null && password.equals("")) password = null;
 1362               url = request.getParameter("url");
 1363               if (url != null && url.equals("")) {
 1364                   url = null;
 1365               } else if (url != null && url.startsWith("URLENCODED")) {
 1366                   try {
 1367                       url = URLDecoder.decode(url.substring(10), "UTF-8");
 1368                   } catch (UnsupportedEncodingException e) {
 1369                       throw new RuntimeException("Unable to decode URL", e);
 1370                   } catch (IllegalArgumentException e) { // not encoded after all??
 1371                       url = url.substring(10);
 1372                   }
 1373               }
 1374               urlPrototype = request.getParameter("urlPrototype");
 1375               if (urlPrototype != null && urlPrototype.equals("")) urlPrototype = null;
 1376               jars = request.getParameterValues("jars");
 1377               minSize = request.getParameter("minSize");
 1378               if (minSize != null && minSize.equals("")) minSize = null;
 1379               maxSize = request.getParameter("maxSize");
 1380               if (maxSize != null && maxSize.equals("")) maxSize = null;
 1381               blockingTimeout = request.getParameter("blockingTimeout");
 1382               if (blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null;
 1383               idleTimeout = request.getParameter("idleTimeout");
 1384               if (idleTimeout != null && idleTimeout.equals("")) idleTimeout = null;
 1385               abstractName = request.getParameter("abstractName");
 1386               if (abstractName != null && abstractName.equals("")) abstractName = null;
 1387               adapterDisplayName = request.getParameter("adapterDisplayName");
 1388               if (adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null;
 1389               adapterDescription = request.getParameter("adapterDescription");
 1390               if (adapterDescription != null && adapterDescription.equals("")) adapterDescription = null;
 1391               rarPath = request.getParameter("rarPath");
 1392               if (rarPath != null && rarPath.equals("")) rarPath = null;
 1393               importSource = request.getParameter("importSource");
 1394               if (importSource != null && importSource.equals("")) importSource = null;
 1395               transactionType = request.getParameter("transactionType");
 1396               if (transactionType != null && "".equals(transactionType)) {
 1397                   if (dbtype != null && dbtype.endsWith("XA")) {
 1398                       transactionType = XA;
 1399                   } else {
 1400                       transactionType = LOCAL;
 1401                   }
 1402               }
 1403               Map map = request.getParameterMap();
 1404               propertyNames = new HashMap<String, String>();
 1405               for (Object o : map.keySet()) {
 1406                   String key = (String) o;
 1407                   if (key.startsWith("urlproperty-")) {
 1408                       urlProperties.put(key, request.getParameter(key));
 1409                   } else if (key.startsWith("property-")) {
 1410                       properties.put(key, request.getParameter(key));
 1411                       propertyNames.put(key, getPropertyName(key));
 1412                   }
 1413               }
 1414               sort();
 1415               deployError = request.getParameter("deployError");
 1416               if (deployError != null && deployError.equals("")) deployError = null;
 1417           }
 1418   
 1419           public void loadPropertyNames() {
 1420               propertyNames = new HashMap<String, String>();
 1421               for (String key : properties.keySet()) {
 1422                   propertyNames.put(key, getPropertyName(key));
 1423               }
 1424           }
 1425   
 1426           private static String getPropertyName(String key) {
 1427               int pos = key.indexOf('-');
 1428               key = Character.toUpperCase(key.charAt(pos + 1)) + key.substring(pos + 2);
 1429               StringBuffer buf = new StringBuffer();
 1430               pos = 0;
 1431               for (int i = 1; i < key.length(); i++) {
 1432                   if (Character.isUpperCase(key.charAt(i))) {
 1433                       if (Character.isUpperCase(key.charAt(i - 1))) { // ongoing capitalized word
 1434   
 1435                       } else { // start of a new word
 1436                           buf.append(key.substring(pos, i)).append(" ");
 1437                           pos = i;
 1438                       }
 1439                   } else {
 1440                       if (Character.isUpperCase(
 1441                               key.charAt(i - 1)) && i - pos > 1) { // first lower-case after a series of caps
 1442                           buf.append(key.substring(pos, i - 1)).append(" ");
 1443                           pos = i - 1;
 1444                       }
 1445                   }
 1446               }
 1447               buf.append(key.substring(pos));
 1448               return buf.toString();
 1449           }
 1450   
 1451           public void store(ActionResponse response) {
 1452               if (name != null) response.setRenderParameter("name", name);
 1453               if (dbtype != null) response.setRenderParameter("dbtype", dbtype);
 1454               if (driverClass != null) response.setRenderParameter("driverClass", driverClass);
 1455               if (user != null) response.setRenderParameter("user", user);
 1456               if (password != null) response.setRenderParameter("password", password);
 1457               if (url != null) { // attempt to work around Pluto/Tomcat error with ; in a stored value
 1458                   try {
 1459                       response.setRenderParameter("url", "URLENCODED" + URLEncoder.encode(url, "UTF-8"));
 1460                   } catch (UnsupportedEncodingException e) {
 1461                       throw new RuntimeException("Unable to encode URL", e);
 1462                   }
 1463               }
 1464               if (urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype);
 1465               if (jars != null) response.setRenderParameter("jars", jars);
 1466               if (minSize != null) response.setRenderParameter("minSize", minSize);
 1467               if (maxSize != null) response.setRenderParameter("maxSize", maxSize);
 1468               if (blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout);
 1469               if (idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout);
 1470               if (abstractName != null) response.setRenderParameter("abstractName", abstractName);
 1471               if (adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName);
 1472               if (adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription);
 1473               if (importSource != null) response.setRenderParameter("importSource", importSource);
 1474               if (rarPath != null) response.setRenderParameter("rarPath", rarPath);
 1475               if (transactionType != null) response.setRenderParameter("transactionType", transactionType);
 1476               for (Map.Entry<String, Object> entry : urlProperties.entrySet()) {
 1477                   if (entry.getValue() != null) {
 1478                       response.setRenderParameter(entry.getKey(), entry.getValue().toString());
 1479                   }
 1480               }
 1481               for (Map.Entry<String, String> entry : properties.entrySet()) {
 1482                   if (entry.getValue() != null) {
 1483                       response.setRenderParameter(entry.getKey(), entry.getValue());
 1484                   }
 1485               }
 1486               if (deployError != null) response.setRenderParameter("deployError", deployError);
 1487           }
 1488   
 1489   
 1490           public void sort() {
 1491               Map<String, String> sortedProperties = new LinkedHashMap<String, String>();
 1492   
 1493               for (String propertyName : ORDERED_PROPERTY_NAMES) {
 1494                   if (properties.containsKey(propertyName)) {
 1495                       sortedProperties.put(propertyName, properties.get(propertyName));
 1496                       properties.remove(propertyName);
 1497                   }
 1498               }
 1499   
 1500               sortedProperties.putAll(properties);
 1501   
 1502               properties = sortedProperties;
 1503           }
 1504   
 1505           public String getName() {
 1506               return name;
 1507           }
 1508   
 1509           public String getDbtype() {
 1510               return dbtype;
 1511           }
 1512   
 1513           public String getUser() {
 1514               return user;
 1515           }
 1516   
 1517           public String getPassword() {
 1518               return password;
 1519           }
 1520   
 1521           public Map<String, String> getProperties() {
 1522               return properties;
 1523           }
 1524   
 1525           public Map<String, String> getPropertyNames() {
 1526               return propertyNames;
 1527           }
 1528   
 1529           public Map<String, Object> getUrlProperties() {
 1530               return urlProperties;
 1531           }
 1532   
 1533           public String getUrl() {
 1534               return url;
 1535           }
 1536   
 1537           public String[] getJars() {
 1538               return jars;
 1539           }
 1540   
 1541           public String getMinSize() {
 1542               return minSize;
 1543           }
 1544   
 1545           public String getMaxSize() {
 1546               return maxSize;
 1547           }
 1548   
 1549           public String getBlockingTimeout() {
 1550               return blockingTimeout;
 1551           }
 1552   
 1553           public String getIdleTimeout() {
 1554               return idleTimeout;
 1555           }
 1556   
 1557           public String getDriverClass() {
 1558               return driverClass;
 1559           }
 1560   
 1561           public String getUrlPrototype() {
 1562               return urlPrototype;
 1563           }
 1564   
 1565           public String getAbstractName() {
 1566               return abstractName;
 1567           }
 1568   
 1569           public String getAdapterDisplayName() {
 1570               return adapterDisplayName;
 1571           }
 1572   
 1573           public String getAdapterDescription() {
 1574               return adapterDescription;
 1575           }
 1576   
 1577           public String getAdapterRarPath() {
 1578               return adapterRarPath;
 1579           }
 1580   
 1581           public String getRarPath() {
 1582               return rarPath;
 1583           }
 1584   
 1585           public boolean isGeneric() {
 1586               //todo: is there any better way to tell?
 1587               return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter");
 1588           }
 1589   
 1590           public String getImportSource() {
 1591               return importSource;
 1592           }
 1593   
 1594           public Map<String, String> getAbstractNameMap() {
 1595               if (abstractName == null) return Collections.emptyMap();
 1596               if (abstractNameMap != null) return abstractNameMap;
 1597               AbstractName name = new AbstractName(URI.create(abstractName));
 1598               abstractNameMap = new HashMap<String, String>(name.getName());
 1599               abstractNameMap.put("domain", name.getObjectName().getDomain());
 1600               abstractNameMap.put("groupId", name.getArtifact().getGroupId());
 1601               abstractNameMap.put("artifactId", name.getArtifact().getArtifactId());
 1602               abstractNameMap.put("type", name.getArtifact().getType());
 1603               abstractNameMap.put("version", name.getArtifact().getVersion().toString());
 1604               return abstractNameMap;
 1605           }
 1606   
 1607           public String getDeployError() {
 1608               return deployError;
 1609           }
 1610           
 1611           public String getTransactionType() {
 1612               return transactionType;
 1613           }
 1614   
 1615           public void setTransactionType(String transactionType) {
 1616               this.transactionType = transactionType;
 1617           }
 1618           
 1619       }
 1620   
 1621       public static class ConnectionPool implements Serializable, Comparable {
 1622           private static final long serialVersionUID = 1L;
 1623           private final String adapterAbstractName;
 1624           private final String factoryAbstractName;
 1625           private final String name;
 1626           private final String parentName;
 1627           private final int state;
 1628   
 1629           public ConnectionPool(AbstractName adapterAbstractName, AbstractName factoryAbstractName, String name, int state) {
 1630               this.adapterAbstractName = adapterAbstractName.toURI().toString();
 1631               String parent = (String) adapterAbstractName.getName().get(NameFactory.J2EE_APPLICATION);
 1632               if (parent != null && parent.equals("null")) {
 1633                   parent = null;
 1634               }
 1635               parentName = parent;
 1636               this.factoryAbstractName = factoryAbstractName.toURI().toString();
 1637               this.name = name;
 1638               this.state = state;
 1639           }
 1640   
 1641           public String getAdapterAbstractName() {
 1642               return adapterAbstractName;
 1643           }
 1644   
 1645           public String getFactoryAbstractName() {
 1646               return factoryAbstractName;
 1647           }
 1648   
 1649           public String getName() {
 1650               return name;
 1651           }
 1652   
 1653           public String getParentName() {
 1654               return parentName;
 1655           }
 1656   
 1657           public int getState() {
 1658               return state;
 1659           }
 1660   
 1661           public String getStateName() {
 1662               return State.toString(state);
 1663           }
 1664   
 1665           public int compareTo(Object o) {
 1666               final ConnectionPool pool = (ConnectionPool) o;
 1667               int names = name.compareTo(pool.name);
 1668               if (parentName == null) {
 1669                   if (pool.parentName == null) {
 1670                       return names;
 1671                   } else {
 1672                       return -1;
 1673                   }
 1674               } else {
 1675                   if (pool.parentName == null) {
 1676                       return 1;
 1677                   } else {
 1678                       int test = parentName.compareTo(pool.parentName);
 1679                       if (test != 0) {
 1680                           return test;
 1681                       } else {
 1682                           return names;
 1683                       }
 1684                   }
 1685               }
 1686           }
 1687       }
 1688   
 1689       public static class ResourceAdapterParams {
 1690           private String displayName;
 1691           private String description;
 1692           private String rarPath;
 1693           private ConfigParam[] configParams;
 1694   
 1695           public ResourceAdapterParams(String displayName, String description, String rarPath, ConfigParam[] configParams) {
 1696               this.displayName = displayName;
 1697               this.description = description;
 1698               this.rarPath = rarPath;
 1699               this.configParams = configParams;
 1700           }
 1701   
 1702           public String getDisplayName() {
 1703               return displayName;
 1704           }
 1705   
 1706           public String getDescription() {
 1707               return description;
 1708           }
 1709           
 1710           public String getRarPath() {
 1711               return rarPath;
 1712           }
 1713   
 1714           public ConfigParam[] getConfigParams() {
 1715               return configParams;
 1716           }
 1717       }
 1718   
 1719       public static class ConfigParam {
 1720           private String name;
 1721           private String type;
 1722           private String description;
 1723           private String defaultValue;
 1724   
 1725           public ConfigParam(String name, String type, String description, String defaultValue) {
 1726               this.name = name;
 1727               this.type = type;
 1728               this.description = description;
 1729               this.defaultValue = defaultValue;
 1730           }
 1731   
 1732           public String getName() {
 1733               return name;
 1734           }
 1735   
 1736           public String getType() {
 1737               return type;
 1738           }
 1739   
 1740           public String getDescription() {
 1741               return description;
 1742           }
 1743   
 1744           public String getDefaultValue() {
 1745               return defaultValue;
 1746           }
 1747       }
 1748   }

Home » geronimo-2.2-source-release » org.apache.geronimo.console.databasemanager.wizard » [javadoc | source]