KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > console > databasemanager > wizard > DatabasePoolPortlet


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 JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.File JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.io.FileReader JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.PrintWriter JavaDoc;
26 import java.io.Serializable JavaDoc;
27 import java.io.StringReader JavaDoc;
28 import java.io.StringWriter JavaDoc;
29 import java.io.UnsupportedEncodingException JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.net.URI JavaDoc;
32 import java.net.URL JavaDoc;
33 import java.net.URLClassLoader JavaDoc;
34 import java.net.URLDecoder JavaDoc;
35 import java.net.URLEncoder JavaDoc;
36 import java.sql.Connection JavaDoc;
37 import java.sql.DatabaseMetaData JavaDoc;
38 import java.sql.Driver JavaDoc;
39 import java.sql.SQLException JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Arrays JavaDoc;
42 import java.util.Collections JavaDoc;
43 import java.util.Comparator JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.Iterator JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Properties JavaDoc;
49 import java.util.SortedSet JavaDoc;
50 import javax.enterprise.deploy.model.DDBean JavaDoc;
51 import javax.enterprise.deploy.model.DDBeanRoot JavaDoc;
52 import javax.enterprise.deploy.shared.StateType JavaDoc;
53 import javax.enterprise.deploy.spi.DeploymentConfiguration JavaDoc;
54 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
55 import javax.enterprise.deploy.spi.Target JavaDoc;
56 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
57 import javax.enterprise.deploy.spi.status.ProgressEvent JavaDoc;
58 import javax.enterprise.deploy.spi.status.ProgressListener JavaDoc;
59 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
60 import javax.portlet.ActionRequest;
61 import javax.portlet.ActionResponse;
62 import javax.portlet.PortletConfig;
63 import javax.portlet.PortletException;
64 import javax.portlet.PortletRequest;
65 import javax.portlet.PortletRequestDispatcher;
66 import javax.portlet.PortletSession;
67 import javax.portlet.RenderRequest;
68 import javax.portlet.RenderResponse;
69 import javax.portlet.WindowState;
70 import javax.xml.parsers.DocumentBuilder JavaDoc;
71 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
72 import org.apache.commons.fileupload.FileItem;
73 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
74 import org.apache.commons.fileupload.portlet.PortletFileUpload;
75 import org.apache.commons.logging.Log;
76 import org.apache.commons.logging.LogFactory;
77 import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting;
78 import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition;
79 import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance;
80 import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager;
81 import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot;
82 import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB;
83 import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter;
84 import org.apache.geronimo.connector.deployment.jsr88.SinglePool;
85 import org.apache.geronimo.connector.outbound.PoolingAttributes;
86 import org.apache.geronimo.console.BasePortlet;
87 import org.apache.geronimo.console.ajax.ProgressInfo;
88 import org.apache.geronimo.console.util.PortletManager;
89 import org.apache.geronimo.converter.DatabaseConversionStatus;
90 import org.apache.geronimo.converter.JDBCPool;
91 import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter;
92 import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter;
93 import org.apache.geronimo.deployment.service.jsr88.EnvironmentData;
94 import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable;
95 import org.apache.geronimo.gbean.AbstractName;
96 import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
97 import org.apache.geronimo.kernel.management.State;
98 import org.apache.geronimo.kernel.proxy.GeronimoManagedBean;
99 import org.apache.geronimo.kernel.repository.Artifact;
100 import org.apache.geronimo.kernel.repository.FileWriteMonitor;
101 import org.apache.geronimo.kernel.repository.ListableRepository;
102 import org.apache.geronimo.kernel.repository.WriteableRepository;
103 import org.apache.geronimo.kernel.util.XmlUtil;
104 import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory;
105 import org.apache.geronimo.management.geronimo.ResourceAdapterModule;
106 import org.w3c.dom.Document JavaDoc;
107 import org.w3c.dom.Element JavaDoc;
108 import org.w3c.dom.Node JavaDoc;
109 import org.w3c.dom.NodeList JavaDoc;
110 import org.xml.sax.InputSource JavaDoc;
111
112 /**
113  * A portlet that lets you configure and deploy JDBC connection pools.
114  *
115  * @version $Rev: 484721 $ $Date: 2006-12-08 15:01:16 -0500 (Fri, 08 Dec 2006) $
116  */

117 public class DatabasePoolPortlet extends BasePortlet {
118     private final static Log log = LogFactory.getLog(DatabasePoolPortlet.class);
119     private final static String JavaDoc[] SKIP_ENTRIES_WITH = new String JavaDoc[]{"geronimo", "tomcat", "tranql", "commons", "directory", "activemq"};
120     private final static String JavaDoc DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers";
121     private final static String JavaDoc CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam";
122     private final static String JavaDoc DRIVER_INFO_URL = "http://geronimo.apache.org/driver-downloads.properties";
123     private static final String JavaDoc LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp";
124     private static final String JavaDoc EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp";
125     private static final String JavaDoc SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp";
126     private static final String JavaDoc BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp";
127     private static final String JavaDoc CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp";
128     private static final String JavaDoc TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp";
129     private static final String JavaDoc DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp";
130     private static final String JavaDoc DOWNLOAD_STATUS_VIEW = "/WEB-INF/view/dbwizard/downloadStatus.jsp";
131     private static final String JavaDoc SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp";
132     private static final String JavaDoc IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp";
133     private static final String JavaDoc IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp";
134     private static final String JavaDoc USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp";
135     private static final String JavaDoc LIST_MODE = "list";
136     private static final String JavaDoc EDIT_MODE = "edit";
137     private static final String JavaDoc SELECT_RDBMS_MODE = "rdbms";
138     private static final String JavaDoc BASIC_PARAMS_MODE = "params";
139     private static final String JavaDoc CONFIRM_URL_MODE = "url";
140     private static final String JavaDoc TEST_CONNECTION_MODE = "test";
141     private static final String JavaDoc SHOW_PLAN_MODE = "plan";
142     private static final String JavaDoc DOWNLOAD_MODE = "download";
143     private static final String JavaDoc DOWNLOAD_STATUS_MODE = "downloadStatus";
144     private static final String JavaDoc EDIT_EXISTING_MODE = "editExisting";
145     private static final String JavaDoc SAVE_MODE = "save";
146     private static final String JavaDoc IMPORT_START_MODE = "startImport";
147     private static final String JavaDoc IMPORT_UPLOAD_MODE = "importUpload";
148     private static final String JavaDoc IMPORT_STATUS_MODE = "importStatus";
149     private static final String JavaDoc IMPORT_COMPLETE_MODE = "importComplete";
150     private static final String JavaDoc WEBLOGIC_IMPORT_MODE = "weblogicImport";
151     private static final String JavaDoc USAGE_MODE = "usage";
152     private static final String JavaDoc IMPORT_EDIT_MODE = "importEdit";
153     private static final String JavaDoc MODE_KEY = "mode";
154
155     private PortletRequestDispatcher listView;
156     private PortletRequestDispatcher editView;
157     private PortletRequestDispatcher selectRDBMSView;
158     private PortletRequestDispatcher basicParamsView;
159     private PortletRequestDispatcher confirmURLView;
160     private PortletRequestDispatcher testConnectionView;
161     private PortletRequestDispatcher downloadView;
162     private PortletRequestDispatcher downloadStatusView;
163     private PortletRequestDispatcher planView;
164     private PortletRequestDispatcher importUploadView;
165     private PortletRequestDispatcher importStatusView;
166     private PortletRequestDispatcher usageView;
167
168     public void init(PortletConfig portletConfig) throws PortletException {
169         super.init(portletConfig);
170         listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW);
171         editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW);
172         selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW);
173         basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW);
174         confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW);
175         testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW);
176         downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW);
177         downloadStatusView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_STATUS_VIEW);
178         planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW);
179         importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW);
180         importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW);
181         usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW);
182     }
183
184     public void destroy() {
185         listView = null;
186         editView = null;
187         selectRDBMSView = null;
188         basicParamsView = null;
189         confirmURLView = null;
190         testConnectionView = null;
191         downloadView = null;
192         downloadStatusView = null;
193         planView = null;
194         importUploadView = null;
195         importStatusView = null;
196         usageView = null;
197         super.destroy();
198     }
199
200     public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) {
201         PortletSession session = request.getPortletSession(true);
202         DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY, PortletSession.APPLICATION_SCOPE);
203         if(results == null) {
204             DriverDownloader downloader = new DriverDownloader();
205             try {
206                 results = downloader.loadDriverInfo(new URL JavaDoc(DRIVER_INFO_URL));
207                 session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE);
208             } catch (MalformedURLException JavaDoc e) {
209                 log.error("Unable to download driver data", e);
210                 results = new DriverDownloader.DriverInfo[0];
211             }
212         }
213         return results;
214     }
215
216     /**
217      * Loads data about a resource adapter. Depending on what we already have, may load
218      * the name and description, but always loads the config property descriptions.
219      * @param request Pass it or die
220      * @param rarPath If we're creating a new RA, the path to identify it
221      * @param displayName If we're editing an existing RA, its name
222      * @param adapterAbstractName If we're editing an existing RA, its AbstractName
223      */

224     public ResourceAdapterParams getRARConfiguration(PortletRequest request, String JavaDoc rarPath, String JavaDoc displayName, String JavaDoc adapterAbstractName) {
225         PortletSession session = request.getPortletSession(true);
226         if(rarPath != null && !rarPath.equals("")) {
227             ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+rarPath, PortletSession.APPLICATION_SCOPE);
228             if(results == null) {
229                 results = loadConfigPropertiesByPath(request, rarPath);
230                 session.setAttribute(CONFIG_SESSION_KEY+"-"+rarPath, results, PortletSession.APPLICATION_SCOPE);
231                 session.setAttribute(CONFIG_SESSION_KEY+"-"+results.displayName, results, PortletSession.APPLICATION_SCOPE);
232             }
233             return results;
234         } else if(displayName != null && !displayName.equals("") && adapterAbstractName != null && !adapterAbstractName.equals("")) {
235             ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+displayName, PortletSession.APPLICATION_SCOPE);
236             if(results == null) {
237                 results = loadConfigPropertiesByAbstractName(request, adapterAbstractName);
238                 session.setAttribute(CONFIG_SESSION_KEY+"-"+displayName, results, PortletSession.APPLICATION_SCOPE);
239             }
240             return results;
241         } else {
242             throw new IllegalArgumentException JavaDoc();
243         }
244     }
245
246     public void processAction(ActionRequest actionRequest,
247             ActionResponse actionResponse) throws PortletException, IOException JavaDoc {
248         String JavaDoc mode = actionRequest.getParameter(MODE_KEY);
249         if(mode.equals(IMPORT_UPLOAD_MODE)) {
250             processImportUpload(actionRequest, actionResponse);
251             actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
252             return;
253         }
254         PoolData data = new PoolData();
255         data.load(actionRequest);
256         if(mode.equals("process-"+SELECT_RDBMS_MODE)) {
257             DatabaseDriver info = null;
258             info = getDatabaseInfo(actionRequest, data);
259             if(info != null) {
260                 data.rarPath = info.getRAR().toString();
261                 if(info.isXA()) {
262                     data.adapterDisplayName="Unknown"; // will pick these up when we process the RA type in the render request
263
data.adapterDescription="Unknown";
264                     actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
265                 } else {
266                     if(data.getDbtype().equals("Other")) {
267                         actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
268                     } else {
269                         data.driverClass = info.getDriverClassName();
270                         data.urlPrototype = info.getURLPrototype();
271                         actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
272                     }
273                 }
274             } else {
275                 actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE);
276             }
277         } else if(mode.equals("process-"+DOWNLOAD_MODE)) {
278             String JavaDoc name = actionRequest.getParameter("driverName");
279             DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest);
280             DriverDownloader.DriverInfo found = null;
281             for (int i = 0; i < drivers.length; i++) {
282                 DriverDownloader.DriverInfo driver = drivers[i];
283                 if(driver.getName().equals(name)) {
284                     found = driver;
285                     break;
286                 }
287             }
288             if(found != null) {
289                 data.jars = new String JavaDoc[] {found.getRepositoryURI()};
290                 WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0];
291                 final PortletSession session = actionRequest.getPortletSession();
292                 ProgressInfo progressInfo = new ProgressInfo();
293                 progressInfo.setMainMessage("Downloading " + found.getName());
294                 session.setAttribute(ProgressInfo.PROGRESS_INFO_KEY, progressInfo, PortletSession.APPLICATION_SCOPE);
295                 // Start the download monitoring
296
new Thread JavaDoc(new Downloader(found, progressInfo, repo)).start();
297                 actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_STATUS_MODE);
298             } else {
299                 actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_MODE);
300             }
301         } else if(mode.equals("process-"+DOWNLOAD_STATUS_MODE)) {
302             if(data.getDbtype() == null || data.getDbtype().equals("Other")) {
303                 actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
304             } else {
305                 actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
306             }
307         } else if(mode.equals("process-"+BASIC_PARAMS_MODE)) {
308             DatabaseDriver info = null;
309             info = getDatabaseInfo(actionRequest, data);
310             if(info != null) {
311                 data.url = populateURL(info.getURLPrototype(), info.getURLParameters(), data.getUrlProperties());
312             }
313             if(attemptDriverLoad(actionRequest, data) != null) {
314                 actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE);
315             } else {
316                 actionResponse.setRenderParameter("driverError", "Unable to load driver "+data.driverClass);
317                 actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE);
318             }
319         } else if(mode.equals("process-"+CONFIRM_URL_MODE)) {
320             String JavaDoc test = actionRequest.getParameter("test");
321             if(test == null || test.equals("true")) {
322                 String JavaDoc result = null;
323                 String JavaDoc stack = null;
324                 try {
325                     result = attemptConnect(actionRequest, data);
326                 } catch (Exception JavaDoc e) {
327                     StringWriter JavaDoc writer = new StringWriter JavaDoc();
328                     PrintWriter JavaDoc temp = new PrintWriter JavaDoc(writer);
329                     e.printStackTrace(temp);
330                     temp.flush();
331                     temp.close();
332                     stack = writer.getBuffer().toString();
333                 }
334                 if(result != null) actionResponse.setRenderParameter("connectResult", result);
335                 actionRequest.getPortletSession(true).setAttribute("connectError", stack);
336                 actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE);
337             } else {
338                 save(actionRequest, actionResponse, data, false);
339             }
340         } else if(mode.equals(SAVE_MODE)) {
341             save(actionRequest, actionResponse, data, false);
342         } else if(mode.equals(SHOW_PLAN_MODE)) {
343             String JavaDoc plan = save(actionRequest, actionResponse, data, true);
344             actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan);
345             actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE);
346         } else if(mode.equals(EDIT_EXISTING_MODE)) {
347             final String JavaDoc name = actionRequest.getParameter("adapterAbstractName");
348             loadConnectionFactory(actionRequest, name, data.getAbstractName(), data);
349             actionResponse.setRenderParameter("adapterAbstractName", name);
350             actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
351         } else if(mode.equals(SELECT_RDBMS_MODE)) {
352             if(data.getAdapterDisplayName() == null) { // Set a default for a new pool
353
data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter";
354             }
355             actionResponse.setRenderParameter(MODE_KEY, mode);
356         } else if(mode.equals(WEBLOGIC_IMPORT_MODE)) {
357             String JavaDoc domainDir = actionRequest.getParameter("weblogicDomainDir");
358             String JavaDoc libDir = actionRequest.getParameter("weblogicLibDir");
359             try {
360                 DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir);
361                 actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status));
362                 actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
363             } catch (Exception JavaDoc e) {
364                 log.error("Unable to import", e);
365                 actionResponse.setRenderParameter("from", actionRequest.getParameter("from"));
366                 actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE);
367             }
368         } else if(mode.equals(IMPORT_START_MODE)) {
369             actionResponse.setRenderParameter("from", actionRequest.getParameter("from"));
370             actionResponse.setRenderParameter(MODE_KEY, mode);
371         } else if(mode.equals(IMPORT_EDIT_MODE)) {
372             ImportStatus status = getImportStatus(actionRequest);
373             int index = Integer.parseInt(actionRequest.getParameter("importIndex"));
374             status.setCurrentPoolIndex(index);
375             loadImportedData(actionRequest, data, status.getCurrentPool());
376             actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE);
377         } else if(mode.equals(IMPORT_COMPLETE_MODE)) {
378             ImportStatus status = getImportStatus(actionRequest);
379             log.warn("Import Results:"); //todo: create a screen for this
380
log.warn(" "+status.getSkippedCount()+" ignored");
381             log.warn(" "+status.getStartedCount()+" reviewed but not deployed");
382             log.warn(" "+status.getPendingCount()+" not reviewed");
383             log.warn(" "+status.getFinishedCount()+" deployed");
384             actionRequest.getPortletSession().removeAttribute("ImportStatus");
385         } else {
386             actionResponse.setRenderParameter(MODE_KEY, mode);
387         }
388         data.store(actionResponse);
389     }
390
391     private static class Downloader implements Runnable JavaDoc {
392         private WriteableRepository repo;
393         private DriverDownloader.DriverInfo driver;
394         private ProgressInfo progressInfo;
395
396         public Downloader(DriverDownloader.DriverInfo driver, ProgressInfo progressInfo, WriteableRepository repo) {
397             this.driver = driver;
398             this.progressInfo = progressInfo;
399             this.repo = repo;
400         }
401
402         public void run() {
403             DriverDownloader downloader = new DriverDownloader();
404             try {
405                 downloader.loadDriver(repo, driver, new FileWriteMonitor() {
406                     private int fileSize;
407
408                     public void writeStarted(String JavaDoc fileDescription, int fileSize) {
409                         this.fileSize = fileSize;
410                         log.info("Downloading "+fileDescription);
411                     }
412
413                     public void writeProgress(int bytes) {
414                         int kbDownloaded = (int)Math.floor(bytes/1024);
415                         if (fileSize > 0) {
416                             int percent = (bytes*100)/fileSize;
417                             progressInfo.setProgressPercent(percent);
418                             progressInfo.setSubMessage(kbDownloaded + " / " + fileSize/1024 + " Kb downloaded");
419                         } else {
420                             progressInfo.setSubMessage(kbDownloaded + " Kb downloaded");
421                         }
422                     }
423
424                     public void writeComplete(int bytes) {
425                         log.info("Finished downloading "+bytes+" b");
426                     }
427                 });
428             } catch (IOException JavaDoc e) {
429                 log.error("Unable to download database driver", e);
430             } finally {
431                 progressInfo.setFinished(true);
432             }
433         }
434     }
435
436     private void loadImportedData(PortletRequest request, PoolData data, ImportStatus.PoolProgress progress) throws PortletException { if(!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) {
437             JDBCPool pool = (JDBCPool) progress.getPool();
438             data.dbtype = "Other";
439             data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter";
440             data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis());
441             data.driverClass = pool.getDriverClass();
442             data.idleTimeout = pool.getIdleTimeoutMillis() == null ? null : Integer.toString(pool.getIdleTimeoutMillis().intValue() / (60 * 1000));
443             data.maxSize = getImportString(pool.getMaxSize());
444             data.minSize = getImportString(pool.getMinSize());
445             data.name = pool.getName();
446             data.password = pool.getPassword();
447             data.url = pool.getJdbcURL();
448             data.user = pool.getUsername();
449             if(pool.getDriverClass() != null) {
450                 DatabaseDriver info = getDatabaseInfoFromDriver(request, data);
451                 if(info != null) {
452                     data.rarPath = info.getRAR().toString();
453                     data.urlPrototype = info.getURLPrototype();
454                 } else {
455                     throw new PortletException("Don't recognize database driver "+data.driverClass+"!");
456                 }
457             }
458         } else {
459             //todo: handle XA
460
}
461     }
462
463     private static String JavaDoc getImportString(Integer JavaDoc value) {
464         return value == null ? null : value.toString();
465     }
466
467     private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException {
468         String JavaDoc type = request.getParameter("importSource");
469         response.setRenderParameter("importSource", type);
470         if (!PortletFileUpload.isMultipartContent(request)) {
471             throw new PortletException("Expected file upload");
472         }
473
474         PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory());
475         try {
476             List JavaDoc items = uploader.parseRequest(request);
477             for (Iterator JavaDoc i = items.iterator(); i.hasNext();) {
478                 FileItem item = (FileItem) i.next();
479                 if (!item.isFormField()) {
480                     File JavaDoc file = File.createTempFile("geronimo-import", "");
481                     file.deleteOnExit();
482                     log.debug("Writing database pool import file to "+file.getAbsolutePath());
483                     item.write(file);
484                     DatabaseConversionStatus status = processImport(file, type);
485                     request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status));
486                     return true;
487                 } else {
488                     throw new PortletException("Not expecting any form fields");
489                 }
490             }
491         } catch(PortletException e) {
492             throw e;
493         } catch(Exception JavaDoc e) {
494             throw new PortletException(e);
495         }
496         return false;
497     }
498
499     private DatabaseConversionStatus processImport(File JavaDoc importFile, String JavaDoc type) throws PortletException, IOException JavaDoc {
500         if(type.equals("JBoss 4")) {
501             return JBoss4DatabaseConverter.convert(new FileReader JavaDoc(importFile));
502         } else if(type.equals("WebLogic 8.1")) {
503             return WebLogic81DatabaseConverter.convert(new FileReader JavaDoc(importFile));
504         } else {
505             throw new PortletException("Unknown import type '"+type+"'");
506         }
507     }
508
509     private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String JavaDoc rarPath) {
510         DeploymentManager JavaDoc mgr = PortletManager.getDeploymentManager(request);
511         try {
512             URL JavaDoc url = getRAR(request, rarPath).toURL();
513             ConnectorDeployable deployable = new ConnectorDeployable(url);
514             final DDBeanRoot JavaDoc ddBeanRoot = deployable.getDDBeanRoot();
515             String JavaDoc adapterName = null, adapterDesc = null;
516             String JavaDoc[] test = ddBeanRoot.getText("connector/display-name");
517             if(test != null && test.length > 0) {
518                 adapterName = test[0];
519             }
520             test = ddBeanRoot.getText("connector/description");
521             if(test != null && test.length > 0) {
522                 adapterDesc = test[0];
523             }
524             DDBean JavaDoc[] definitions = ddBeanRoot.getChildBean("connector/resourceadapter/outbound-resourceadapter/connection-definition");
525             List JavaDoc configs = new ArrayList JavaDoc();
526             if(definitions != null) {
527                 for (int i = 0; i < definitions.length; i++) {
528                     DDBean JavaDoc definition = definitions[i];
529                     String JavaDoc iface = definition.getText("connectionfactory-interface")[0];
530                     if(iface.equals("javax.sql.DataSource")) {
531                         DDBean JavaDoc[] beans = definition.getChildBean("config-property");
532                         for (int j = 0; j < beans.length; j++) {
533                             DDBean JavaDoc bean = beans[j];
534                             String JavaDoc name = bean.getText("config-property-name")[0].trim();
535                             String JavaDoc type = bean.getText("config-property-type")[0].trim();
536                             test = bean.getText("config-property-value");
537                             String JavaDoc value = test == null || test.length == 0 ? null : test[0].trim();
538                             test = bean.getText("description");
539                             String JavaDoc desc = test == null || test.length == 0 ? null : test[0].trim();
540                             configs.add(new ConfigParam(name, type, desc, value));
541                         }
542                     }
543                 }
544             }
545             return new ResourceAdapterParams(adapterName, adapterDesc, (ConfigParam[]) configs.toArray(new ConfigParam[configs.size()]));
546         } catch (Exception JavaDoc e) {
547             log.error("Unable to read configuration properties", e);
548             return null;
549         } finally {
550             if(mgr != null) mgr.release();
551         }
552     }
553
554     private ResourceAdapterParams loadConfigPropertiesByAbstractName(PortletRequest request, String JavaDoc abstractName) {
555         ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, new AbstractName(URI.create(abstractName)));
556         String JavaDoc dd = module.getDeploymentDescriptor();
557         DocumentBuilderFactory JavaDoc factory = XmlUtil.newDocumentBuilderFactory();
558         factory.setValidating(false);
559         factory.setNamespaceAware(true);
560         try {
561             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
562             final StringReader JavaDoc reader = new StringReader JavaDoc(dd);
563             Document JavaDoc doc = builder.parse(new InputSource JavaDoc(reader));
564             reader.close();
565             Element JavaDoc elem = doc.getDocumentElement(); // connector
566
String JavaDoc displayName = getFirstText(elem.getElementsByTagName("display-name"));
567             String JavaDoc description = getFirstText(elem.getElementsByTagName("description"));
568             elem = (Element JavaDoc) elem.getElementsByTagName("resourceadapter").item(0);
569             elem = (Element JavaDoc) elem.getElementsByTagName("outbound-resourceadapter").item(0);
570             NodeList JavaDoc defs = elem.getElementsByTagName("connection-definition");
571             List JavaDoc all = new ArrayList JavaDoc();
572             for(int i=0; i<defs.getLength(); i++) {
573                 final Element JavaDoc def = (Element JavaDoc)defs.item(i);
574                 String JavaDoc iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim();
575                 if(iface.equals("javax.sql.DataSource")) {
576                     NodeList JavaDoc configs = def.getElementsByTagName("config-property");
577                     for(int j=0; j<configs.getLength(); j++) {
578                         Element JavaDoc config = (Element JavaDoc) configs.item(j);
579                         String JavaDoc name = getFirstText(config.getElementsByTagName("config-property-name")).trim();
580                         String JavaDoc type = getFirstText(config.getElementsByTagName("config-property-type")).trim();
581                         String JavaDoc test = getFirstText(config.getElementsByTagName("config-property-value"));
582                         String JavaDoc value = test == null ? null : test.trim();
583                         test = getFirstText(config.getElementsByTagName("description"));
584                         String JavaDoc desc = test == null ? null : test.trim();
585                         all.add(new ConfigParam(name, type, desc, value));
586                     }
587                 }
588             }
589             return new ResourceAdapterParams(displayName, description, (ConfigParam[]) all.toArray(new ConfigParam[all.size()]));
590         } catch (Exception JavaDoc e) {
591             log.error("Unable to read resource adapter DD", e);
592             return null;
593         }
594     }
595
596     private String JavaDoc getFirstText(NodeList JavaDoc list) {
597         if(list.getLength() == 0) {
598             return null;
599         }
600         Element JavaDoc first = (Element JavaDoc) list.item(0);
601         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
602         NodeList JavaDoc all = first.getChildNodes();
603         for(int i=0; i<all.getLength(); i++) {
604             Node JavaDoc node = all.item(i);
605             if(node.getNodeType() == Node.TEXT_NODE) {
606                 buf.append(node.getNodeValue());
607             }
608         }
609         return buf.toString();
610     }
611
612     private void loadConnectionFactory(ActionRequest actionRequest, String JavaDoc adapterName, String JavaDoc factoryName, PoolData data) {
613         AbstractName abstractAdapterName = new AbstractName(URI.create(adapterName));
614         AbstractName abstractFactoryName = new AbstractName(URI.create(factoryName));
615         
616         ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest,abstractAdapterName);
617         JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest, abstractFactoryName);
618         data.adapterDisplayName = adapter.getDisplayName();
619         data.adapterDescription = adapter.getDescription();
620         try {
621             data.name = (String JavaDoc)abstractFactoryName.getName().get("name");
622             if(data.isGeneric()) {
623                 data.url = (String JavaDoc) factory.getConfigProperty("ConnectionURL");
624                 data.driverClass = (String JavaDoc) factory.getConfigProperty("Driver");
625                 data.user = (String JavaDoc) factory.getConfigProperty("UserName");
626                 data.password = (String JavaDoc) factory.getConfigProperty("Password");
627             } else {
628                 ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(), data.getAdapterDisplayName(), adapterName);
629                 for(int i=0; i<params.getConfigParams().length; i++) {
630                     ConfigParam cp = params.getConfigParams()[i];
631                     Object JavaDoc value = factory.getConfigProperty(cp.getName());
632                     data.properties.put("property-"+cp.getName(), value == null ? null : value.toString());
633                 }
634             }
635         } catch (Exception JavaDoc e) {
636             log.error("Unable to look up connection property", e);
637         }
638         //todo: push the lookup into ManagementHelper
639
PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManager();
640         data.minSize = Integer.toString(pool.getPartitionMinSize());
641         data.maxSize = Integer.toString(pool.getPartitionMaxSize());
642         data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds());
643         data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes());
644
645     }
646
647     protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
648         if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) {
649             return;
650         }
651         try {
652             String JavaDoc mode = renderRequest.getParameter(MODE_KEY);
653             PoolData data = new PoolData();
654             data.load(renderRequest);
655             renderRequest.setAttribute("pool", data);
656             // If not headed anywhere in particular, send to list
657
if(mode == null || mode.equals("")) {
658                 mode = LIST_MODE;
659             }
660             // If headed to list but there's an import in progress, redirect to import status
661
if(mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) {
662                 mode = IMPORT_STATUS_MODE;
663             }
664
665             if(mode.equals(LIST_MODE)) {
666                 renderList(renderRequest, renderResponse);
667             } else if(mode.equals(EDIT_MODE)) {
668                 renderEdit(renderRequest, renderResponse, data);
669             } else if(mode.equals(SELECT_RDBMS_MODE)) {
670                 renderSelectRDBMS(renderRequest, renderResponse);
671             } else if(mode.equals(DOWNLOAD_MODE)) {
672                 renderDownload(renderRequest, renderResponse);
673             } else if(mode.equals(DOWNLOAD_STATUS_MODE)) {
674                 renderDownloadStatus(renderRequest, renderResponse);
675             } else if(mode.equals(BASIC_PARAMS_MODE)) {
676                 renderBasicParams(renderRequest, renderResponse, data);
677             } else if(mode.equals(CONFIRM_URL_MODE)) {
678                 renderConfirmURL(renderRequest, renderResponse);
679             } else if(mode.equals(TEST_CONNECTION_MODE)) {
680                 renderTestConnection(renderRequest, renderResponse);
681             } else if(mode.equals(SHOW_PLAN_MODE)) {
682                 renderPlan(renderRequest, renderResponse, data);
683             } else if(mode.equals(IMPORT_START_MODE)) {
684                 renderImportUploadForm(renderRequest, renderResponse);
685             } else if(mode.equals(IMPORT_STATUS_MODE)) {
686                 renderImportStatus(renderRequest, renderResponse);
687             } else if(mode.equals(USAGE_MODE)) {
688                 renderUsage(renderRequest, renderResponse);
689             }
690         } catch (Throwable JavaDoc e) {
691             log.error("Unable to render portlet", e);
692         }
693     }
694
695     private void renderUsage(RenderRequest request, RenderResponse response) throws IOException JavaDoc, PortletException {
696         usageView.include(request, response);
697     }
698
699     private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException JavaDoc, PortletException {
700         request.setAttribute("status", getImportStatus(request));
701         populatePoolList(request);
702         importStatusView.include(request, response);
703     }
704
705     private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException JavaDoc, PortletException {
706         request.setAttribute("from", request.getParameter("from"));
707         importUploadView.include(request, response);
708     }
709
710     private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
711         populatePoolList(renderRequest);
712         listView.include(renderRequest, renderResponse);
713     }
714
715     private void populatePoolList(PortletRequest renderRequest) {
716         ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource");
717         List JavaDoc list = new ArrayList JavaDoc();
718         for (int i = 0; i < modules.length; i++) {
719             ResourceAdapterModule module = modules[i];
720             AbstractName moduleName = PortletManager.getManagementHelper(renderRequest).getNameFor(module);
721             
722             JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module, "javax.sql.DataSource");
723             for (int j = 0; j < databases.length; j++) {
724                 JCAManagedConnectionFactory db = databases[j];
725                 AbstractName dbName = PortletManager.getManagementHelper(renderRequest).getNameFor(db);
726                 list.add(new ConnectionPool(moduleName, dbName, (String JavaDoc)dbName.getName().get(NameFactory.J2EE_NAME), ((GeronimoManagedBean)db).getState()));
727             }
728         }
729         Collections.sort(list);
730         renderRequest.setAttribute("pools", list);
731     }
732
733     private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException JavaDoc, PortletException {
734         if(data.abstractName == null || data.abstractName.equals("")) {
735             loadDriverJARList(renderRequest);
736         }
737         if(!data.isGeneric()) {
738             ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(), data.getAdapterDisplayName(), renderRequest.getParameter("adapterAbstractName"));
739             data.adapterDisplayName = params.getDisplayName();
740             data.adapterDescription = params.getDescription();
741             Map JavaDoc map = new HashMap JavaDoc();
742             boolean more = false;
743             for (int i = 0; i < params.getConfigParams().length; i++) {
744                 ConfigParam param = params.getConfigParams()[i];
745                 if(!data.properties.containsKey("property-"+param.getName())) {
746                     data.properties.put("property-"+param.getName(), param.getDefaultValue());
747                     more = true;
748                 }
749                 map.put("property-"+param.getName(), param);
750             }
751             if(more) {
752                 data.loadPropertyNames();
753             }
754             renderRequest.setAttribute("ConfigParams", map);
755         }
756         editView.include(renderRequest, renderResponse);
757     }
758
759     private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
760         renderRequest.setAttribute("databases", getAllDrivers(renderRequest));
761         selectRDBMSView.include(renderRequest, renderResponse);
762     }
763
764     private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
765         renderRequest.setAttribute("drivers", getDriverInfo(renderRequest));
766         downloadView.include(renderRequest, renderResponse);
767     }
768
769     private void renderDownloadStatus(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
770         downloadStatusView.include(renderRequest, renderResponse);
771     }
772
773     private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException JavaDoc, PortletException {
774         loadDriverJARList(renderRequest);
775         // Make sure all properties available for the DB are listed
776
DatabaseDriver info = getDatabaseInfo(renderRequest, data);
777         if(info != null) {
778             String JavaDoc[] params = info.getURLParameters();
779             for (int i = 0; i < params.length; i++) {
780                 String JavaDoc param = params[i];
781                 final String JavaDoc key = "urlproperty-"+param;
782                 if(!data.getUrlProperties().containsKey(key)) {
783                     data.getUrlProperties().put(key, param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? new Integer JavaDoc(info.getDefaultPort()) : null);
784                 }
785             }
786         }
787         // Pass on errors
788
renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError"));
789
790         basicParamsView.include(renderRequest, renderResponse);
791     }
792
793     private void loadDriverJARList(RenderRequest renderRequest) {
794         // List the available JARs
795
List JavaDoc list = new ArrayList JavaDoc();
796         ListableRepository[] repos = PortletManager.getCurrentServer(renderRequest).getRepositories();
797         for (int i = 0; i < repos.length; i++) {
798             ListableRepository repo = repos[i];
799
800             SortedSet JavaDoc artifacts = repo.list();
801             outer:
802             for (Iterator JavaDoc iterator = artifacts.iterator(); iterator.hasNext();) {
803                 Artifact artifact = (Artifact) iterator.next();
804                 String JavaDoc test = artifact.toString();
805                 // todo should only test groupId and should check for long (org.apache.geronimo) and short form
806
for (int k = 0; k < SKIP_ENTRIES_WITH.length; k++) {
807                     String JavaDoc skip = SKIP_ENTRIES_WITH[k];
808                     if(test.indexOf(skip) > -1) {
809                         continue outer;
810                     }
811                 }
812                 list.add(test);
813             }
814         }
815         Collections.sort(list);
816         renderRequest.setAttribute("availableJars", list);
817     }
818
819     private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
820         confirmURLView.include(renderRequest, renderResponse);
821     }
822
823     private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException JavaDoc, PortletException {
824         // Pass on results
825
renderRequest.setAttribute("connectResult", renderRequest.getParameter("connectResult"));
826         renderRequest.setAttribute("connectError", renderRequest.getPortletSession().getAttribute("connectError"));
827         testConnectionView.include(renderRequest, renderResponse);
828     }
829
830     private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException JavaDoc, PortletException {
831         // Pass on results
832
renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan"));
833         // Digest the RAR URI
834
String JavaDoc path = PortletManager.getRepositoryEntry(renderRequest, data.getRarPath()).getPath();
835         String JavaDoc base = PortletManager.getCurrentServer(renderRequest).getServerInfo().getCurrentBaseDirectory();
836         if(base != null && path.startsWith(base)) {
837             path = path.substring(base.length());
838             if(path.startsWith("/")) {
839                 path = path.substring(1);
840             }
841         } else {
842             int pos = path.lastIndexOf('/');
843             path = path.substring(pos+1);
844         }
845         renderRequest.setAttribute("rarRelativePath", path);
846
847         planView.include(renderRequest, renderResponse);
848     }
849
850     private static String JavaDoc attemptConnect(PortletRequest request, PoolData data) throws SQLException JavaDoc, IllegalAccessException JavaDoc, InstantiationException JavaDoc {
851         Class JavaDoc driverClass = attemptDriverLoad(request, data);
852         Driver JavaDoc driver = (Driver JavaDoc) driverClass.newInstance();
853         if(driver.acceptsURL(data.url)) {
854             Properties JavaDoc props = new Properties JavaDoc();
855             if(data.user != null) {
856                 props.put("user", data.user);
857             }
858             if(data.password != null) {
859                 props.put("password", data.password);
860             }
861             Connection JavaDoc con = null;
862             try {
863                 con = driver.connect(data.url, props);
864                 final DatabaseMetaData JavaDoc metaData = con.getMetaData();
865                 return metaData.getDatabaseProductName()+" "+metaData.getDatabaseProductVersion();
866             } finally {
867                 if(con != null) try{con.close();}catch(SQLException JavaDoc e) {}
868             }
869         } else throw new SQLException JavaDoc("Driver "+data.getDriverClass()+" does not accept URL "+data.url);
870     }
871
872     private static String JavaDoc save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) {
873         ImportStatus status = getImportStatus(request);
874         if(data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool
875
data.name = data.name.replaceAll("\\s", "");
876             DeploymentManager JavaDoc mgr = PortletManager.getDeploymentManager(request);
877             try {
878                 File JavaDoc rarFile = getRAR(request, data.getRarPath());
879                 ConnectorDeployable deployable = new ConnectorDeployable(rarFile.toURL());
880                 DeploymentConfiguration JavaDoc config = mgr.createConfiguration(deployable);
881                 final DDBeanRoot JavaDoc ddBeanRoot = deployable.getDDBeanRoot();
882                 Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot);
883                 ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean(ddBeanRoot.getChildBean(root.getXpaths()[0])[0]);
884                 
885                 EnvironmentData environment = new EnvironmentData();
886                 connector.setEnvironment(environment);
887                 org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact();
888                 environment.setConfigId(configId);
889                 configId.setGroupId("console.dbpool");
890                 String JavaDoc artifactId = data.name;
891                 if(artifactId.indexOf('/') != -1) {
892                     // slash in artifact-id results in invalid configuration-id and leads to deployment errors
893
artifactId = artifactId.replaceAll("/", "%2F");
894                 }
895                 configId.setArtifactId(artifactId);
896                 configId.setVersion("1.0");
897                 configId.setType("rar");
898
899                 String JavaDoc[] jars = data.getJars();
900                 int length = jars[jars.length - 1].length() ==0? jars.length -1: jars.length;
901                 org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length];
902                 for (int i=0; i<dependencies.length; i++) {
903                     dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact();
904                 }
905                 environment.setDependencies(dependencies);
906                 for (int i=0; i<dependencies.length; i++) {
907                         Artifact tmp = Artifact.create(jars[i]);
908                         dependencies[i].setGroupId(tmp.getGroupId());
909                         dependencies[i].setArtifactId(tmp.getArtifactId());
910                         dependencies[i].setVersion(tmp.getVersion().toString());
911                         dependencies[i].setType(tmp.getType());
912                 }
913                
914                 ResourceAdapter adapter = connector.getResourceAdapter()[0];
915                 ConnectionDefinition definition = new ConnectionDefinition();
916                 adapter.setConnectionDefinition(new ConnectionDefinition[]{definition});
917                 definition.setConnectionFactoryInterface("javax.sql.DataSource");
918                 ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance();
919                 definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance});
920                 instance.setName(data.getName());
921                 ConfigPropertySetting[] settings = instance.getConfigPropertySetting();
922                 if(data.isGeneric()) { // it's a generic TranQL JDBC pool
923
for (int i = 0; i < settings.length; i++) {
924                         ConfigPropertySetting setting = settings[i];
925                         if(setting.getName().equals("UserName")) {
926                             setting.setValue(data.user);
927                         } else if(setting.getName().equals("Password")) {
928                             setting.setValue(data.password);
929                         } else if(setting.getName().equals("ConnectionURL")) {
930                             setting.setValue(data.url);
931                         } else if(setting.getName().equals("Driver")) {
932                             setting.setValue(data.driverClass);
933                         }
934                     }
935                 } else { // it's an XA driver or non-TranQL RA
936
for (int i = 0; i < settings.length; i++) {
937                         ConfigPropertySetting setting = settings[i];
938                         String JavaDoc value = (String JavaDoc) data.properties.get("property-"+setting.getName());
939                         setting.setValue(value == null ? "" : value);
940                     }
941                 }
942                 ConnectionManager manager = instance.getConnectionManager();
943                 manager.setTransactionLocal(true);
944                 SinglePool pool = new SinglePool();
945                 manager.setPoolSingle(pool);
946                 pool.setMatchOne(true);
947                 // Max Size needs to be set before the minimum. This is because
948
// the connection manager will constrain the minimum based on the
949
// current maximum value in the pool. We might consider adding a
950
// setPoolConstraints method to allow specifying both at the same time.
951
if(data.maxSize != null && !data.maxSize.equals("")) {
952                     pool.setMaxSize(new Integer JavaDoc(data.maxSize));
953                 }
954                 if(data.minSize != null && !data.minSize.equals("")) {
955                     pool.setMinSize(new Integer JavaDoc(data.minSize));
956                 }
957                 if(data.blockingTimeout != null && !data.blockingTimeout.equals("")) {
958                     pool.setBlockingTimeoutMillis(new Integer JavaDoc(data.blockingTimeout));
959                 }
960                 if(data.idleTimeout != null && !data.idleTimeout.equals("")) {
961                     pool.setIdleTimeoutMinutes(new Integer JavaDoc(data.idleTimeout));
962                 }
963                 
964                 if(planOnly) {
965                     ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
966                     config.save(out);
967                     out.close();
968                     return new String JavaDoc(out.toByteArray(), "US-ASCII");
969                 } else {
970                     File JavaDoc tempFile = File.createTempFile("console-deployment",".xml");
971                     tempFile.deleteOnExit();
972                     log.debug("Writing database pool deployment plan to "+tempFile.getAbsolutePath());
973                     BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(tempFile));
974                     config.save(out);
975                     out.flush();
976                     out.close();
977                     Target JavaDoc[] targets = mgr.getTargets();
978                     ProgressObject JavaDoc po = mgr.distribute(targets, rarFile, tempFile);
979                     waitForProgress(po);
980                     if(po.getDeploymentStatus().isCompleted()) {
981                         TargetModuleID JavaDoc[] ids = po.getResultTargetModuleIDs();
982                         po = mgr.start(ids);
983                         waitForProgress(po);
984                         if(po.getDeploymentStatus().isCompleted()) {
985                             ids = po.getResultTargetModuleIDs();
986                             if(status != null) {
987                                 status.getCurrentPool().setName(data.getName());
988                                 status.getCurrentPool().setConfigurationName(ids[0].getModuleID());
989                                 status.getCurrentPool().setFinished(true);
990                                 response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
991                             }
992                             
993                             log.info("Deployment completed successfully!");
994                         }
995                     } else if(po.getDeploymentStatus().isFailed()) {
996                         data.deployError = "Unable to deploy: " + data.name;
997                         response.setRenderParameter(MODE_KEY, EDIT_MODE);
998                         log.info("Deployment Failed!");
999                     }
1000                }
1001            } catch (Exception JavaDoc e) {
1002                log.error("Unable to save connection pool", e);
1003            } finally {
1004                if(mgr != null) mgr.release();
1005            }
1006        } else { // We're saving updates to an existing pool
1007
if(planOnly) {
1008                throw new UnsupportedOperationException JavaDoc("Can't update a plan for an existing deployment");
1009            }
1010            try {
1011                JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(request, new AbstractName(URI.create(data.getAbstractName())));
1012                if(data.isGeneric()) {
1013                    factory.setConfigProperty("ConnectionURL", data.getUrl());
1014                    factory.setConfigProperty("UserName", data.getUser());
1015                    factory.setConfigProperty("Password", data.getPassword());
1016                } else {
1017                    for (Iterator JavaDoc it = data.getProperties().entrySet().iterator(); it.hasNext();) {
1018                        Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
1019                        factory.setConfigProperty(((String JavaDoc) entry.getKey()).substring("property-".length()), entry.getValue());
1020                    }
1021                }
1022                //todo: push the lookup into ManagementHelper
1023
PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManager();
1024                pool.setPartitionMinSize(data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize));
1025                pool.setPartitionMaxSize(data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize));
1026                pool.setBlockingTimeoutMilliseconds(data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt(data.blockingTimeout));
1027                pool.setIdleTimeoutMinutes(data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt(data.idleTimeout));
1028            } catch (Exception JavaDoc e) {
1029                log.error("Unable to save connection pool", e);
1030            }
1031        }
1032        return null;
1033    }
1034
1035    private static void waitForProgress(ProgressObject JavaDoc po) {
1036        while(po.getDeploymentStatus().isRunning()) {
1037            try {
1038                Thread.sleep(100);
1039            } catch (InterruptedException JavaDoc e) {
1040                e.printStackTrace();
1041            }
1042        }
1043    }
1044
1045    private static ImportStatus getImportStatus(PortletRequest request) {
1046        return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus");
1047    }
1048
1049    private static File JavaDoc getRAR(PortletRequest request, String JavaDoc rarPath) {
1050        org.apache.geronimo.kernel.repository.Artifact artifact = org.apache.geronimo.kernel.repository.Artifact.create(rarPath);
1051        ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();
1052        for (int i = 0; i < repos.length; i++) {
1053            ListableRepository repo = repos[i];
1054            // if the artifact is not fully resolved then try to resolve it
1055
if (!artifact.isResolved()) {
1056                SortedSet JavaDoc results = repo.list(artifact);
1057                if (!results.isEmpty()) {
1058                    artifact = (org.apache.geronimo.kernel.repository.Artifact) results.first();
1059                }
1060            }
1061            File JavaDoc url = repo.getLocation(artifact);
1062            if (url != null) {
1063                if (url.exists() && url.canRead() && !url.isDirectory()) {
1064                    return url;
1065                }
1066            }
1067        }
1068        return null;
1069    }
1070
1071    /**
1072     * WARNING: This method relies on having access to the same repository
1073     * URLs as the server uses.
1074     */

1075    private static Class JavaDoc attemptDriverLoad(PortletRequest request, PoolData data) {
1076        List JavaDoc list = new ArrayList JavaDoc();
1077        try {
1078            String JavaDoc[] jars = data.getJars();
1079            if(jars == null) {
1080                log.error("Driver load failed since no jar files were selected.");
1081                return null;
1082            }
1083            ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();
1084
1085            for (int i = 0; i < jars.length; i++) {
1086                org.apache.geronimo.kernel.repository.Artifact artifact = org.apache.geronimo.kernel.repository.Artifact.create(jars[i]);
1087                for (int j = 0; j < repos.length; j++) {
1088                    ListableRepository repo = repos[j];
1089                    File JavaDoc url = repo.getLocation(artifact);
1090                    if (url != null) {
1091                        list.add(url.toURL());
1092                    }
1093                }
1094            }
1095            URLClassLoader JavaDoc loader = new URLClassLoader JavaDoc((URL JavaDoc[]) list.toArray(new URL JavaDoc[list.size()]), DatabasePoolPortlet.class.getClassLoader());
1096            try {
1097                return loader.loadClass(data.driverClass);
1098            } catch (ClassNotFoundException JavaDoc e) {
1099                return null;
1100            }
1101        } catch (Exception JavaDoc e) {
1102            e.printStackTrace();
1103            return null;
1104        }
1105    }
1106
1107    private static String JavaDoc populateURL(String JavaDoc url, String JavaDoc[] keys, Map JavaDoc properties) {
1108        for (int i = 0; i < keys.length; i++) {
1109            String JavaDoc key = keys[i];
1110            String JavaDoc value = (String JavaDoc) properties.get("urlproperty-"+key);
1111            if(value == null || value.equals("")) {
1112                int begin = url.indexOf("{"+key+"}");
1113                int end = begin + key.length() + 2;
1114                for(int j=begin-1; j>=0; j--) {
1115                    char c = url.charAt(j);
1116                    if(c == ';' || c == ':') {
1117                        begin = j;
1118                        break;
1119                    } else if(c == '/') {
1120                        if(url.length() > end && url.charAt(end) == '/') {
1121                            begin = j; // Don't leave // if foo is null for /<foo>/
1122
}
1123                        break;
1124                    }
1125                }
1126                url = url.substring(0, begin)+url.substring(end);
1127            } else {
1128                if(value.indexOf('\\') != -1 || value.indexOf('$') != -1) {
1129                    // value contains backslash or dollar sign and needs preprocessing for replaceAll to work properly
1130
StringBuffer JavaDoc temp = new StringBuffer JavaDoc();
1131                    char[] valueChars = value.toCharArray();
1132                    for(int j = 0; j < valueChars.length; ++j) {
1133                        if(valueChars[j] == '\\' || valueChars[j] == '$') {
1134                            temp.append('\\');
1135                        }
1136                        temp.append(valueChars[j]);
1137                    }
1138                    value = temp.toString();
1139                }
1140                url = url.replaceAll("\\{"+key+"\\}", value);
1141            }
1142        }
1143        return url;
1144    }
1145
1146    
1147    private static DatabaseDriver[] getAllDrivers(PortletRequest request) {
1148        DatabaseDriver[] result = (DatabaseDriver[]) PortletManager.getGBeansImplementing(request, DatabaseDriver.class);
1149        Arrays.sort(result, new Comparator JavaDoc() {
1150            public int compare(Object JavaDoc o1, Object JavaDoc o2) {
1151                String JavaDoc name1 = ((DatabaseDriver) o1).getName();
1152                String JavaDoc name2 = ((DatabaseDriver) o2).getName();
1153                if (name1.equals("Other")) name1 = "zzzOther";
1154                if (name2.equals("Other")) name2 = "zzzOther";
1155                return name1.compareTo(name2);
1156            }
1157        });
1158        return result;
1159    }
1160        
1161    private static DatabaseDriver getDatabaseInfo(PortletRequest request, PoolData data) {
1162        DatabaseDriver info = null;
1163        DatabaseDriver[] all = getAllDrivers(request);
1164        for (int i = 0; i < all.length; i++) {
1165            DatabaseDriver next = all[i];
1166            if (next.getName().equals(data.getDbtype())) {
1167                info = next;
1168                break;
1169            }
1170        }
1171        return info;
1172    }
1173
1174    private static DatabaseDriver getDatabaseInfoFromDriver(PortletRequest request, PoolData data) {
1175        DatabaseDriver info = null;
1176        DatabaseDriver[] all = getAllDrivers(request);
1177        for (int i = 0; i < all.length; i++) {
1178            DatabaseDriver next = all[i];
1179            if (next.getDriverClassName()!=null && next.getDriverClassName().equals(data.getDriverClass())) {
1180                info = next;
1181                break;
1182            }
1183        }
1184        return info;
1185    }
1186
1187    public static class PoolData implements Serializable JavaDoc {
1188        private static final long serialVersionUID = 1L;
1189        private String JavaDoc name;
1190        private String JavaDoc dbtype;
1191        private String JavaDoc user;
1192        private String JavaDoc password;
1193        private Map JavaDoc properties = new HashMap JavaDoc(); // Configuration for non-Generic drivers
1194
private Map JavaDoc urlProperties = new HashMap JavaDoc(); // URL substitution for Generic drivers
1195
private Map JavaDoc propertyNames; //todo: store these in the ConfigParam instead
1196
private String JavaDoc driverClass;
1197        private String JavaDoc url;
1198        private String JavaDoc urlPrototype;
1199        private String JavaDoc[] jars;
1200        private String JavaDoc minSize;
1201        private String JavaDoc maxSize;
1202        private String JavaDoc blockingTimeout;
1203        private String JavaDoc idleTimeout;
1204        private String JavaDoc abstractName;
1205        private String JavaDoc adapterDisplayName;
1206        private String JavaDoc adapterDescription;
1207        private String JavaDoc rarPath;
1208        private String JavaDoc importSource;
1209        private Map JavaDoc abstractNameMap; // generated as needed, don't need to read/write it
1210
private String JavaDoc deployError;
1211
1212        public void load(PortletRequest request) {
1213            name = request.getParameter("name");
1214            if(name != null && name.equals("")) name = null;
1215            driverClass = request.getParameter("driverClass");
1216            if(driverClass != null && driverClass.equals("")) driverClass = null;
1217            dbtype = request.getParameter("dbtype");
1218            if(dbtype != null && dbtype.equals("")) dbtype = null;
1219            user = request.getParameter("user");
1220            if(user != null && user.equals("")) user = null;
1221            password = request.getParameter("password");
1222            if(password != null && password.equals("")) password = null;
1223            url = request.getParameter("url");
1224            if(url != null && url.equals("")) {
1225                url = null;
1226            } else if(url != null && url.startsWith("URLENCODED")) {
1227                try {
1228                    url = URLDecoder.decode(url.substring(10), "UTF-8");
1229                } catch (UnsupportedEncodingException JavaDoc e) {
1230                    throw new RuntimeException JavaDoc("Unable to decode URL", e);
1231                } catch(IllegalArgumentException JavaDoc e) { // not encoded after all??
1232
url = url.substring(10);
1233                }
1234            }
1235            urlPrototype = request.getParameter("urlPrototype");
1236            if(urlPrototype != null && urlPrototype.equals("")) urlPrototype = null;
1237            jars = request.getParameterValues("jars");
1238            minSize = request.getParameter("minSize");
1239            if(minSize != null && minSize.equals("")) minSize = null;
1240            maxSize = request.getParameter("maxSize");
1241            if(maxSize != null && maxSize.equals("")) maxSize = null;
1242            blockingTimeout = request.getParameter("blockingTimeout");
1243            if(blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null;
1244            idleTimeout = request.getParameter("idleTimeout");
1245            if(idleTimeout != null && idleTimeout.equals("")) idleTimeout = null;
1246            abstractName = request.getParameter("abstractName");
1247            if(abstractName != null && abstractName.equals("")) abstractName = null;
1248            adapterDisplayName = request.getParameter("adapterDisplayName");
1249            if(adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null;
1250            adapterDescription = request.getParameter("adapterDescription");
1251            if(adapterDescription != null && adapterDescription.equals("")) adapterDescription = null;
1252            rarPath = request.getParameter("rarPath");
1253            if(rarPath != null && rarPath.equals("")) rarPath = null;
1254            importSource = request.getParameter("importSource");
1255            if(importSource != null && importSource.equals("")) importSource = null;
1256            Map JavaDoc map = request.getParameterMap();
1257            propertyNames = new HashMap JavaDoc();
1258            for (Iterator JavaDoc it = map.keySet().iterator(); it.hasNext();) {
1259                String JavaDoc key = (String JavaDoc) it.next();
1260                if(key.startsWith("urlproperty-")) {
1261                    urlProperties.put(key, request.getParameter(key));
1262                } else if(key.startsWith("property-")) {
1263                    properties.put(key, request.getParameter(key));
1264                    propertyNames.put(key, getPropertyName(key));
1265                }
1266            }
1267            deployError = request.getParameter("deployError");
1268            if(deployError != null && deployError.equals("")) deployError = null;
1269        }
1270
1271        public void loadPropertyNames() {
1272            propertyNames = new HashMap JavaDoc();
1273            for (Iterator JavaDoc it = properties.keySet().iterator(); it.hasNext();) {
1274                String JavaDoc key = (String JavaDoc) it.next();
1275                propertyNames.put(key, getPropertyName(key));
1276            }
1277        }
1278
1279        private static String JavaDoc getPropertyName(String JavaDoc key) {
1280            int pos = key.indexOf('-');
1281            key = Character.toUpperCase(key.charAt(pos+1))+key.substring(pos+2);
1282            StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1283            pos = 0;
1284            for(int i=1; i<key.length(); i++) {
1285                if(Character.isUpperCase(key.charAt(i))) {
1286                    if(Character.isUpperCase(key.charAt(i-1))) { // ongoing capitalized word
1287

1288                    } else { // start of a new word
1289
buf.append(key.substring(pos, i)).append(" ");
1290                        pos = i;
1291                    }
1292                } else {
1293                    if(Character.isUpperCase(key.charAt(i-1)) && i-pos > 1) { // first lower-case after a series of caps
1294
buf.append(key.substring(pos, i-1)).append(" ");
1295                        pos = i-1;
1296                    }
1297                }
1298            }
1299            buf.append(key.substring(pos));
1300            return buf.toString();
1301        }
1302
1303        public void store(ActionResponse response) {
1304            if(name != null) response.setRenderParameter("name", name);
1305            if(dbtype != null) response.setRenderParameter("dbtype", dbtype);
1306            if(driverClass != null) response.setRenderParameter("driverClass", driverClass);
1307            if(user != null) response.setRenderParameter("user", user);
1308            if(password != null) response.setRenderParameter("password", password);
1309            if(url != null) { // attempt to work around Pluto/Tomcat error with ; in a stored value
1310
try {
1311                    response.setRenderParameter("url", "URLENCODED"+URLEncoder.encode(url, "UTF-8"));
1312                } catch (UnsupportedEncodingException JavaDoc e) {
1313                    throw new RuntimeException JavaDoc("Unable to encode URL", e);
1314                }
1315            }
1316            if(urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype);
1317            if(jars != null) response.setRenderParameter("jars", jars);
1318            if(minSize != null) response.setRenderParameter("minSize", minSize);
1319            if(maxSize != null) response.setRenderParameter("maxSize", maxSize);
1320            if(blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout);
1321            if(idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout);
1322            if(abstractName != null) response.setRenderParameter("abstractName", abstractName);
1323            if(adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName);
1324            if(adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription);
1325            if(importSource != null) response.setRenderParameter("importSource", importSource);
1326            if(rarPath != null) response.setRenderParameter("rarPath", rarPath);
1327            for (Iterator JavaDoc it = urlProperties.entrySet().iterator(); it.hasNext();) {
1328                Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
1329                if(entry.getValue() != null) {
1330                    response.setRenderParameter((String JavaDoc)entry.getKey(), (String JavaDoc)entry.getValue());
1331                }
1332            }
1333            for (Iterator JavaDoc it = properties.entrySet().iterator(); it.hasNext();) {
1334                Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
1335                if(entry.getValue() != null) {
1336                    response.setRenderParameter((String JavaDoc)entry.getKey(), (String JavaDoc)entry.getValue());
1337                }
1338            }
1339            if(deployError != null) response.setRenderParameter("deployError", deployError);
1340        }
1341
1342        public String JavaDoc getName() {
1343            return name;
1344        }
1345
1346        public String JavaDoc getDbtype() {
1347            return dbtype;
1348        }
1349
1350        public String JavaDoc getUser() {
1351            return user;
1352        }
1353
1354        public String JavaDoc getPassword() {
1355            return password;
1356        }
1357
1358        public Map JavaDoc getProperties() {
1359            return properties;
1360        }
1361
1362        public Map JavaDoc getPropertyNames() {
1363            return propertyNames;
1364        }
1365
1366        public Map JavaDoc getUrlProperties() {
1367            return urlProperties;
1368        }
1369
1370        public String JavaDoc getUrl() {
1371            return url;
1372        }
1373
1374        public String JavaDoc[] getJars() {
1375            return jars;
1376        }
1377
1378        public String JavaDoc getMinSize() {
1379            return minSize;
1380        }
1381
1382        public String JavaDoc getMaxSize() {
1383            return maxSize;
1384        }
1385
1386        public String JavaDoc getBlockingTimeout() {
1387            return blockingTimeout;
1388        }
1389
1390        public String JavaDoc getIdleTimeout() {
1391            return idleTimeout;
1392        }
1393
1394        public String JavaDoc getDriverClass() {
1395            return driverClass;
1396        }
1397
1398        public String JavaDoc getUrlPrototype() {
1399            return urlPrototype;
1400        }
1401
1402        public String JavaDoc getAbstractName() {
1403            return abstractName;
1404        }
1405
1406        public String JavaDoc getAdapterDisplayName() {
1407            return adapterDisplayName;
1408        }
1409
1410        public String JavaDoc getAdapterDescription() {
1411            return adapterDescription;
1412        }
1413
1414        public String JavaDoc getRarPath() {
1415            return rarPath;
1416        }
1417
1418        public boolean isGeneric() {
1419            //todo: is there any better way to tell?
1420
return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter");
1421        }
1422
1423        public String JavaDoc getImportSource() {
1424            return importSource;
1425        }
1426
1427        public Map JavaDoc getAbstractNameMap() {
1428            if(abstractName == null) return Collections.EMPTY_MAP;
1429            if(abstractNameMap != null) return abstractNameMap;
1430            AbstractName name = new AbstractName(URI.create(abstractName));
1431            abstractNameMap = new HashMap JavaDoc(name.getName());
1432            abstractNameMap.put("domain", name.getObjectName().getDomain());
1433            abstractNameMap.put("groupId", name.getArtifact().getGroupId());
1434            abstractNameMap.put("artifactId", name.getArtifact().getArtifactId());
1435            abstractNameMap.put("type", name.getArtifact().getType());
1436            abstractNameMap.put("version", name.getArtifact().getVersion().toString());
1437            return abstractNameMap;
1438        }
1439        
1440        public String JavaDoc getDeployError() {
1441            return deployError;
1442        }
1443    }
1444
1445    public static class ConnectionPool implements Serializable JavaDoc, Comparable JavaDoc {
1446        private static final long serialVersionUID = 1L;
1447        private final String JavaDoc adapterAbstractName;
1448        private final String JavaDoc factoryAbstractName;
1449        private final String JavaDoc name;
1450        private final String JavaDoc parentName;
1451        private final int state;
1452
1453        public ConnectionPool(AbstractName adapterAbstractName, AbstractName factoryAbstractName, String JavaDoc name, int state) {
1454            this.adapterAbstractName = adapterAbstractName.toURI().toString();
1455            String JavaDoc parent = (String JavaDoc)adapterAbstractName.getName().get(NameFactory.J2EE_APPLICATION);
1456            if(parent != null && parent.equals("null")) {
1457                parent = null;
1458            }
1459            parentName = parent;
1460            this.factoryAbstractName = factoryAbstractName.toURI().toString();
1461            this.name = name;
1462            this.state = state;
1463        }
1464
1465        public String JavaDoc getAdapterAbstractName() {
1466            return adapterAbstractName;
1467        }
1468
1469        public String JavaDoc getFactoryAbstractName() {
1470            return factoryAbstractName;
1471        }
1472
1473        public String JavaDoc getName() {
1474            return name;
1475        }
1476
1477        public String JavaDoc getParentName() {
1478            return parentName;
1479        }
1480
1481        public int getState() {
1482            return state;
1483        }
1484
1485        public String JavaDoc getStateName() {
1486            return State.toString(state);
1487        }
1488
1489        public int compareTo(Object JavaDoc o) {
1490            final ConnectionPool pool = (ConnectionPool)o;
1491            int names = name.compareTo(pool.name);
1492            if(parentName == null) {
1493                if(pool.parentName == null) {
1494                    return names;
1495                } else {
1496                    return -1;
1497                }
1498            } else {
1499                if(pool.parentName == null) {
1500                    return 1;
1501                } else {
1502                    int test = parentName.compareTo(pool.parentName);
1503                    if(test != 0) {
1504                        return test;
1505                    } else {
1506                        return names;
1507                    }
1508                }
1509            }
1510        }
1511    }
1512
1513    public static class ResourceAdapterParams {
1514        private String JavaDoc displayName;
1515        private String JavaDoc description;
1516        private ConfigParam[] configParams;
1517
1518        public ResourceAdapterParams(String JavaDoc displayName, String JavaDoc description, ConfigParam[] configParams) {
1519            this.displayName = displayName;
1520            this.description = description;
1521            this.configParams = configParams;
1522        }
1523
1524        public String JavaDoc getDisplayName() {
1525            return displayName;
1526        }
1527
1528        public String JavaDoc getDescription() {
1529            return description;
1530        }
1531
1532        public ConfigParam[] getConfigParams() {
1533            return configParams;
1534        }
1535    }
1536
1537    public static class ConfigParam {
1538        private String JavaDoc name;
1539        private String JavaDoc type;
1540        private String JavaDoc description;
1541        private String JavaDoc defaultValue;
1542
1543        public ConfigParam(String JavaDoc name, String JavaDoc type, String JavaDoc description, String JavaDoc defaultValue) {
1544            this.name = name;
1545            this.type = type;
1546            this.description = description;
1547            this.defaultValue = defaultValue;
1548        }
1549
1550        public String JavaDoc getName() {
1551            return name;
1552        }
1553
1554        public String JavaDoc getType() {
1555            return type;
1556        }
1557
1558        public String JavaDoc getDescription() {
1559            return description;
1560        }
1561
1562        public String JavaDoc getDefaultValue() {
1563            return defaultValue;
1564        }
1565    }
1566}
1567
Popular Tags